Callbacks
In short: a callback is Daraja calling your server back with the final result. Your endpoint must be public, fast, and safe to receive twice.
Callback Mechanisms
The transition from the synchronous request-response cycle of initiating an STK Push, as detailed in the previous section, to the asynchronous callback mechanism is the most critical juncture in the Mpesa Daraja integration lifecycle. While the initial request confirms that Safaricom’s gateway has accepted the transaction command, it does not confirm that the customer has entered their PIN or that the funds have been successfully moved; that confirmation is delivered exclusively through the callback mechanism, which serves as the definitive source of truth for transaction finality.
The Fundamental Necessity of Callbacks: Polling vs. Callbacks
To understand the architecture of Mpesa integration, one must first distinguish between the two primary methods of state synchronization: polling and callbacks. Polling is a pull-based communication pattern where a client, in this case, the merchant’s server, repeatedly requests the status of a transaction from the server (Safaricom’s Mpesa platform). In a polling-based architecture, the merchant’s application would maintain a loop, perhaps querying the QueryTransactionStatus API every five seconds to determine if a CheckoutRequestID has transitioned from "PENDING" to "COMPLETED" or "FAILED."
The drawbacks of polling are systemic and severe. First, it introduces artificial latency; if the polling interval is set to ten seconds, the merchant’s system will, on average, be five seconds behind the actual transaction state. Second, it creates an immense, unnecessary load on the infrastructure of both the merchant and Safaricom. If a merchant processes 1,000 transactions simultaneously, a polling frequency of once every five seconds results in 12,000 requests per minute, the vast majority of which return the same "PENDING" status. This consumes network bandwidth, CPU cycles, and database connections without providing any new information. Third, polling requires the merchant to manage complex state machines to track which transactions are still active, when they were last checked, and how to handle timeouts in the polling loop itself.
Callbacks, or webhooks, represent a push-based communication paradigm that resolves these inefficiencies. In this model, the merchant’s server exposes a publicly accessible URL—the listener endpoint—and registers this URL with Safaricom. When the transaction state changes, Safaricom’s platform proactively sends an HTTP POST request to that endpoint. This ensures that the merchant’s system is notified exactly when the event occurs, with zero polling overhead. The callback mechanism is not merely an optimization; it is the standard for high-throughput, real-time financial systems where the cost of delayed state updates includes lost revenue, customer dissatisfaction, and operational reconciliation errors.
Core Concepts and Mechanisms of the Callback Architecture
A webhook is defined as a user-defined HTTP callback that is triggered by specific events within a source system. In the context of Mpesa, the "source system" is the Mpesa Daraja platform, and the "event" is the finalization of a payment transaction. The listener endpoint is the destination for these events. It must be a server capable of receiving and parsing HTTP POST requests.
The HTTP POST method is the transport vehicle for these callbacks. Unlike the GET method, which is intended for data retrieval and should be idempotent (meaning multiple identical requests should have the same effect as a single request), the POST method is designed to send data to a server for processing. When Safaricom sends a callback, it includes a JSON payload in the request body. This payload contains the transaction metadata, such as the MpesaReceiptNumber, Amount, PhoneNumber, and the ResultCode. The ResultCode is the most important field in the payload; a value of 0 indicates success, while any non-zero value indicates a failure, with the ResultDesc field providing the human-readable reason for that failure.
Mpesa Daraja Callback Architecture and Data Flow
The lifecycle of a callback begins the moment the customer completes the STK Push prompt on their mobile device. Once the customer enters their PIN and the Mpesa core banking system processes the debit, Safaricom’s Daraja platform triggers the callback generation engine. This engine packages the transaction results into a structured JSON object.
The data flow follows a strict sequence:
- Transaction Finalization: The Mpesa core system updates the transaction status.
- Payload Construction: The Daraja platform generates a JSON object. For an STK Push, this object is nested within a
Body->stkCallbackstructure. - HTTP POST Transmission: The Daraja platform initiates an HTTP POST request to the merchant’s registered URL.
- Network Transit: The request travels over the public internet, typically secured via TLS (Transport Layer Security).
- Endpoint Reception: The merchant’s web server receives the request and routes it to the application logic.
- Processing and Idempotency Check: The application parses the JSON, checks if the
CheckoutRequestIDhas already been processed, and updates the database. - Acknowledgment: The application returns an HTTP 200 OK response to Safaricom.
The following sequence diagram illustrates this interaction: