M-Pesa Daraja STK Push (Lipa na M-Pesa Online)

Accept M-Pesa payments in Kenya by sending a PIN prompt to the customer's phone: OAuth token, STK Push, callback handling, STK query, Transaction Status and reversals.

Provider
M-Pesa (Safaricom Daraja API)
Level
Intermediate
Stacks
Node.js (Express), Python (FastAPI), PHP (Laravel), React, cURL
Code maturity
Sandbox-ready
Last verified
25 Nov 2026

Introduction

M-Pesa is Kenya's dominant mobile-money service, and Daraja is Safaricom's developer platform for its APIs. The most common integration for online checkouts is M-Pesa Express, better known as STK Push or Lipa na M-Pesa Online: your server asks Safaricom to show a payment prompt on the customer's phone, the customer enters their M-Pesa PIN, and Safaricom calls your server back with the result.

This guide builds the full loop in sandbox: get an OAuth token, send an STK Push, receive the callback, confirm the result with the STK query API, and keep your order records consistent even when callbacks arrive late, twice, or never.

Tip: Daraja 3.0's documentation pages are rendered in the browser. Field names and limits in this guide were checked against the portal's own simulator on 2026-11-25; always compare with the portal before going live.

What STK Push does

STK Push is a merchant-initiated customer payment. Instead of the customer typing your Paybill or Till number into the M-Pesa menu, your backend triggers the prompt for them.

  • Your backend calls POST /mpesa/stkpush/v1/processrequest with your shortcode, a password, the amount and the customer's phone number.
  • Safaricom answers immediately with a MerchantRequestID and CheckoutRequestID — this only means the request was accepted, not paid.
  • The customer sees a SIM-toolkit prompt and enters their PIN (or cancels, or ignores it).
  • Safaricom POSTs the final result to your CallBackURL. You can also ask for the result with POST /mpesa/stkpushquery/v1/query.

Countries and currency

Daraja (developer.safaricom.co.ke) serves M-Pesa Kenya, so payments are in KES from Safaricom M-Pesa customers. M-Pesa also operates in other countries through Vodacom and other operators, but those markets use different APIs and portals — this guide does not apply to them.

