mpesa-servc
v1.0.0
Published
M-Pesa payment service with comprehensive API integration and certificate-based security
Maintainers
Readme
Secure M-Pesa Service - Updated Implementation
Overview
This is a secure Node.js service for integrating with Safaricom M-Pesa APIs, now fully aligned with official documentation and enhanced with certificate-based security.
New Features Added
1. B2Pochi API Support
- Complete implementation of B2Pochi API for payments to customer business wallets (Pochi La Biashara)
- Dedicated controller and service methods
- Proper validation and error handling
2. Certificate-Based Password Encryption
- Integration with certificate files from
certfolder - Automatic password encryption using RSA PKCS1 padding
- Support for both sandbox and production certificates
- Certificate validation utilities
3. Enhanced B2B Operations
- BusinessPayBill endpoint for paying bills from business account
- BusinessBuyGoods endpoint for paying to till numbers
- Proper command ID validation
- Enhanced error handling
4. Improved B2C Operations
- Dedicated endpoints for different payment types:
- SalaryPayment - Employee salary disbursements
- BusinessPayment - Standard business to customer payments
- PromotionPayment - Promotional payments with congratulatory messages
5. Enhanced C2B API (v2)
- Updated to use official v2 endpoints
- Proper simulation for both buy goods and pay bill
- Enhanced validation with correct command IDs
- Improved callback handling
6. Advanced Transaction Operations
- Query transactions by receipt number
- Query by originator conversation ID
- Enhanced status checking with proper parameters
- Improved reversal functionality
API Endpoints
Payment Methods
# Phone Payment
POST /api/mpesa/payments/phone
# Pochi Payment
POST /api/mpesa/payments/pochi
# Till Payment
POST /api/mpesa/payments/till
# Paybill Payment
POST /api/mpesa/payments/paybill
# Customer Buy Goods Online
POST /api/mpesa/payments/buy-goods-online
# Customer Pay Bill Online
POST /api/mpesa/payments/pay-bill-onlineSTK Push
# Initiate STK Push
POST /api/mpesa/stkpush/initiate
# Query STK Push Status
GET /api/mpesa/stkpush/query/:checkoutRequestIDB2B Operations
# Generic B2B Transfer
POST /api/mpesa/b2b/transfer
# Business Pay Bill
POST /api/mpesa/b2b/business-pay-bill
# Business Buy Goods
POST /api/mpesa/b2b/business-buy-goodsB2Pochi Operations (NEW)
# B2Pochi Payment
POST /api/mpesa/b2pochi/paymentB2C Operations
# Generic B2C Payment
POST /api/mpesa/b2c/payment
# Salary Payment
POST /api/mpesa/b2c/salary
# Business Payment
POST /api/mpesa/b2c/business
# Promotion Payment
POST /api/mpesa/b2c/promotionC2B Operations
# Register C2B URLs
POST /api/mpesa/c2b/register
# Simulate C2B Payment
POST /api/mpesa/c2b/simulate
# Customer Buy Goods Simulation
POST /api/mpesa/c2b/buy-goods
# Customer Pay Bill Simulation
POST /api/mpesa/c2b/pay-billTransaction Operations
# Check Transaction Status
POST /api/mpesa/transactions/status
# Check Account Balance
POST /api/mpesa/transactions/balance
# Reverse Transaction
POST /api/mpesa/transactions/reversal
# Query by Receipt
POST /api/mpesa/transactions/query-by-receipt
# Query by Originator ID
POST /api/mpesa/transactions/query-by-originator-idCertificate Setup
Certificate File Location
Place your M-Pesa certificate file in the cert folder:
cert/ProductionCertificate.cer- For production environmentcert/SandboxCertificate.cer- For sandbox environment (optional)
Password Encryption
The service now automatically encrypts initiator passwords using the certificate. You can also manually encrypt passwords:
const EncryptionUtils = require('./utils/encryptionUtils');
// Encrypt password for current environment
const encryptedPassword = EncryptionUtils.encryptPassword('your_password');
// Encrypt password for specific environment
const encryptedPassword = EncryptionUtils.encryptPasswordForEnvironment('your_password', 'production');
// Validate certificate
const certValidation = EncryptionUtils.validateCertificate();
console.log(certValidation);Configuration Updates
Environment Variables
Update your .env file with the new variables:
# Existing variables remain the same
MPESA_CONSUMER_KEY=your_consumer_key_here
MPESA_CONSUMER_SECRET=your_consumer_secret_here
MPESA_PASSKEY=your_passkey_here
MPESA_SHORTCODE=174379
MPESA_HEAD_OFFICE=174379
MPESA_INITIATOR_NAME=testapi
MPESA_INITIATOR_PASSWORD=your_initiator_password_here
MPESA_SECURITY_CREDENTIAL=your_encrypted_security_credential_here
MPESA_CALLBACK_URL=https://your-domain.com/api/mpesa/callback
MPESA_TIMEOUT_URL=https://your-domain.com/api/mpesa/timeout
MPESA_RESULT_URL=https://your-domain.com/api/mpesa/result
MPESA_QUEUE_TIMEOUT_URL=https://your-domain.com/api/mpesa/queue-timeout
MPESA_ENVIRONMENT=sandbox
PORT=3000
API_KEY=your_api_key_hereSecurity Credential
You need to encrypt your initiator password using the certificate before adding it to the .env file:
- Use the encryption utility:
const EncryptionUtils = require('./utils/encryptionUtils');
const encrypted = EncryptionUtils.encryptPassword('your_initiator_password');
console.log(encrypted);- Add the encrypted value to your
.envfile:
MPESA_SECURITY_CREDENTIAL=your_encrypted_password_hereUsage Examples
B2Pochi Payment
curl -X POST http://localhost:3000/api/mpesa/b2pochi/payment \
-H "Content-Type: application/json" \
-H "x-api-key: your_api_key" \
-d '{
"amount": 100,
"partyB": "254700000000",
"remarks": "Pochi payment",
"occasion": "Business payment"
}'Business Buy Goods Payment
curl -X POST http://localhost:3000/api/mpesa/b2b/business-buy-goods \
-H "Content-Type: application/json" \
-H "x-api-key: your_api_key" \
-d '{
"amount": 500,
"partyA": "174379",
"partyB": "174380",
"accountReference": "Goods Purchase",
"remarks": "Business payment to till",
"requester": "254700000000"
}'Business Pay Bill Payment
curl -X POST http://localhost:3000/api/mpesa/b2b/business-pay-bill \
-H "Content-Type: application/json" \
-H "x-api-key: your_api_key" \
-d '{
"amount": 1000,
"partyA": "174379",
"partyB": "174381",
"accountReference": "ACC123456",
"remarks": "Bill payment",
"requester": "254700000000"
}'Salary Payment (B2C)
curl -X POST http://localhost:3000/api/mpesa/b2c/salary \
-H "Content-Type: application/json" \
-H "x-api-key: your_api_key" \
-d '{
"amount": 50000,
"partyB": "254700000000",
"remarks": "January Salary",
"occasion": "Monthly Salary"
}'Customer Buy Goods Simulation (C2B)
curl -X POST http://localhost:3000/api/mpesa/c2b/buy-goods \
-H "Content-Type: application/json" \
-H "x-api-key: your_api_key" \
-d '{
"shortCode": "174379",
"amount": 100,
"msisdn": "254700000000"
}'Transaction Query by Receipt
curl -X POST http://localhost:3000/api/mpesa/transactions/query-by-receipt \
-H "Content-Type: application/json" \
-H "x-api-key: your_api_key" \
-d '{
"transactionID": "LHG31AA5TX",
"remarks": "Query transaction"
}'Security Enhancements
Certificate-Based Encryption
- Automatic password encryption using M-Pesa certificates
- Certificate validation before encryption
- Support for multiple certificates (sandbox/production)
Enhanced Validation
- Phone number format validation (254XXXXXXXXX)
- Command ID validation for all operations
- Amount validation (positive numbers)
- Required field checking
Improved Error Handling
- Specific error codes from official M-Pesa documentation
- Descriptive error messages
- Proper logging of all operations
Callback Handling
All callbacks now handle the official M-Pesa response formats:
- STK Push callbacks with proper result parsing
- C2B v2 validation and confirmation callbacks
- B2C, B2B, and B2Pochi result callbacks
- Transaction status and reversal callbacks
Testing
The service includes comprehensive testing capabilities:
- All endpoints properly validated
- Error handling for all scenarios
- Certificate validation utilities
- Phone number formatting utilities
Production Deployment
Checklist
- ✅ Obtain production certificate from M-Pesa
- ✅ Encrypt initiator password using certificate
- ✅ Configure production environment variables
- ✅ Set up production callback URLs (HTTPS required)
- ✅ Configure proper firewall and security
- ✅ Set up monitoring and logging
- ✅ Test all endpoints in production environment
Security Recommendations
- Use HTTPS for all production endpoints
- Implement additional API key management
- Set up proper rate limiting per user
- Monitor logs for suspicious activities
- Regular security audits
- Implement database for transaction persistence
Support and Documentation
All implementation is based on official M-Pesa documentation:
- C2B API v2 documentation
- B2C API v3 documentation
- B2B API documentation
- B2Pochi API documentation
- Transaction Status API documentation
For issues and questions, please refer to the official M-Pesa API documentation at https://developer.safaricom.co.ke
