M-Pesa Integration for E-commerce: Complete Guide
M-Pesa has revolutionized digital payments in Kenya, with over 30 million active users conducting billions of shillings in transactions daily. For any e-commerce business operating in Kenya. This comprehensive guide walks you through everything you need to know about integrating M-Pesa into your online store.
Why M-Pesa Integration Matters for Your E-commerce Business
M-Pesa dominates Kenya's digital payment landscape. While credit and debit cards remain popular among certain demographics, the vast majority of Kenyan consumers prefer M-Pesa for online transactions. Here's why integrating M-Pesa can transform your e-commerce business:
Increased Conversion Rates
Customers abandon shopping carts when their preferred payment method isn't available. By offering M-Pesa, you eliminate this friction point and capture sales you'd otherwise lose to competitors.
Wider Customer Reach
M-Pesa's penetration extends far beyond urban centers. Integrating M-Pesa allows you to serve customers across Kenya, including those in rural areas who may not have access to traditional banking services.
Instant Payment Confirmation
Unlike bank transfers that can take hours or days to confirm, M-Pesa transactions process within seconds. This speed improves customer experience and allows you to fulfill orders faster.
Lower Transaction Costs
Compared to international payment gateways that charge 3-5% plus currency conversion fees, M-Pesa offers competitive rates that protect your profit margins.
Trust and Familiarity
Kenyan consumers trust M-Pesa. Seeing the familiar green payment option at checkout increases confidence and reduces purchase hesitation.
Understanding M-Pesa Payment Options
Before diving into integration, you need to understand the different M-Pesa payment solutions available:
STK Push (Lipa Na M-Pesa Online)
This is the most common integration for e-commerce websites. When customers choose M-Pesa at checkout, they receive a pop-up prompt on their phone asking them to enter their M-Pesa PIN to complete the payment. The entire process happens automatically without customers needing to manually send money.
Paybill Numbers
Customers manually send money to your business paybill number, including their order number as the account reference. This method requires more customer effort but works well for businesses just starting out.
Till Numbers
Similar to paybill, but customers send money to your till number. Till numbers are easier to obtain than paybill numbers but offer less professional branding and fewer integration options.
C2B (Customer to Business) API
This allows customers to initiate payments from their M-Pesa menu by entering your paybill or till number. Your system receives automatic notifications when payments arrive.
B2C (Business to Customer) API
This enables you to send money to customers, useful for processing refunds, affiliate payments, or cashback programs.
Methods to Integrate M-Pesa into Your E-commerce Website
Method 1: Direct Integration with Safaricom Daraja API
The Daraja API is Safaricom's official developer platform for M-Pesa integration. This method gives you complete control and eliminates third-party fees.
Requirements:
- Safaricom Daraja account (register at developer.safaricom.co.ke)
- Active paybill or till number
- Basic programming knowledge (PHP, Python, Node.js, or similar)
- SSL certificate for your website
- Server with callback URL capability
Step-by-Step Process:
Step 1: Register on Daraja Visit developer.safaricom.co.ke and create an account. You'll receive consumer key and consumer secret credentials needed for API calls.
Step 2: Create an App In your Daraja dashboard, create a new app. Choose whether you're building for sandbox (testing) or production environment.
Step 3: Obtain Production Credentials For live transactions, you need to move from sandbox to production. Contact Safaricom through the portal to request production credentials. You'll need to provide business registration documents and your paybill number.
Step 4: Generate Access Token Your application must generate an OAuth access token before making any API requests. This token expires after a set time, so implement automatic token refresh in your code.
Step 5: Implement STK Push Use the Lipa Na M-Pesa Online API to trigger payment prompts on customer phones. Your code sends a request containing the customer's phone number, amount, and your business details.
Step 6: Set Up Callback URL Create a callback endpoint on your server where Safaricom sends payment confirmation. This URL must be publicly accessible and secured with SSL.
Step 7: Handle Responses Process the callback data to confirm successful payments, update order status, and trigger order fulfillment in your system.
Step 8: Implement Error Handling Account for failed transactions, timeouts, insufficient balances, and other potential issues. Provide clear error messages to customers.
Step 9: Test Thoroughly Use the sandbox environment to test various scenarios before going live. Test successful payments, failed payments, timeouts, and edge cases.
Step 10: Go Live Switch to production credentials and monitor initial transactions closely to ensure everything works smoothly.
Advantages:
- No third-party fees beyond Safaricom's transaction charges
- Complete control over the payment experience
- Direct access to transaction data
- Ability to customize every aspect
Disadvantages:
- Requires technical expertise
- More time-intensive to set up
- You're responsible for security and PCI compliance
- Need to maintain and update integration code
Method 2: Payment Gateway Integration
Payment gateways act as intermediaries, simplifying M-Pesa integration while often supporting multiple payment methods.
Popular Payment Gateways in Kenya:
Pesapal
Pesapal is one of Kenya's most established payment gateways, supporting M-Pesa, cards, and bank transfers.
Pricing: Typically 2.5% - 3.5% per transaction Setup: Simple API integration or plugins for WordPress/WooCommerce Settlement: Daily or weekly payouts to your bank account
Advantages:
- Quick setup with ready-made plugins
- Supports multiple payment methods
- Handles security and compliance
- Customer support available
Disadvantages:
- Transaction fees reduce profit margins
- Less control over payment flow
- Dependent on third-party service
iPay
iPay offers robust payment solutions tailored for East African businesses.
Pricing: Competitive rates, typically around 3% Setup: API integration or e-commerce plugins Settlement: Flexible payout schedules
Flutterwave
While pan-African, Flutterwave provides excellent M-Pesa integration for Kenyan businesses.
Pricing: Transparent pricing around 3.5% Setup: Comprehensive API documentation and plugins Settlement: Fast payouts with multiple currency support
DPO PayGate (formerly DPO Group)
Enterprise-grade payment gateway serving businesses across Africa.
Pricing: Custom pricing for larger businesses Setup: Professional integration support available Settlement: Reliable payout schedules
Intasend
Growing Kenyan payment gateway focusing on developer experience.
Pricing: Competitive transaction fees Setup: Modern API with excellent documentation Settlement: Quick turnaround times
Kopokopo (now Cellulant)
Specialized in M-Pesa and mobile money integration.
Pricing: Variable based on transaction volume Setup: Focused specifically on mobile money Settlement: Efficient processing
How to Choose a Payment Gateway:
- Compare transaction fees against your profit margins
- Check settlement times (how quickly you receive funds)
- Verify customer support quality and availability
- Test the checkout experience from a customer perspective
- Read reviews from other Kenyan businesses
- Confirm compatibility with your e-commerce platform
Method 3: E-commerce Platform Built-in Integration
If you're using popular e-commerce platforms, M-Pesa integration may already be simplified through plugins or native features.
WooCommerce (WordPress)
Several M-Pesa plugins exist for WooCommerce:
- M-Pesa for WooCommerce (various developers)
- Payment gateway plugins (Pesapal, Flutterwave, etc.)
- Custom plugins built by Kenyan developers
Installation: Install plugin, enter your API credentials, configure settings Cost: Plugin costs vary from free to KES 5,000 - KES 20,000
Shopify
Shopify supports M-Pesa through payment gateway apps available in their app store.
Installation: Install payment app, connect your M-Pesa account Cost: Standard Shopify transaction fees plus app fees
PrestaShop
PrestaShop modules enable M-Pesa integration through various payment gateways.
Installation: Purchase and install module, configure credentials Cost: Module costs plus gateway fees
Magento
Extensions available for M-Pesa integration, suitable for larger enterprises.
Installation: Technical installation through Magento marketplace Cost: Varies by extension
Custom-built Websites
For custom websites, you'll either implement direct Daraja integration or integrate a payment gateway SDK.
Setting Up Your M-Pesa Business Account
Before you can integrate M-Pesa, you need the right business account:
Paybill vs Till Number
Paybill Number:
- Professional business solution
- Supports account references (useful for order tracking)
- Better for e-commerce integration
- Requires business registration documents
- Takes 2-4 weeks to obtain
Till Number:
- Faster to obtain (can be instant)
- Simpler application process
- Less professional appearance
- Limited integration capabilities
- Better suited for physical businesses
How to Apply for Paybill:
Visit your nearest Safaricom shop with required documents
Submit business registration certificate, KRA PIN, ID copies for directors
Fill out the application form
Pay the setup fee (currently around KES 5,000)
Wait for approval and activation
Receive your paybill number and initial credentials
Required Documents:
- Certificate of business registration
- KRA PIN certificate
- National IDs for all directors/owners
- Letter from your bank with account details
- Business permit (may be required)
Technical Implementation Guide
Here's a basic implementation example using PHP for STK Push:
Step 1: Generate Access Token
function getAccessToken() { $consumerKey = 'YOUR_CONSUMER_KEY'; $consumerSecret = 'YOUR_CONSUMER_SECRET'; $credentials = base64_encode($consumerKey . ':' . $consumerSecret); $url = 'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials'; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . $credentials)); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($curl); $result = json_decode($response); return $result->access_token; }
Step 2: Initiate STK Push
function initiateSTKPush($phone, $amount, $orderID) { $accessToken = getAccessToken(); $url = 'https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest'; $businessShortCode = 'YOUR_SHORTCODE'; $passkey = 'YOUR_PASSKEY'; $timestamp = date('YmdHis'); $password = base64_encode($businessShortCode . $passkey . $timestamp); $curl_post_data = array( 'BusinessShortCode' => $businessShortCode, 'Password' => $password, 'Timestamp' => $timestamp, 'TransactionType' => 'CustomerPayBillOnline', 'Amount' => $amount, 'PartyA' => $phone, 'PartyB' => $businessShortCode, 'PhoneNumber' => $phone, 'CallBackURL' => 'https://yourwebsite.com/callback.php', 'AccountReference' => $orderID, 'TransactionDesc' => 'Payment for Order ' . $orderID ); $data_string = json_encode($curl_post_data); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'Content-Type:application/json', 'Authorization:Bearer ' . $accessToken )); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string); $response = curl_exec($curl); return json_decode($response); }
Step 3: Handle Callback
// callback.php $response = file_get_contents('php://input'); $data = json_decode($response, true); if (isset($data['Body']['stkCallback']['ResultCode'])) { if ($data['Body']['stkCallback']['ResultCode'] == 0) { // Payment successful $merchantRequestID = $data['Body']['stkCallback']['MerchantRequestID']; $checkoutRequestID = $data['Body']['stkCallback']['CheckoutRequestID']; // Extract transaction details $items = $data['Body']['stkCallback']['CallbackMetadata']['Item']; foreach ($items as $item) { if ($item['Name'] == 'MpesaReceiptNumber') { $mpesaCode = $item['Value']; } } // Update order status in your database // Send confirmation email to customer // Trigger order fulfillment } else { // Payment failed // Update order status // Notify customer } }
Important Security Considerations:
- Never expose your consumer key and secret in client-side code
- Always use HTTPS for your website and callback URL
- Validate all callback data before processing
- Store credentials securely, preferably in environment variables
- Implement rate limiting to prevent abuse
- Log all transactions for auditing purposes
Testing Your M-Pesa Integration
Thorough testing prevents costly errors and ensures smooth customer experience.
Sandbox Testing
Safaricom provides a sandbox environment with test credentials. Use these to test:
- Successful payments
- Failed payments (insufficient funds)
- Cancelled payments (customer declines)
- Timeout scenarios (customer doesn't respond)
- Wrong PIN entries
- Network failures
Test Phone Numbers
Safaricom provides test phone numbers for sandbox testing. Never use real customer numbers during testing.
Common Test Scenarios:
Complete successful transaction from start to finish
Customer cancels payment prompt
Customer enters wrong PIN multiple times
Payment timeout (customer doesn't respond within 60 seconds)
Insufficient balance in M-Pesa account
Duplicate transaction prevention
Callback handling when server is temporarily down
Production Testing
Before announcing M-Pesa payment to customers:
Process small test transactions with real money
Verify callbacks work correctly
Confirm order status updates properly
Test email/SMS confirmations
Verify funds arrive in your account
Process a test refund
Handling Common M-Pesa Integration Issues
Issue: Customer doesn't receive STK push prompt
Solutions:
- Verify phone number format (254XXXXXXXXX, no spaces or special characters)
- Check customer has active M-Pesa account
- Ensure customer's phone is on and has network coverage
- Verify your API credentials are correct
- Check callback URL is publicly accessible
Issue: Callbacks not received
Solutions:
- Confirm callback URL is using HTTPS
- Verify URL is publicly accessible (not localhost)
- Check server firewall isn't blocking Safaricom IPs
- Ensure callback script has no fatal errors
- Implement logging to debug callback data
Issue: Transaction succeeds but order not updated
Solutions:
- Review callback handling code for errors
- Check database connection is stable
- Implement transaction logging
- Add error notifications for failed updates
- Use queuing system for callback processing
Issue: Duplicate payments
Solutions:
- Implement checkout request ID tracking
- Validate transaction hasn't already been processed
- Use database constraints to prevent duplicate orders
- Add idempotency keys to API requests
Issue: Slow callback processing
Solutions:
- Optimize database queries
- Use asynchronous processing for heavy tasks
- Implement caching where appropriate
- Consider queue systems for background processing
- Scale server resources if needed
M-Pesa Transaction Costs
Understanding M-Pesa costs helps you price products appropriately:
Customer Charges: M-Pesa charges customers fees for sending money. These fees vary by amount but are typically:
- KES 0 - KES 100: Free to KES 1
- KES 101 - KES 2,500: KES 11 - KES 28
- KES 2,501 - KES 70,000: KES 29 - KES 105
- Above KES 70,000: KES 105+
Business Charges: Your business pays Safaricom for receiving payments:
- Paybill rates typically 0.5% - 2% depending on negotiated terms
- Withdrawal fees when moving money from M-Pesa to bank
- Some businesses pass these costs to customers; others absorb them
Payment Gateway Fees: If using a gateway, expect additional fees:
- Transaction percentage: 2.5% - 4%
- Fixed per-transaction fee: KES 0 - KES 20
- Monthly subscription: Some gateways charge monthly fees
Best Practices for M-Pesa E-commerce Integration
Optimize Checkout Experience
- Display M-Pesa prominently as a payment option
- Show clear instructions before initiating payment
- Inform customers they'll receive a pop-up on their phone
- Provide estimated time for payment processing
- Show loading indicators during payment processing
- Display clear success/failure messages
Communicate Clearly
- Send immediate order confirmation emails
- Include M-Pesa receipt number in confirmations
- Provide customer support contact for payment issues
- Explain what happens if payment fails
- Set clear expectations for order fulfillment timing
Handle Failed Payments Gracefully
- Don't immediately delete cart contents
- Allow customers to retry payment easily
- Provide alternative payment options
- Send follow-up email for abandoned checkouts
- Offer customer support assistance
Monitor and Reconcile
- Implement daily transaction reconciliation
- Monitor for unusual patterns or fraud attempts
- Track success/failure rates
- Keep audit logs for all transactions
- Reconcile M-Pesa statements with orders regularly
Ensure Security
- Never store customer M-Pesa PINs
- Use HTTPS throughout your website
- Implement fraud detection mechanisms
- Monitor for suspicious transaction patterns
- Keep API credentials secure and rotate regularly
- Comply with data protection regulations
Provide Excellent Support
- Train support team on M-Pesa process
- Create FAQ section addressing common payment questions
- Respond quickly to payment-related inquiries
- Have escalation process for technical issues
- Maintain backup contact with Safaricom support
Legal and Compliance Considerations
Data Protection
Under Kenya's Data Protection Act, you must:
- Obtain customer consent for processing payment data
- Secure customer information appropriately
- Have clear privacy policy explaining data usage
- Allow customers to access their data
- Report data breaches within required timeframes
Terms and Conditions
Your website should clearly state:
- Accepted payment methods
- Refund policy for M-Pesa payments
- Processing times
- Customer responsibilities
- Dispute resolution process
Transaction Records
Maintain records of:
- All M-Pesa transactions for at least 7 years
- Customer payment confirmations
- Refund transactions
- Failed payment attempts
- This protects you in disputes and supports tax compliance
Tax Compliance
- Issue receipts/invoices for all transactions
- Track M-Pesa income for tax purposes
- Remit VAT if registered
- Keep records for KRA audits
- Consider consulting tax professional for complex scenarios
Alternative Payment Methods to Complement M-Pesa
While M-Pesa should be your primary payment option for Kenyan customers, offering alternatives increases conversion:
Airtel Money
The second-largest mobile money provider in Kenya deserves integration consideration, especially if your target market includes Airtel users.
Card Payments
Credit and debit cards remain important for:
- Higher-value transactions
- International customers
- Corporate buyers
- Customers preferring card rewards
Bank Transfers
Some customers prefer direct bank transfers, particularly for large purchases.
Cash on Delivery
For areas with limited digital payment adoption or high-value items where customers want to inspect before paying.
Scaling Your M-Pesa Integration
As your business grows, consider these optimizations:
Implement Auto-reconciliation
Automate matching M-Pesa transactions to orders, flagging discrepancies for manual review.
Add B2C for Refunds
Automate refund processing directly to customers' M-Pesa accounts instead of manual processing.
Optimize for High Volume
- Implement caching strategies
- Use queue systems for callback processing
- Scale server infrastructure
- Consider load balancing
- Optimize database queries
Advanced Features
- Installment payment options
- Subscription billing
- Split payments (partial M-Pesa, partial other methods)
- Multi-currency support for regional expansion
Getting Help with M-Pesa Integration
Safaricom Resources:
- Daraja developer portal: developer.safaricom.co.ke
- Safaricom business support: 0722 000 000
- Developer forums and community
Professional Integration Services:
At Breon, we specialize in M-Pesa integration for Kenyan e-commerce businesses. Whether you need complete integration setup, troubleshooting existing systems, or optimization for scale, we offer:
- Custom M-Pesa integration tailored to your platform
- Payment gateway setup and configuration
- Testing and quality assurance
- Ongoing support and maintenance
- Competitive pricing with flexible packages
- Fast turnaround times
Don't let payment integration hold back your e-commerce success. Contact us today for a free consultation and discover how we can implement seamless M-Pesa payments that increase your conversions and delight your customers.
Conclusion
M-Pesa integration is non-negotiable for e-commerce success in Kenya. Whether you choose direct Daraja integration for maximum control, a payment gateway for simplicity, or platform plugins for convenience, the key is implementing a solution that works reliably and provides excellent customer experience.
Start with sandbox testing, move to production carefully, monitor continuously, and optimize based on real transaction data. With proper implementation, M-Pesa becomes your competitive advantage, enabling you to serve the millions of Kenyan consumers who prefer mobile money for online shopping.
The technical challenges are manageable with the right approach, and the business benefits increased conversions, wider reach, faster payments far outweigh the integration effort. Your customers are ready to pay with M-Pesa. Make sure your e-commerce store is ready to accept it.