Phone numbers must be in international format without +, for example 2547XXXXXXXX or 2541XXXXXXXX (the portal's hint: "Ensure your number starts with the country code 254").

Payment methods covered

  • STK Push (M-Pesa Express) — customer pays your Paybill (CustomerPayBillOnline) or Till (CustomerBuyGoodsOnline) after a PIN prompt. Covered in depth here.
  • C2B — customer pays from their own M-Pesa menu and Safaricom notifies your validation/confirmation URLs. Mentioned only.
  • B2C — your business pays out to customers (mpesa/b2c/v1/paymentrequest in the portal simulator). Needs separate approval and an initiator. Mentioned only.
  • Transaction Status and Reversal — back-office APIs for checking or reversing a completed M-Pesa transaction. Covered briefly in the status-check and refunds sections.

When to use STK Push

  • Your customers are in Kenya and expect to pay with M-Pesa (most of them do).
  • You want a checkout where the customer only confirms with their PIN — no card details, no typing a Paybill number.
  • You have (or can get) a registered Paybill or Till number from Safaricom.
  • You can run a backend with a public HTTPS endpoint to receive callbacks.

When not to use it

  • You need cards, multiple countries or multiple wallets from one integration — an aggregator (for example Pesapal, Paystack or Flutterwave) may be simpler.
  • You have no registered business shortcode yet — you can build in sandbox, but you cannot go live without one.
  • You cannot host a public HTTPS callback endpoint (a pure static site or a mobile app with no backend).
  • You need instant payouts to customers — that is B2C, a different product with stricter onboarding.

Real-world scenarios

  • E-commerce in Kenya: the customer enters their phone number at checkout, approves the prompt, and the order page flips to "Paid" once your backend has the confirmed result.
  • SaaS invoice payment: your billing page sends an STK Push for the invoice amount with the invoice number as AccountReference.
  • Event tickets or school fees: use the ticket or student number as AccountReference so the payment is easy to reconcile in M-Pesa statements.
  • Mobile app: the app calls YOUR backend, which calls Daraja. The app never holds Daraja credentials.

Registration and onboarding

  • Create an account on the Daraja portal and create an app in the sandbox. The app gives you a Consumer Key and Consumer Secret.
  • Build and test everything against the sandbox.
  • To go live you need a registered M-Pesa Paybill or Till (Buy Goods) number for your business. Use the portal's Go Live flow to link your production app to that shortcode.
  • The production passkey for M-Pesa Express is issued by Safaricom after go-live approval — it is not the sandbox passkey.

Warning: Go-live requirements (documents, who may approve, turnaround time) change and are not published as a fixed list on the portal. Check the portal's Go Live section and Safaricom support before planning a launch date.

Sandbox environment

  • Sandbox base URL: https://sandbox.safaricom.co.ke
  • Production base URL: https://api.safaricom.co.ke

The portal shows test credentials for each sandbox app, including a test Business Shortcode and Passkey for M-Pesa Express and a test phone number. Copy them from the portal (APIs → M-Pesa Express) into your .env — do not hard-code them.

In sandbox you can put your own Safaricom number (format 2547...) as PhoneNumber to receive a real test prompt; the portal simulator suggests exactly this. Sandbox amounts are not charged in the normal sense, but use small values such as 1.

Tip: Many tutorials quote shortcode 174379 as the sandbox M-Pesa Express shortcode. Treat whatever the portal shows for your app as the source of truth.

Credentials you need

  • Consumer Key / Consumer Secret — per app; used to get an OAuth access token.
  • Business Shortcode — your Paybill, or for Till payments the store/head-office number that owns the Till.
  • Passkey — Lipa na M-Pesa Online passkey; used to build the request Password.
  • Initiator name + initiator password + Safaricom public certificate — only for back-office APIs (Transaction Status, Reversal, B2C). The password is encrypted into a SecurityCredential.

All of these are secrets. Keep them in environment variables or a secrets manager on the server only.

Security: Never ship the consumer secret or passkey in a React, Flutter or mobile bundle. Anyone can extract them and initiate requests as your business.

Environment configuration

Create a .env file for local development (never commit it) and a committed .env.example with placeholders. MPESA_CALLBACK_TOKEN is a random string you generate; it becomes part of the callback URL so that random internet traffic cannot reach your handler (Daraja callbacks are not signed — see the webhooks section).

.env.example · cURL

# Daraja (M-Pesa Kenya) — copy to .env and fill in from the Daraja portal
MPESA_ENV=sandbox                      # sandbox | production
MPESA_CONSUMER_KEY=replace-me
MPESA_CONSUMER_SECRET=replace-me
MPESA_SHORTCODE=replace-with-test-shortcode-from-portal
MPESA_PASSKEY=replace-with-test-passkey-from-portal
MPESA_TRANSACTION_TYPE=CustomerPayBillOnline   # or CustomerBuyGoodsOnline for a Till
MPESA_PARTY_B=                          # leave empty for Paybill; Till number for Buy Goods
# Public HTTPS URL that reaches your server (use a tunnel such as ngrok in development)
MPESA_CALLBACK_URL=https://your-public-host.example.com/mpesa/callback
# Long random value, e.g. from: openssl rand -hex 24
MPESA_CALLBACK_TOKEN=replace-with-random-hex
PORT=3000

Authentication (OAuth access token)

Every Daraja call needs a bearer token from GET /oauth/v1/generate?grant_type=client_credentials, authenticated with HTTP Basic auth: base64(consumerKey:consumerSecret).

The response contains access_token and expires_in (seconds, as a string; typically about an hour). Cache the token and refresh it shortly before expiry instead of requesting a new one per payment.

The module below is reused by every Node example in this guide. It also builds the Timestamp (YYYYMMDDHHmmss, Kenyan time) and the Password = base64(Shortcode + Passkey + Timestamp), exactly as the portal simulator describes it.

mpesa.mjs — token cache, timestamp, password (Node 18+) · Node.js (Express)

// mpesa.mjs — shared Daraja helpers. Node 18+ (global fetch).
export const BASE_URL = process.env.MPESA_ENV === "production"
  ? "https://api.safaricom.co.ke"
  : "https://sandbox.safaricom.co.ke";

let cache = { token: null, expiresAt: 0 };

export async function getAccessToken() {
  if (cache.token && Date.now() < cache.expiresAt) return cache.token;
  const basic = Buffer.from(
    process.env.MPESA_CONSUMER_KEY + ":" + process.env.MPESA_CONSUMER_SECRET
  ).toString("base64");
  const res = await fetch(BASE_URL + "/oauth/v1/generate?grant_type=client_credentials", {
    headers: { Authorization: "Basic " + basic },
  });
  if (!res.ok) throw new Error("Daraja OAuth failed with HTTP " + res.status);
  const body = await res.json();
  const ttlSeconds = Number(body.expires_in) || 3599;
  // Refresh one minute early so an in-flight request never uses an expired token.
  cache = { token: body.access_token, expiresAt: Date.now() + (ttlSeconds - 60) * 1000 };
  return cache.token;
}

// YYYYMMDDHHmmss in East Africa Time (UTC+3, no daylight saving).
export function darajaTimestamp(date = new Date()) {
  const eat = new Date(date.getTime() + 3 * 60 * 60 * 1000);
  return eat.toISOString().replace(/[-:TZ.]/g, "").slice(0, 14);
}

export function stkPassword(timestamp) {
  return Buffer.from(
    process.env.MPESA_SHORTCODE + process.env.MPESA_PASSKEY + timestamp
  ).toString("base64");
}

export async function darajaPost(path, payload) {
  const token = await getAccessToken();
  const res = await fetch(BASE_URL + path, {
    method: "POST",
    headers: { Authorization: "Bearer " + token, "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  });
  const body = await res.json().catch(() => ({}));
  if (!res.ok) {
    // Daraja errors look like { requestId, errorCode, errorMessage }
    const err = new Error(body.errorMessage || "Daraja HTTP " + res.status);
    err.code = body.errorCode;
    err.status = res.status;
    throw err;
  }
  return body;
}

Get a sandbox token with curl · cURL

# Reads MPESA_CONSUMER_KEY / MPESA_CONSUMER_SECRET from your shell environment
curl -s -u "$MPESA_CONSUMER_KEY:$MPESA_CONSUMER_SECRET" \
  "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"
# => {"access_token":"...","expires_in":"3599"}

Warning: A wrong key/secret pair, extra whitespace in the .env value, or calling the production URL with sandbox keys all fail at this step. Fix the token before debugging anything else.

Backend: initiate, receive the callback, update the order once

The backend owns three jobs:

  • Initiate: load the order from YOUR database, take the amount from the order (never from the browser), and call STK Push. Save the returned CheckoutRequestID on the order.
  • Receive the callback: look up the order by CheckoutRequestID, check the amount, and move it from PENDING to PAID or FAILED exactly once.
  • Report status: give the frontend a read-only endpoint to poll.

The Node example keeps orders in a Map so it runs with no database. In production use your database with a unique index on checkoutRequestId and on the M-Pesa receipt number, and do the status change as a single conditional update (WHERE status = 'PENDING').

server.mjs — Express STK Push + callback (npm i express dotenv) · Node.js (Express)

import "dotenv/config";
import express from "express";
import crypto from "node:crypto";
import { darajaPost, darajaTimestamp, stkPassword } from "./mpesa.mjs";

const app = express();
app.use(express.json({ limit: "100kb" }));

// Demo store. Replace with a DB table: unique(checkoutRequestId), unique(mpesaReceipt).
const orders = new Map([["order-1001", { id: "order-1001", amountKes: 1, status: "PENDING" }]]);

app.post("/api/orders/:id/pay", async (req, res) => {
  const order = orders.get(req.params.id);
  if (!order || order.status !== "PENDING") return res.status(404).json({ error: "Order not payable" });
  const phone = String(req.body.phone || "").trim();
  if (!/^254(7|1)\d{8}$/.test(phone)) return res.status(400).json({ error: "Use format 2547XXXXXXXX" });

  const timestamp = darajaTimestamp();
  try {
    const out = await darajaPost("/mpesa/stkpush/v1/processrequest", {
      BusinessShortCode: process.env.MPESA_SHORTCODE,
      Password: stkPassword(timestamp),
      Timestamp: timestamp,
      TransactionType: process.env.MPESA_TRANSACTION_TYPE || "CustomerPayBillOnline",
      Amount: order.amountKes,                 // whole shillings, from YOUR order record
      PartyA: phone,
      PartyB: process.env.MPESA_PARTY_B || process.env.MPESA_SHORTCODE,
      PhoneNumber: phone,
      CallBackURL: process.env.MPESA_CALLBACK_URL + "/" + process.env.MPESA_CALLBACK_TOKEN,
      AccountReference: order.id.slice(0, 12), // portal limit: 12 characters
      TransactionDesc: "Order payment",        // portal limit: 13 characters
    });
    if (out.ResponseCode !== "0") return res.status(502).json({ error: out.ResponseDescription });
    order.checkoutRequestId = out.CheckoutRequestID;
    res.json({ status: "PROMPT_SENT", message: out.CustomerMessage });
  } catch (err) {
    console.error("STK push failed", err.code, err.message);
    res.status(502).json({ error: "Could not start M-Pesa payment" });
  }
});

app.post("/mpesa/callback/:token", (req, res) => {
  const expected = Buffer.from(process.env.MPESA_CALLBACK_TOKEN || "");
  const given = Buffer.from(req.params.token || "");
  if (expected.length === 0 || given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) {
    return res.sendStatus(404);
  }
  res.json({ ResultCode: 0, ResultDesc: "Accepted" }); // acknowledge fast, then process

  const cb = req.body?.Body?.stkCallback;
  if (!cb) return;
  const order = [...orders.values()].find((o) => o.checkoutRequestId === cb.CheckoutRequestID);
  if (!order || order.status !== "PENDING") return; // unknown or already final: idempotent no-op

  if (cb.ResultCode !== 0) {
    order.status = "FAILED";
    order.failure = cb.ResultCode + " " + cb.ResultDesc;
    return;
  }
  const meta = Object.fromEntries((cb.CallbackMetadata?.Item || []).map((i) => [i.Name, i.Value]));
  if (Number(meta.Amount) !== order.amountKes) {
    order.status = "REVIEW"; // amount mismatch: never auto-fulfil
    return;
  }
  order.status = "PAID";
  order.mpesaReceipt = meta.MpesaReceiptNumber;
  order.paidAt = String(meta.TransactionDate);
});

app.get("/api/orders/:id", (req, res) => {
  const o = orders.get(req.params.id);
  if (!o) return res.sendStatus(404);
  res.json({ id: o.id, status: o.status, receipt: o.mpesaReceipt || null });
});

app.listen(process.env.PORT || 3000, () => console.log("listening"));

main.py — FastAPI STK Push + callback (pip install fastapi uvicorn httpx) · Python (FastAPI)

import base64, hmac, os, re, time
from datetime import datetime, timedelta, timezone
import httpx
from fastapi import FastAPI, HTTPException, Request

BASE = "https://api.safaricom.co.ke" if os.getenv("MPESA_ENV") == "production" else "https://sandbox.safaricom.co.ke"
ENV = os.environ
app = FastAPI()
orders = {"order-1001": {"id": "order-1001", "amount_kes": 1, "status": "PENDING"}}  # use a DB in real apps
_token = {"value": None, "exp": 0.0}

async def token() -> str:
    if _token["value"] and time.time() < _token["exp"]:
        return _token["value"]
    async with httpx.AsyncClient(timeout=30) as c:
        r = await c.get(f"{BASE}/oauth/v1/generate", params={"grant_type": "client_credentials"},
                        auth=(ENV["MPESA_CONSUMER_KEY"], ENV["MPESA_CONSUMER_SECRET"]))
    r.raise_for_status()
    body = r.json()
    _token.update(value=body["access_token"], exp=time.time() + int(body.get("expires_in", 3599)) - 60)
    return _token["value"]

def timestamp() -> str:
    return datetime.now(timezone(timedelta(hours=3))).strftime("%Y%m%d%H%M%S")

@app.post("/api/orders/{order_id}/pay")
async def pay(order_id: str, payload: dict):
    order = orders.get(order_id)
    if not order or order["status"] != "PENDING":
        raise HTTPException(404, "Order not payable")
    phone = str(payload.get("phone", "")).strip()
    if not re.fullmatch(r"254(7|1)\d{8}", phone):
        raise HTTPException(400, "Use format 2547XXXXXXXX")
    ts = timestamp()
    password = base64.b64encode((ENV["MPESA_SHORTCODE"] + ENV["MPESA_PASSKEY"] + ts).encode()).decode()
    body = {
        "BusinessShortCode": ENV["MPESA_SHORTCODE"], "Password": password, "Timestamp": ts,
        "TransactionType": ENV.get("MPESA_TRANSACTION_TYPE", "CustomerPayBillOnline"),
        "Amount": order["amount_kes"], "PartyA": phone,
        "PartyB": ENV.get("MPESA_PARTY_B") or ENV["MPESA_SHORTCODE"], "PhoneNumber": phone,
        "CallBackURL": f"{ENV['MPESA_CALLBACK_URL']}/{ENV['MPESA_CALLBACK_TOKEN']}",
        "AccountReference": order_id[:12], "TransactionDesc": "Order payment",
    }
    async with httpx.AsyncClient(timeout=30) as c:
        r = await c.post(f"{BASE}/mpesa/stkpush/v1/processrequest", json=body,
                         headers={"Authorization": f"Bearer {await token()}"})
    out = r.json()
    if r.status_code != 200 or out.get("ResponseCode") != "0":
        raise HTTPException(502, out.get("errorMessage") or out.get("ResponseDescription", "STK push failed"))
    order["checkout_request_id"] = out["CheckoutRequestID"]
    return {"status": "PROMPT_SENT", "message": out.get("CustomerMessage")}

@app.post("/mpesa/callback/{token_in_url}")
async def callback(token_in_url: str, request: Request):
    if not hmac.compare_digest(token_in_url, ENV.get("MPESA_CALLBACK_TOKEN", "")):
        raise HTTPException(404)
    cb = (await request.json()).get("Body", {}).get("stkCallback", {})
    order = next((o for o in orders.values() if o.get("checkout_request_id") == cb.get("CheckoutRequestID")), None)
    if order and order["status"] == "PENDING":  # idempotent: only PENDING orders change
        if cb.get("ResultCode") != 0:
            order["status"] = "FAILED"
        else:
            meta = {i["Name"]: i.get("Value") for i in cb.get("CallbackMetadata", {}).get("Item", [])}
            ok = int(meta.get("Amount", -1)) == order["amount_kes"]
            order.update(status="PAID" if ok else "REVIEW", receipt=meta.get("MpesaReceiptNumber"))
    return {"ResultCode": 0, "ResultDesc": "Accepted"}

@app.get("/api/orders/{order_id}")
async def status(order_id: str):
    o = orders.get(order_id) or {}
    return {"id": order_id, "status": o.get("status"), "receipt": o.get("receipt")}

Security: The amount always comes from your order record on the server. If the browser could send the amount, a customer could pay KES 1 for a KES 10,000 order.

Tip: Daraja's Amount is whole Kenyan shillings, not cents. If your database stores minor units, divide by 100 and reject non-whole values before calling the API.

Frontend: collect the phone number and wait for the result

The frontend only talks to your backend. It sends the order id and phone number, tells the customer to check their phone, then polls your order-status endpoint. It never decides that a payment succeeded — it only displays what your server has confirmed.

PayWithMpesa.jsx — trigger the prompt and poll your backend · React

import { useEffect, useRef, useState } from "react";

export default function PayWithMpesa({ orderId }) {
  const [phone, setPhone] = useState("");
  const [state, setState] = useState("idle"); // idle | sending | waiting | PAID | FAILED | error
  const [message, setMessage] = useState("");
  const timer = useRef(null);

  useEffect(() => () => clearInterval(timer.current), []);

  async function pay(e) {
    e.preventDefault();
    setState("sending");
    const res = await fetch("/api/orders/" + orderId + "/pay", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ phone }),
    });
    const body = await res.json().catch(() => ({}));
    if (!res.ok) { setState("error"); setMessage(body.error || "Could not start payment"); return; }
    setState("waiting");
    setMessage("Check your phone and enter your M-Pesa PIN.");
    const started = Date.now();
    timer.current = setInterval(async () => {
      const s = await fetch("/api/orders/" + orderId).then((r) => r.json());
      if (s.status === "PAID" || s.status === "FAILED") {
        clearInterval(timer.current);
        setState(s.status);
        setMessage(s.status === "PAID" ? "Payment received. Receipt " + s.receipt : "Payment was not completed.");
      } else if (Date.now() - started > 120000) {
        clearInterval(timer.current);
        setState("error");
        setMessage("Still waiting for M-Pesa. We will update your order when the result arrives.");
      }
    }, 4000);
  }

  return (
    <form onSubmit={pay}>
      <label htmlFor="mpesa-phone">M-Pesa phone number</label>
      <input id="mpesa-phone" inputMode="numeric" placeholder="2547XXXXXXXX"
        value={phone} onChange={(e) => setPhone(e.target.value.trim())} />
      <button type="submit" disabled={state === "sending" || state === "waiting"}>Pay with M-Pesa</button>
      <p role="status" aria-live="polite">{message}</p>
    </form>
  );
}

Initiating an STK Push (raw request)

POST {base}/mpesa/stkpush/v1/processrequest with Authorization: Bearer <token> and a JSON body. Fields (names are case-sensitive):

  • BusinessShortCode — your Paybill or store number.
  • Password — base64(BusinessShortCode + Passkey + Timestamp).
  • Timestamp — YYYYMMDDHHmmss; must be the same value used inside the password.
  • TransactionType — CustomerPayBillOnline (Paybill) or CustomerBuyGoodsOnline (Till).
  • Amount — whole KES, at least 1.
  • PartyA — the paying phone number; PartyB — the receiving shortcode (Paybill) or Till number.
  • PhoneNumber — the phone that receives the PIN prompt (normally the same as PartyA).
  • CallBackURL — public HTTPS URL for the result.
  • AccountReference — up to 12 characters (shown to the customer); TransactionDesc — up to 13 characters.

A successful response has ResponseCode: "0", MerchantRequestID, CheckoutRequestID, ResponseDescription and CustomerMessage.

STK Push with curl (sandbox) · cURL

TOKEN="paste-access-token-here"
TS=$(TZ=Africa/Nairobi date +%Y%m%d%H%M%S)
PASSWORD=$(printf "%s%s%s" "$MPESA_SHORTCODE" "$MPESA_PASSKEY" "$TS" | base64 -w0)

curl -s -X POST "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "BusinessShortCode": "'"$MPESA_SHORTCODE"'",
    "Password": "'"$PASSWORD"'",
    "Timestamp": "'"$TS"'",
    "TransactionType": "CustomerPayBillOnline",
    "Amount": 1,
    "PartyA": "2547XXXXXXXX",
    "PartyB": "'"$MPESA_SHORTCODE"'",
    "PhoneNumber": "2547XXXXXXXX",
    "CallBackURL": "https://your-public-host.example.com/mpesa/callback/your-token",
    "AccountReference": "order-1001",
    "TransactionDesc": "Order payment"
  }'

