Introduction
M-Pesa has revolutionized payments in Kenya and East Africa, making it essential for developers to understand how to integrate this mobile money service into their applications. This comprehensive guide will walk you through everything you need to know about M-Pesa integration.
Understanding M-Pesa APIs
M-Pesa provides several APIs for different payment scenarios. The main APIs include:
1. STK Push (Lipa na M-Pesa Online)
This is the most popular integration method, allowing customers to pay directly from their M-Pesa account without leaving your application.
2. C2B (Customer to Business)
Enables customers to initiate payments by entering your business's paybill or till number.
3. B2C (Business to Customer)
Allows businesses to send money to customers' M-Pesa accounts.
4. B2B (Business to Business)
Facables business-to-business payments between organizations.
Getting Started
Prerequisites
- Valid M-Pesa developer account
- Business registration documents
- Valid phone number for testing
- HTTPS-enabled server for callbacks
Sandbox vs Production
M-Pesa provides a sandbox environment for testing. Always test thoroughly in sandbox before moving to production.
STK Push Implementation
Step 1: Authentication
First, you need to authenticate with M-Pesa's OAuth API to get an access token.
// Authentication example
const authenticate = async () => {
const auth = Buffer.from(`${consumerKey}:${consumerSecret}`).toString('base64');
const response = await fetch('https://sandbox.safaricom.com/oauth/v1/generate?grant_type=client_credentials', {
method: 'GET',
headers: {
'Authorization': `Basic ${auth}`
}
});
const data = await response.json();
return data.access_token;
};
Step 2: Initiate STK Push
Use the access token to initiate the STK push request.
// STK Push initiation
const initiateSTKPush = async (phoneNumber, amount, accountReference) => {
const accessToken = await authenticate();
const stkPushData = {
BusinessShortCode: '174379',
Password: generatePassword(),
Timestamp: getTimestamp(),
TransactionType: 'CustomerPayBillOnline',
Amount: amount,
PartyA: phoneNumber,
PartyB: '174379',
PhoneNumber: phoneNumber,
CallBackURL: 'https://yourdomain.com/callback',
AccountReference: accountReference,
TransactionDesc: 'Payment for services'
};
const response = await fetch('https://sandbox.safaricom.com/mpesa/stkpush/v1/processrequest', {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(stkPushData)
});
return response.json();
};
Handling Callbacks
M-Pesa will send payment results to your callback URL. It's crucial to handle these callbacks properly.
// Callback handler example
app.post('/callback', (req, res) => {
const { Body } = req.body;
const { stkCallback } = Body;
if (stkCallback.ResultCode === 0) {
// Payment successful
const { CheckoutRequestID, MerchantRequestID } = stkCallback;
// Update your database
updatePaymentStatus(CheckoutRequestID, 'completed');
} else {
// Payment failed
console.log('Payment failed:', stkCallback.ResultDesc);
}
res.status(200).json({ ResultCode: 0, ResultDesc: 'Success' });
});
Security Best Practices
1. Validate Callbacks
Always validate that callbacks are coming from M-Pesa by checking the source IP and using webhook signatures.
2. Encrypt Sensitive Data
Store sensitive information like consumer keys and secrets encrypted in your database.
3. Use HTTPS
Always use HTTPS for all M-Pesa API calls and callback URLs.
4. Implement Rate Limiting
Protect your API endpoints from abuse by implementing rate limiting.
Testing Your Integration
Test Phone Numbers
M-Pesa provides specific test phone numbers for sandbox testing. Use these numbers to test your integration thoroughly.
Test Scenarios
- Successful payments
- Insufficient funds
- Invalid phone numbers
- Network timeouts
- User cancellation
Common Issues and Solutions
1. Invalid Phone Number Format
Ensure phone numbers are in the format 254XXXXXXXXX (without the + sign).
2. Callback URL Issues
Make sure your callback URL is accessible and returns a 200 status code.
3. Timestamp Issues
Use the correct timestamp format (YYYYMMDDHHMMSS) and ensure your server time is synchronized.
Production Deployment
1. Update API URLs
Change from sandbox URLs to production URLs when going live.
2. Update Credentials
Use production consumer key and secret instead of sandbox credentials.
3. Monitor Transactions
Implement proper logging and monitoring for all M-Pesa transactions.
Conclusion
M-Pesa integration is essential for any business operating in Kenya. By following this guide and implementing proper security measures, you can successfully integrate M-Pesa payments into your application and provide a seamless payment experience for your customers.