M-PESA integration in Kenya is often described as adding a payment button to a website or app. The visible payment prompt is only the beginning. A dependable integration must also identify the order, receive and verify the result, handle delays and duplicates, reconcile money against business records, protect credentials, and give staff a clear way to resolve exceptions.
Those less-visible details decide whether the integration saves work or creates a daily spreadsheet problem. This guide is for business owners, product managers, operations teams, and developers planning a production M-PESA integration through Safaricom's Daraja platform.
Map the payment workflow before choosing the API.
Share what customers pay for, how orders are created, which shortcode you use, and how your team reconciles payments today. Rx Code Labs will help you define a sensible production scope.
Plan it on WhatsAppWhat an M-PESA integration actually connects
Safaricom describes Daraja 3.0 as the bridge between M-PESA APIs and web or mobile applications. In practice, your customer-facing interface, your server, the Daraja API, your database, and your operations team all participate in one payment workflow.
The integration should connect a payment to a specific business event: an order, invoice, subscription, booking, account top-up, loan repayment, donation, membership, delivery, or service request. If the system can confirm that money arrived but cannot reliably say what it was for, the integration is incomplete.
Choose the payment flow from the business process
Do not begin with an API name. Begin with who initiates the transaction, where it starts, who receives the money, and what the system must do after the result.
| Business need | Typical M-PESA capability | Important design question |
|---|---|---|
| A customer starts payment inside a website or app | Lipa Na M-PESA Online (commonly called STK Push) | What happens when the prompt is cancelled, times out, or completes after the customer leaves? |
| A customer pays directly to a PayBill or Till | Customer-to-Business (C2B) confirmation and validation | How will the account reference map to the correct customer, invoice, or order? |
| The business sends money to a customer or worker | Business-to-Customer (B2C) | Who authorizes disbursement, and how are failed or repeated payouts prevented? |
| The business pays another organization | Business-to-Business (B2B) | Which approval, beneficiary, and reconciliation controls are required? |
| The system needs to verify an uncertain transaction | Transaction status query | When should the system query instead of waiting for a callback? |
Safaricom's current M-PESA business channel guidance lists these capabilities and explains that Daraja serves both integrators and business owners who need reconciliation. Confirm the APIs, onboarding requirements, commercial terms, and shortcode configuration that apply to your organization directly with Safaricom before implementation.
Ten requirements for a production-ready integration
1. Business-owned accounts and production credentials
The merchant shortcode, Daraja organization, production application, callback domain, certificates, credentials, and support contacts should be controlled by the business or governed through documented access. A developer's personal account should not become an invisible dependency for a business-critical payment channel.
Record who can request, approve, rotate, and revoke credentials. Keep sandbox and production configuration separate, and never place secret keys in browser code, a mobile app bundle, a public repository, or a shared document.
2. A payment reference that means something
Create the order or invoice before requesting payment, then pass a stable reference through the workflow. Store the internal order ID, requested amount, phone number as needed for the transaction, timestamp, current status, and provider request identifiers.
The reference should let an authorized staff member move from an M-PESA receipt to the correct order and back again. Avoid using a customer's name as the primary key; names change, repeat, and are entered inconsistently.
3. Server-side confirmation as the source of truth
A browser success screen is not proof of payment. The customer may close the page, lose connectivity, refresh, or manipulate a client-side request. Treat the secure server-to-server result as the authoritative event, then update the order according to verified transaction data.
The customer interface can show waiting for confirmation, paid, cancelled, or needs attention. It should not invent certainty while the final result is still pending.
4. Idempotency and duplicate protection
Networks retry. Users tap twice. Callbacks can be delivered more than once. Your code must be safe when the same event appears repeatedly.
Use unique constraints and transaction identifiers so one M-PESA receipt cannot settle two orders or credit one account twice. Make repeated callback processing return a safe response without repeating stock changes, notifications, ledger entries, or fulfilment.
5. Reconciliation built into operations
Automation should reduce reconciliation work, not hide it. Store the amount requested, amount received, receipt number, payer details that the business is permitted to retain, transaction time, order reference, raw provider status where appropriate, and the system action taken.
Give authorized staff a reconciliation view for unmatched references, amount differences, pending transactions, duplicates, reversals, manual payments, and callbacks that failed processing. Include export or reporting requirements during discovery rather than adding them after launch. Rx Code Labs' dashboard and workflow automation service covers this operational layer.
6. Failure and pending-state handling
Design for declined prompts, incorrect PIN attempts, customer cancellation, insufficient balance, timeout, unavailable services, delayed callbacks, invalid references, and internal processing errors. Each state needs a user message and a staff action.
Do not automatically create a second charge while the first request may still complete. Where the API and workflow support it, use a controlled transaction-status query and a defined expiry window before offering another attempt.
7. Security around every boundary
Use HTTPS, validate expected request structure, keep credentials in protected server-side configuration, restrict administrative access, log security-relevant events, rotate secrets, patch dependencies, and rate-limit endpoints that could be abused. Do not log passwords, PINs, complete secrets, or more personal data than support teams need.
Separate the public callback endpoint from the internal action it triggers. Validate the event, locate the expected transaction, enforce allowed state transitions, then record the outcome. Security review should cover both the M-PESA connection and your own application.
8. Privacy and data-retention decisions
Payment integrations process phone numbers, transaction references, timestamps, customer identifiers, and sometimes names. Kenya's Data Protection Act, 2019 makes it important to define the purpose, access, retention, protection, and deletion of personal data.
Collect only what the transaction and legitimate business process require. Tell customers how their information is used, limit staff access by role, establish retention rules with qualified legal or compliance advice, and include payment data in backup and incident-response planning.
9. A clear eTIMS boundary
M-PESA confirms movement of money; it does not by itself complete every invoicing or tax workflow. KRA states that businesses can connect qualifying invoicing or ERP systems to eTIMS through OSCU or VSCU system-to-system integration.
If your system must issue electronic tax invoices, define when an invoice is created, how payment and invoice states relate, what happens after cancellation or refund, and whether your organization will self-integrate or use a certified third-party integrator. Confirm the current requirements with KRA or a qualified tax adviser; do not assume an M-PESA receipt replaces the applicable tax invoice.
10. Testing, monitoring, documentation, and handover
Use the Daraja sandbox to test the basic flow, then prepare production acceptance cases that cover success, cancellation, timeout, duplicate callbacks, wrong references, amount differences, delayed responses, status queries, and internal failures. Sandbox success is necessary, but it is not the same as production readiness.
Monitor callback availability, processing errors, unusual pending volumes, reconciliation gaps, and credential expiry. Document architecture, configuration ownership, support escalation, deployment, recovery, and the safe procedure for changing callback URLs or credentials.
A dependable transaction sequence
- Your server creates an order with a unique reference and expected amount.
- The server requests the appropriate M-PESA transaction through Daraja.
- The customer completes, rejects, or ignores the prompt where that flow applies.
- Your public callback endpoint receives the provider result and acknowledges it quickly.
- An internal service validates identifiers and permitted state changes.
- The database records the transaction once and links it to the order.
- Fulfilment, receipt communication, stock movement, or account credit happens once.
- Exceptions enter a visible reconciliation queue instead of disappearing into logs.
What affects M-PESA integration cost and timeline?
A simple checkout for one product is different from a multi-branch platform with C2B references, payouts, partial payments, refunds, approvals, eTIMS, accounting integration, and detailed reconciliation. The main cost drivers are:
- the number of transaction types and merchant shortcodes;
- existing website, app, ERP, POS, or invoicing-system quality;
- order, customer, inventory, delivery, and accounting workflows;
- reconciliation, reporting, approval, and audit requirements;
- production onboarding and third-party dependencies;
- security review, testing, monitoring, and support coverage; and
- data migration or cleanup needed before integration.
Request an estimate against written acceptance cases. A quote that says only “integrate M-PESA” leaves too much room for disagreement about callbacks, reconciliation, exception handling, deployment, and support. If the payment workflow sits inside a larger operational product, review our custom software cost guide for Kenya.
Frequently asked questions
What is the best M-PESA API for a website checkout?
Lipa Na M-PESA Online is commonly used when a customer initiates payment inside a website or app. C2B may fit direct PayBill or Till payments. The correct choice depends on who initiates payment, how references are assigned, and how the business reconciles transactions.
Can I test an M-PESA integration before going live?
Yes. Safaricom's Daraja portal provides a sandbox for creating an app and simulating supported API flows. Production onboarding, credentials, callback configuration, merchant setup, and real-world acceptance testing are still required.
Why should payment confirmation happen on the server?
The browser or mobile interface can close, lose connectivity, or be manipulated. A secure server-side result can be validated, recorded once, reconciled, and used to update the order reliably.
Does M-PESA integration automatically handle eTIMS?
No. Payment confirmation and electronic tax invoicing are separate concerns. If your system must connect to eTIMS, define that workflow and confirm current KRA requirements independently.
Can Rx Code Labs add M-PESA to an existing website or application?
Often, yes. We first review the codebase, hosting, order model, current payment workflow, merchant setup, security, and reconciliation needs before confirming the safest integration approach.
Make every transaction traceable from customer to reconciliation.
Rx Code Labs builds M-PESA-enabled websites, web applications, mobile products, and custom business systems for organizations in Kenya.
Discuss the integration on WhatsApp Explore web and mobile development