Laravel: MpesaService::stkPush() · PHP (Laravel)

<?php
// app/Services/MpesaService.php — uses Laravel's HTTP client and cache.
namespace App\Services;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class MpesaService
{
    private function base(): string
    {
        return config('services.mpesa.env') === 'production'
            ? 'https://api.safaricom.co.ke' : 'https://sandbox.safaricom.co.ke';
    }

    public function token(): string
    {
        return Cache::remember('mpesa_token', now()->addMinutes(55), function () {
            $res = Http::withBasicAuth(config('services.mpesa.key'), config('services.mpesa.secret'))
                ->get($this->base() . '/oauth/v1/generate', ['grant_type' => 'client_credentials'])
                ->throw();
            return $res->json('access_token');
        });
    }

    public function stkPush(string $phone, int $amountKes, string $reference): array
    {
        $shortcode = config('services.mpesa.shortcode');
        $timestamp = now('Africa/Nairobi')->format('YmdHis');
        $password = base64_encode($shortcode . config('services.mpesa.passkey') . $timestamp);

        return Http::withToken($this->token())
            ->post($this->base() . '/mpesa/stkpush/v1/processrequest', [
                'BusinessShortCode' => $shortcode,
                'Password' => $password,
                'Timestamp' => $timestamp,
                'TransactionType' => config('services.mpesa.type', 'CustomerPayBillOnline'),
                'Amount' => $amountKes,
                'PartyA' => $phone,
                'PartyB' => config('services.mpesa.party_b') ?: $shortcode,
                'PhoneNumber' => $phone,
                'CallBackURL' => config('services.mpesa.callback_url') . '/' . config('services.mpesa.callback_token'),
                'AccountReference' => substr($reference, 0, 12),
                'TransactionDesc' => 'Order payment',
            ])->throw()->json();
    }
}
// config/services.php: 'mpesa' => ['env' => env('MPESA_ENV'), 'key' => env('MPESA_CONSUMER_KEY'), ...]

