How M-Pesa STK Push integration works
A step-by-step developer guide to the Safaricom Daraja STK Push flow: getting a token, sending the request, handling the callback and reconciling payments, with a Spring Boot example.
What STK Push is
STK Push, also called M-Pesa Express, lets your system ask a customer to pay by popping up a prompt on their phone. The customer checks the amount, enters their M-Pesa PIN, and your system is told the result automatically. No one has to copy transaction codes or match payments by hand.
Endpoints and fields can change. Always check the official Safaricom Daraja documentation for the current details before you build.
The flow in five steps
Step 1: Credentials and sandbox
Create an account on the Safaricom Daraja developer portal, create an app and note its consumer key and consumer secret. In the sandbox you can use the test shortcode 174379 with the passkey shown in the portal. For production you need your own Paybill or Till number and go through Safaricom's go-live process.
Step 2: Get an access token
Call the OAuth endpoint with HTTP Basic authentication. The response contains an access token that expires after a short time, so cache it and refresh it when needed.
GET https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials
Authorization: Basic base64(consumerKey:consumerSecret)Step 3: Build the password and timestamp
The Timestamp is the current time as yyyyMMddHHmmss. The Password is the Base64 encoding of your shortcode, passkey and timestamp joined together. Generate the timestamp in East Africa Time, because a server running in UTC can produce a mismatched value.
Step 4: Send the request
Post the request with your access token. Phone numbers must be in the 2547XXXXXXXX format. Use CustomerPayBillOnline for a Paybill and CustomerBuyGoodsOnline for a Till.
POST https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest
Authorization: Bearer <access_token>
Content-Type: application/json
{
"BusinessShortCode": "174379",
"Password": "base64(BusinessShortCode + Passkey + Timestamp)",
"Timestamp": "20261023143000",
"TransactionType": "CustomerPayBillOnline",
"Amount": 1,
"PartyA": "2547XXXXXXXX",
"PartyB": "174379",
"PhoneNumber": "2547XXXXXXXX",
"CallBackURL": "https://yourdomain.co.ke/mpesa/callback",
"AccountReference": "INV-2041",
"TransactionDesc": "Invoice payment"
}A successful response only means the prompt was sent to the phone. It does not mean the customer has paid. Keep the returned CheckoutRequestID, because it links the callback to your order.
Step 5: Handle the callback
Safaricom sends the result to your CallBackURL as JSON. A ResultCode of 0 means success. Anything else is a failure or cancellation, with the reason in ResultDesc.
{
"Body": {
"stkCallback": {
"MerchantRequestID": "...",
"CheckoutRequestID": "ws_CO_...",
"ResultCode": 0,
"ResultDesc": "The service request is processed successfully.",
"CallbackMetadata": {
"Item": [
{ "Name": "Amount", "Value": 1.00 },
{ "Name": "MpesaReceiptNumber", "Value": "QK..." },
{ "Name": "TransactionDate", "Value": 20261023143015 },
{ "Name": "PhoneNumber", "Value": 2547XXXXXXXX }
]
}
}
}
}Rules for a safe callback endpoint
- It must be a publicly reachable HTTPS URL.
- Match the callback to your order using
CheckoutRequestID. - Be idempotent: if the same callback arrives twice, only credit the order once.
- Answer quickly and do slow work afterwards.
- Store the full payload for audit and troubleshooting.
Step 6: Do not rely on the callback alone
Callbacks can be delayed or lost. For any order still pending after a reasonable time, use the STK Push query endpoint with the CheckoutRequestID to ask Safaricom what happened, then update the order. This reconciliation step is what separates a demo from a production system.
Example in Spring Boot
Here is the request step in Java using Spring's RestClient:
String ts = LocalDateTime.now(ZoneId.of("Africa/Nairobi"))
.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
String password = Base64.getEncoder().encodeToString(
(shortcode + passkey + ts).getBytes(StandardCharsets.UTF_8));
var body = Map.ofEntries(
Map.entry("BusinessShortCode", shortcode),
Map.entry("Password", password),
Map.entry("Timestamp", ts),
Map.entry("TransactionType", "CustomerPayBillOnline"),
Map.entry("Amount", amount),
Map.entry("PartyA", phone),
Map.entry("PartyB", shortcode),
Map.entry("PhoneNumber", phone),
Map.entry("CallBackURL", callbackUrl),
Map.entry("AccountReference", reference),
Map.entry("TransactionDesc", "Payment"));
String response = restClient.post()
.uri(baseUrl + "/mpesa/stkpush/v1/processrequest")
.header("Authorization", "Bearer " + accessToken)
.body(body)
.retrieve()
.body(String.class);Common mistakes
- Treating the first response as proof of payment.
- Using a callback URL that is not public or not HTTPS.
- Generating the timestamp in the wrong time zone.
- Hard-coding the consumer key, secret or passkey in source code.
- Crediting the customer twice when a callback repeats.
Want this built and tested properly for your business? See our M-Pesa integration service.
Ready to get started?
Tell us what you need and we will reply with a clear plan. Call, text or WhatsApp 0707 083 949, or email support@mabiznahub.co.ke.