← Back to Blog
Article · January 20, 2026

M-Pesa Integration for E-commerce: Complete Guide

M-Pesa Integration for E-commerce: Complete Guide

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:

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:

Disadvantages:

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:

Disadvantages:

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:

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:

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:

Till Number:

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:

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:

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:

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:

Issue: Callbacks not received

Solutions:

Issue: Transaction succeeds but order not updated

Solutions:

Issue: Duplicate payments

Solutions:

Issue: Slow callback processing

Solutions:

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:

Business Charges: Your business pays Safaricom for receiving payments:

Payment Gateway Fees: If using a gateway, expect additional fees:

Best Practices for M-Pesa E-commerce Integration

Optimize Checkout Experience

Communicate Clearly

Handle Failed Payments Gracefully

Monitor and Reconcile

Ensure Security

Provide Excellent Support

Legal and Compliance Considerations

Data Protection

Under Kenya's Data Protection Act, you must:

Terms and Conditions

Your website should clearly state:

Transaction Records

Maintain records of:

Tax Compliance

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:

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

Advanced Features

Getting Help with M-Pesa Integration

Safaricom Resources:

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:

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.

Need a website or system?

Talk to Breon Studio in Nairobi — honest advice, clear scope.

Get in Touch