Confirming the payment

A payment is confirmed only when your server has a final result from Safaricom — either the callback with ResultCode 0, or an STK query that returns ResultCode "0". On success the callback's CallbackMetadata.Item list contains Amount, MpesaReceiptNumber, TransactionDate (as a number like 20261125143015) and PhoneNumber.

Before fulfilling, check that the order is still PENDING, the CheckoutRequestID matches, and the amount equals the order amount. Store the MpesaReceiptNumber — it is the reference customers and Safaricom support will quote.

Example success callback body (shape) · Node.js (Express)

{
  "Body": {
    "stkCallback": {
      "MerchantRequestID": "29115-34620561-1",
      "CheckoutRequestID": "ws_CO_191220191020363925",
      "ResultCode": 0,
      "ResultDesc": "The service request is processed successfully.",
      "CallbackMetadata": {
        "Item": [
          { "Name": "Amount", "Value": 1.0 },
          { "Name": "MpesaReceiptNumber", "Value": "NLJ7RT61SV" },
          { "Name": "TransactionDate", "Value": 20191219102115 },
          { "Name": "PhoneNumber", "Value": 254708374149 }
        ]
      }
    }
  }
}

Warning: Failed or cancelled payments have a non-zero ResultCode and usually no CallbackMetadata. Parse defensively and never assume the Item list exists.

Tip: The example IDs above are illustrative values in the shape Daraja uses; the exact sample body on the portal could not be copied because the docs are client-rendered.

Callbacks (webhooks) and how to trust them

Daraja sends the STK result as a JSON POST to your CallBackURL. Unlike Paystack or Flutterwave, Daraja callbacks carry no signature header, so you cannot cryptographically prove a callback came from Safaricom. Defend in layers:

  • Secret path token: include a long random token in the callback URL (as in the examples) and compare it in constant time. Rotate it if it leaks.
  • Cross-check: the callback must reference a CheckoutRequestID you created, for an order that is still PENDING, with the exact amount.
  • Confirm when in doubt: for high-value orders, call the STK query API before fulfilling, so a forged callback cannot mark an order paid.
  • Optional: restrict the callback route to Safaricom's egress IP ranges if Safaricom support provides them to you (they are not published on the docs pages we checked).
  • Respond quickly with HTTP 200 and process after acknowledging; keep the handler idempotent because duplicates and late deliveries happen.

Laravel callback controller with idempotent update · PHP (Laravel)

<?php
// routes/api.php: Route::post('/mpesa/callback/{token}', MpesaCallbackController::class);
namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class MpesaCallbackController extends Controller
{
    public function __invoke(Request $request, string $token)
    {
        abort_unless(hash_equals((string) config('services.mpesa.callback_token'), $token), 404);

        $cb = $request->input('Body.stkCallback', []);
        $items = collect(data_get($cb, 'CallbackMetadata.Item', []))->pluck('Value', 'Name');

        DB::transaction(function () use ($cb, $items) {
            $order = Order::where('checkout_request_id', $cb['CheckoutRequestID'] ?? null)
                ->lockForUpdate()->first();
            if (! $order || $order->status !== 'pending') {
                return; // unknown or already final: idempotent no-op
            }
            if ((int) ($cb['ResultCode'] ?? -1) !== 0) {
                $order->update(['status' => 'failed', 'failure_reason' => $cb['ResultDesc'] ?? null]);
                return;
            }
            $paidOk = (int) $items->get('Amount') === (int) $order->amount_kes;
            $order->update([
                'status' => $paidOk ? 'paid' : 'review',
                'mpesa_receipt' => $items->get('MpesaReceiptNumber'), // unique column
            ]);
        });

        return response()->json(['ResultCode' => 0, 'ResultDesc' => 'Accepted']);
    }
}

Security: Never treat a callback as proof by itself if the URL could be guessed. A secret token in the path plus an amount and CheckoutRequestID check is the minimum; an STK query before shipping valuable goods is better.

Status check: STK query and Transaction Status

Callbacks can be delayed or lost (your server was down, a proxy rejected it). Run a job that queries every order still PENDING a minute or two after initiation.

STK query — POST /mpesa/stkpushquery/v1/query with BusinessShortCode, Password, Timestamp (new timestamp, same formula) and CheckoutRequestID. While the customer has not finished, Daraja typically answers with an error saying the transaction is still being processed; retry later. A final answer contains ResultCode and ResultDesc ("0" = paid).

Transaction Status — POST /mpesa/transactionstatus/v1/query looks up a completed M-Pesa transaction by its receipt (TransactionID). It needs an Initiator, an encrypted SecurityCredential, CommandID: "TransactionStatusQuery", PartyA (your shortcode), IdentifierType (4 for a shortcode), ResultURL, QueueTimeOutURL, Remarks and Occassion (Safaricom's spelling). The answer arrives asynchronously at your ResultURL.

reconcile.mjs — query pending STK requests · Node.js (Express)

import { darajaPost, darajaTimestamp, stkPassword } from "./mpesa.mjs";

// Call for each order that is still PENDING ~60s after the prompt was sent.
export async function queryStk(checkoutRequestId) {
  const timestamp = darajaTimestamp();
  try {
    const out = await darajaPost("/mpesa/stkpushquery/v1/query", {
      BusinessShortCode: process.env.MPESA_SHORTCODE,
      Password: stkPassword(timestamp),
      Timestamp: timestamp,
      CheckoutRequestID: checkoutRequestId,
    });
    // ResultCode is a string here, e.g. "0" (paid) or "1032" (cancelled by user)
    return { final: true, paid: out.ResultCode === "0", code: out.ResultCode, desc: out.ResultDesc };
  } catch (err) {
    // While the customer is still deciding, Daraja answers with an error such as
    // "The transaction is being processed". Treat it as "not final yet" and retry later.
    if (err.status === 500 || /being processed/i.test(err.message)) return { final: false };
    throw err;
  }
}

Tip: An STK query success tells you the payment went through but does not include the receipt number. Keep the order PENDING-to-PAID transition the same whichever path (callback or query) gets there first.

Refunds and reversals

M-Pesa Express has no "refund" call. Options:

  • Reversal API — POST /mpesa/reversal/v1/request with CommandID: "TransactionReversal", the original TransactionID (receipt), Amount, ReceiverParty (your shortcode), RecieverIdentifierType (Safaricom's spelling; the portal simulator uses "11"), Initiator, SecurityCredential, ResultURL, QueueTimeOutURL, Remarks, Occassion. The result is asynchronous. Reversal access is granted per organisation and is meant for genuine errors, not routine refunds.
  • B2C payment — pay the customer back from a B2C-enabled shortcode (mpesa/b2c/v1/paymentrequest in the portal simulator). Requires B2C onboarding and float.
  • Manual refund via the M-Pesa business portal (M-Pesa Org Portal) by your finance team.

SecurityCredential is your initiator password encrypted with Safaricom's public certificate (sandbox and production certificates are different) using RSA with PKCS#1 v1.5 padding, then base64-encoded.

securityCredential.mjs — encrypt the initiator password · Node.js (Express)

import { readFileSync } from "node:fs";
import crypto from "node:crypto";

// Download the sandbox or production certificate from the Daraja portal and point to it.
export function securityCredential(initiatorPassword, certPath = process.env.MPESA_CERT_PATH) {
  const cert = readFileSync(certPath, "utf8");
  return crypto
    .publicEncrypt({ key: cert, padding: crypto.constants.RSA_PKCS1_PADDING }, Buffer.from(initiatorPassword))
    .toString("base64");
}

Warning: Reversal and B2C eligibility, limits and approval steps are decided by Safaricom per business and are not fully documented publicly. Treat the reversal flow here as simplified and confirm with Safaricom before relying on it.

Errors and result codes

API errors (HTTP 4xx/5xx) have the shape { requestId, errorCode, errorMessage }. Verified against the sandbox on 2026-11-25:

  • 404.001.03 Invalid Access Token — token missing, expired, or from the other environment.
  • 404.001.04 Invalid Authentication Header — no Authorization: Bearer ... header at all.

Commonly reported (not re-verified here): 400.002.02 *Bad Request - Invalid ...* for a malformed field such as Timestamp, PhoneNumber or Amount; 500.001.1001 for problems such as a wrong passkey/shortcode pair or a query sent while the transaction is still being processed.

Callback ResultCode values you will see often: 0 success; 1032 request cancelled by the user; 1037 the phone could not be reached / no response in time; 1 insufficient balance; 2001 wrong PIN or invalid initiator information. Always store ResultDesc for support.

Warning: Result codes other than 0 are not an exhaustive or officially versioned list in the pages we could read. Handle any non-zero code as 'not paid' and log the description.

Going to production

  • Switch the base URL to https://api.safaricom.co.ke and use the production consumer key/secret, shortcode and passkey issued after go-live.
  • Make the callback URL a stable public HTTPS endpoint on your own domain (no tunnels), behind a valid certificate.
  • Use a real database with unique indexes on checkoutRequestId and mpesaReceipt; do order transitions in a transaction or conditional update.
  • Run a reconciliation job (STK query for stale PENDING orders) and a daily comparison against your M-Pesa statement.
  • Add monitoring: rate of 1032/1037, token failures, callback latency.
  • Rate-limit your /pay endpoint per user and per phone number so attackers cannot spam customers with prompts.

Security checklist

  • Secrets (consumer secret, passkey, initiator password, callback token) only in server-side environment variables or a secrets manager.
  • Amount and order details come from your database, never from the client.
  • Callback route protected by a secret path token compared in constant time; payloads validated; unknown CheckoutRequestIDs ignored.
  • Idempotent state changes: only PENDING orders can change; receipt numbers unique.
  • Confirm high-value payments with the STK query before fulfilment.
  • Log request ids and result codes, but never log the passkey, token or full credentials. Phone numbers are personal data — mask them in logs.
  • Rate-limit prompt initiation to prevent prompt-bombing customers.

Security: A client-side 'success' (for example the customer saying they paid, or your app closing the dialog) is never proof. Only a server-side callback or query result marks an order paid.

Testing

  • Expose your local server over HTTPS with a tunnel (for example ngrok or Cloudflare Tunnel) and set MPESA_CALLBACK_URL to the tunnel URL.
  • Trigger a payment to your own Safaricom number in sandbox and approve the prompt; then repeat and cancel it to see 1032.
  • Replay a callback to your handler with curl to check the duplicate path is a no-op.
  • Stop your server, make a payment, start it again, and confirm the reconciliation job (STK query) completes the order.
  • Unit-test the timestamp and password helpers with a fixed date.

Replay a callback locally (duplicate-delivery test) · cURL

# Use the CheckoutRequestID your server saved for order-1001
curl -s -X POST "http://localhost:3000/mpesa/callback/$MPESA_CALLBACK_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"Body":{"stkCallback":{"MerchantRequestID":"test","CheckoutRequestID":"ws_CO_REPLACE_ME",
       "ResultCode":0,"ResultDesc":"The service request is processed successfully.",
       "CallbackMetadata":{"Item":[{"Name":"Amount","Value":1},
       {"Name":"MpesaReceiptNumber","Value":"TEST123456"},{"Name":"TransactionDate","Value":20261125120000},
       {"Name":"PhoneNumber","Value":254700000000}]}}}}'
# Send it twice: the second call must not change anything.
curl -s http://localhost:3000/api/orders/order-1001

Common mistakes

  • Requesting a new token for every call, or caching it forever — both cause Invalid Access Token sooner or later. Cache and refresh before expires_in.
  • Timestamp mismatch: generating one timestamp for Password and another for Timestamp, using UTC instead of Kenyan time inconsistently, or the wrong format (it must be YYYYMMDDHHmmss, 14 digits).
  • Wrong shortcode/passkey pair: sandbox passkey with a production shortcode, or a Till number in BusinessShortCode instead of the store/head-office number.
  • Phone number format: 07... or +254... instead of 2547.../2541....
  • Callback URL not reachable: localhost, plain HTTP, an expired tunnel, a URL behind authentication or a firewall. It must be public HTTPS.
  • Marking the order paid when STK Push returns ResponseCode 0 — that only means the prompt was sent.
  • AccountReference longer than 12 or TransactionDesc longer than 13 characters.
  • Sending decimals or cents as Amount — Daraja expects whole shillings.

Troubleshooting

  • Invalid Access Token (404.001.03): token expired or from the other environment; check MPESA_ENV matches your keys and that you refresh the cache.
  • Invalid Authentication Header (404.001.04): the Authorization header is missing or not Bearer <token>.
  • Bad Request - Invalid Timestamp / Invalid PhoneNumber / Invalid Amount: check the 14-digit timestamp, the 254 phone format and a whole-number amount.
  • Prompt never appears: the phone is off or out of coverage, the SIM toolkit is busy with another prompt, or the number is not a Safaricom M-Pesa line. Expect 1037 in the callback.
  • No callback received: confirm the URL with an external HTTP tester, check your server logs for 4xx/5xx (body parser limits, CSRF middleware in Laravel — exclude the route), and rely on the STK query job.
  • Callback received but order not found: you did not save CheckoutRequestID before the callback arrived (save it before responding to the client), or you saved MerchantRequestID instead.
  • Works in sandbox, fails in production: production passkey, shortcode and base URL all must change together; Till payments need CustomerBuyGoodsOnline with the Till number as PartyB.

Tip: Laravel's CSRF middleware rejects external POSTs to web routes. Put the callback in routes/api.php or exclude it explicitly.

Further reading

  • Daraja API catalogue — all APIs, including C2B, B2C, Account Balance and Bill Manager.
  • Transaction Status and Reversal for back-office flows.
  • Related Metatron guides: Pesapal API 3.0 and PayHero STK if you prefer an aggregator that also accepts cards or handles M-Pesa for you.

Official documentation

Checked 2026-11-25. The portal is a client-rendered app: if a link opens the catalogue instead of the page, search the API name inside the portal.

Official documentation

Sources

More payment guides