Skip to content

Nairobi · East Africa

Fintech & Digital Payments

How to Integrate M-Pesa Payments Into a Web Application

A practical Daraja API guide: OAuth, STK Push, callbacks, status queries, C2B URLs and go-live, with server-side TypeScript code and idempotent reconciliation.

TechBytes EA Engineering Team· · 14 min read

Person using a phone and laptop to make a payment

Most M-Pesa integrations that fail in production do not fail at the API call; they fail at the edges: a callback that never arrives, a duplicate notification that credits a customer twice, a timestamp in the wrong timezone, or a consumer secret shipped inside a mobile app. This guide walks through Safaricom's Daraja API end to end, from the OAuth token to go-live, with server-side TypeScript you can adapt directly. By the end you will be able to trigger an STK Push, receive and verify the result, recover from missing callbacks and reconcile payments against your orders.

Key takeaways

  • All Daraja calls happen server-side. Consumer keys, secrets and the passkey must never reach a browser or mobile app.
  • STK Push (M-Pesa Express) is a two-phase flow: a synchronous acknowledgement with a CheckoutRequestID, then an asynchronous callback with the real result.
  • Store the CheckoutRequestID before you return to the user, and make callback processing idempotent.
  • Callbacks can be late or missing. Use the STK Push Query endpoint on a schedule to settle pending transactions.
  • Your callback URL must be public HTTPS. Use a tunnel during development.
  • Reconcile daily against your M-Pesa statement; the API is not your only source of truth.

How the STK Push flow works

 Browser                Your server                    Safaricom Daraja           Customer phone
    |  POST /pay (orderId)  |                                 |                          |
    |---------------------->|  1. GET oauth token (cached)     |                          |
    |                       |-------------------------------->|                          |
    |                       |  2. POST stkpush/processrequest  |                          |
    |                       |-------------------------------->|  3. PIN prompt            |
    |                       |  <- CheckoutRequestID (ack)      |------------------------->|
    |  <- "check your phone"|  4. save CheckoutRequestID       |                          |
    |                       |                                 |  5. customer enters PIN  |
    |                       |  6. POST CallBackURL (result)    |<-------------------------|
    |                       |<--------------------------------|                          |
    |  7. poll /pay/status  |  8. mark order PAID / FAILED     |                          |
    |<--------------------->|  (fallback: stkpushquery)        |                          |

The acknowledgement in step 3 only means Safaricom accepted the request. The payment outcome arrives in step 6, or must be fetched with a status query if the callback never arrives.

Phone screen showing a QR code paymentQR and mobile money payments are everyday checkout options in East Africa.

Prerequisites

  1. An account on the Safaricom Developer Portal and a sandbox app with M-Pesa Express (and C2B if needed) enabled. The app gives you a Consumer Key and Consumer Secret.
  2. The sandbox test shortcode and passkey for M-Pesa Express, shown in the portal's test credentials and API simulator. The commonly used sandbox Paybill is 174379; take the passkey from the portal rather than from blog posts.
  3. Node.js 18 or later (for the built-in fetch), TypeScript, Express and PostgreSQL. Any stack works; the logic is identical.
  4. A public HTTPS URL for callbacks. In development, a tunnel such as ngrok http 3000 or cloudflared tunnel --url http://localhost:3000 exposes your local server.

Base URLs:

EnvironmentBase URL
Sandboxhttps://sandbox.safaricom.co.ke
Productionhttps://api.safaricom.co.ke

Step 1: Configuration and secrets

Keep credentials in environment variables or a secrets manager, never in the repository.

# .env (do not commit)
MPESA_BASE_URL=https://sandbox.safaricom.co.ke
MPESA_CONSUMER_KEY=your_consumer_key
MPESA_CONSUMER_SECRET=your_consumer_secret
MPESA_SHORTCODE=174379
MPESA_PASSKEY=your_passkey_from_portal
MPESA_TRANSACTION_TYPE=CustomerPayBillOnline
MPESA_PARTY_B=174379
MPESA_CALLBACK_TOKEN=LONG_RANDOM_TOKEN
MPESA_CALLBACK_URL=https://your-tunnel.example/api/payments/callback/LONG_RANDOM_TOKEN
DATABASE_URL=postgres://user:pass@localhost:5432/shop

For a Paybill, BusinessShortCode and PartyB are both the Paybill number and TransactionType is CustomerPayBillOnline. For a Till (Buy Goods), BusinessShortCode is the head office (store) number used to generate the password, PartyB is the till number, and TransactionType is CustomerBuyGoodsOnline. Confirm the exact numbers with Safaricom when you onboard, because mismatches here are the most common production error.

Step 2: Database schema

CREATE TABLE mpesa_payments (
  id                   BIGSERIAL PRIMARY KEY,
  order_id             TEXT        NOT NULL,
  idempotency_key      TEXT        NOT NULL UNIQUE,
  merchant_request_id  TEXT,
  checkout_request_id  TEXT        UNIQUE,
  phone                TEXT        NOT NULL,
  amount               INTEGER     NOT NULL CHECK (amount > 0),
  status               TEXT        NOT NULL DEFAULT 'PENDING',
  result_code          INTEGER,
  result_desc          TEXT,
  mpesa_receipt        TEXT        UNIQUE,
  raw_callback         JSONB,
  created_at           TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at           TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX mpesa_payments_pending_idx
  ON mpesa_payments (status, created_at) WHERE status = 'PENDING';

The UNIQUE constraints do real work: idempotency_key stops a double-click from sending two prompts, checkout_request_id ties the callback to exactly one row, and mpesa_receipt makes it impossible to record the same M-Pesa transaction twice.

Step 3: The Daraja client

The OAuth endpoint uses HTTP Basic authentication with base64(ConsumerKey:ConsumerSecret):

GET https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials

The response contains access_token and expires_in (about an hour). Cache the token and refresh it shortly before expiry rather than requesting a new one per call.

The STK Push password is base64(BusinessShortCode + Passkey + Timestamp), and the timestamp is YYYYMMDDHHmmss. Generate it in East Africa Time (UTC+3), matching the time Safaricom expects.

// src/daraja.ts
const cfg = {
  baseUrl: process.env.MPESA_BASE_URL!,
  key: process.env.MPESA_CONSUMER_KEY!,
  secret: process.env.MPESA_CONSUMER_SECRET!,
  shortcode: process.env.MPESA_SHORTCODE!,
  passkey: process.env.MPESA_PASSKEY!,
  txType: process.env.MPESA_TRANSACTION_TYPE as
    | "CustomerPayBillOnline"
    | "CustomerBuyGoodsOnline",
  partyB: process.env.MPESA_PARTY_B!,
  callbackUrl: process.env.MPESA_CALLBACK_URL!,
};

let cachedToken: { value: string; expiresAt: number } | null = null;

export async function getAccessToken(): Promise<string> {
  if (cachedToken && Date.now() < cachedToken.expiresAt) return cachedToken.value;

  const basic = Buffer.from(`${cfg.key}:${cfg.secret}`).toString("base64");
  const res = await fetch(
    `${cfg.baseUrl}/oauth/v1/generate?grant_type=client_credentials`,
    { headers: { Authorization: `Basic ${basic}` }, signal: AbortSignal.timeout(15_000) }
  );
  if (!res.ok) throw new Error(`OAuth failed: ${res.status} ${await res.text()}`);

  const body = (await res.json()) as { access_token: string; expires_in: string };
  // Refresh 60 seconds early to avoid using a token at the edge of expiry.
  cachedToken = {
    value: body.access_token,
    expiresAt: Date.now() + (Number(body.expires_in) - 60) * 1000,
  };
  return cachedToken.value;
}

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

export function stkPassword(timestamp: string): string {
  return Buffer.from(`${cfg.shortcode}${cfg.passkey}${timestamp}`).toString("base64");
}

/** Accepts 07XXXXXXXX, 01XXXXXXXX, +2547..., 2547... and returns 2547XXXXXXXX / 2541XXXXXXXX. */
export function normaliseMsisdn(input: string): string {
  const digits = input.replace(/[\s-]/g, "");
  const m = digits.match(/^(?:\+?254|0)?([17]\d{8})$/);
  if (!m) throw new Error("Invalid Kenyan mobile number");
  return `254${m[1]}`;
}

async function darajaPost<T>(path: string, payload: object): Promise<T> {
  const token = await getAccessToken();
  const res = await fetch(`${cfg.baseUrl}${path}`, {
    method: "POST",
    headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
    body: JSON.stringify(payload),
    signal: AbortSignal.timeout(30_000),
  });
  const body = await res.json();
  if (!res.ok) throw new Error(`Daraja ${path} ${res.status}: ${JSON.stringify(body)}`);
  return body as T;
}

export interface StkPushAck {
  MerchantRequestID: string;
  CheckoutRequestID: string;
  ResponseCode: string; // "0" means accepted for processing
  ResponseDescription: string;
  CustomerMessage: string;
}

export function stkPush(params: {
  phone: string;
  amount: number;
  accountReference: string;
  description: string;
}): Promise<StkPushAck> {
  const timestamp = darajaTimestamp();
  return darajaPost<StkPushAck>("/mpesa/stkpush/v1/processrequest", {
    BusinessShortCode: cfg.shortcode,
    Password: stkPassword(timestamp),
    Timestamp: timestamp,
    TransactionType: cfg.txType,
    Amount: Math.round(params.amount), // whole shillings only
    PartyA: params.phone,
    PartyB: cfg.partyB,
    PhoneNumber: params.phone,
    CallBackURL: cfg.callbackUrl,
    AccountReference: params.accountReference.slice(0, 12),
    TransactionDesc: params.description.slice(0, 13),
  });
}

export interface StkQueryResult {
  ResponseCode: string;
  ResponseDescription: string;
  MerchantRequestID: string;
  CheckoutRequestID: string;
  ResultCode: string;
  ResultDesc: string;
}

export function stkQuery(checkoutRequestId: string): Promise<StkQueryResult> {
  const timestamp = darajaTimestamp();
  return darajaPost<StkQueryResult>("/mpesa/stkpushquery/v1/query", {
    BusinessShortCode: cfg.shortcode,
    Password: stkPassword(timestamp),
    Timestamp: timestamp,
    CheckoutRequestID: checkoutRequestId,
  });
}

AccountReference and TransactionDesc have short maximum lengths in the Daraja documentation (around 12 and 13 characters at the time of writing); truncating defensively avoids rejected requests. Amounts are whole Kenyan shillings.

Step 4: Initiating a payment idempotently

The browser sends only an order ID and phone number. The server looks up the amount from the order, never trusting a client-supplied price.

// src/server.ts
import express from "express";
import { Pool } from "pg";
import { normaliseMsisdn, stkPush, stkQuery } from "./daraja";

const db = new Pool({ connectionString: process.env.DATABASE_URL });
const app = express();
app.use(express.json());

app.post("/api/payments/mpesa", async (req, res) => {
  const { orderId, phone } = req.body as { orderId: string; phone: string };
  const idemKey = req.header("Idempotency-Key");
  if (!orderId || !phone || !idemKey) return res.status(400).json({ error: "Missing fields" });

  let msisdn: string;
  try { msisdn = normaliseMsisdn(phone); }
  catch { return res.status(400).json({ error: "Enter a valid Safaricom number" }); }

  // Replace with your real order lookup; the amount must come from the server.
  const order = await db.query("SELECT total_kes FROM orders WHERE id = $1", [orderId]);
  if (order.rowCount === 0) return res.status(404).json({ error: "Order not found" });
  const amount = Number(order.rows[0].total_kes);

  // Claim the idempotency key first. A retry with the same key returns the existing row.
  const inserted = await db.query(
    `INSERT INTO mpesa_payments (order_id, idempotency_key, phone, amount)
     VALUES ($1, $2, $3, $4)
     ON CONFLICT (idempotency_key) DO NOTHING
     RETURNING id`,
    [orderId, idemKey, msisdn, amount]
  );
  if (inserted.rowCount === 0) {
    const existing = await db.query(
      "SELECT checkout_request_id, status FROM mpesa_payments WHERE idempotency_key = $1",
      [idemKey]
    );
    return res.status(200).json(existing.rows[0]);
  }
  const paymentId = inserted.rows[0].id;

  try {
    const ack = await stkPush({
      phone: msisdn,
      amount,
      accountReference: String(orderId),
      description: "Order payment",
    });
    if (ack.ResponseCode !== "0") throw new Error(ack.ResponseDescription);

    await db.query(
      `UPDATE mpesa_payments
         SET merchant_request_id = $1, checkout_request_id = $2, updated_at = now()
       WHERE id = $3`,
      [ack.MerchantRequestID, ack.CheckoutRequestID, paymentId]
    );
    return res.status(202).json({
      checkoutRequestId: ack.CheckoutRequestID,
      message: "Check your phone and enter your M-Pesa PIN",
    });
  } catch (err) {
    await db.query(
      `UPDATE mpesa_payments SET status = 'FAILED', result_desc = $1, updated_at = now()
       WHERE id = $2`,
      [(err as Error).message.slice(0, 500), paymentId]
    );
    return res.status(502).json({ error: "Could not start M-Pesa payment, try again" });
  }
});

The front end generates the Idempotency-Key (for example crypto.randomUUID()) once per payment attempt and reuses it on retries. It then polls GET /api/payments/mpesa/:checkoutRequestId every few seconds for up to two minutes, showing "waiting for confirmation" rather than an error.

Step 5: Handling the callback

Safaricom posts the result to your CallBackURL. A successful callback body looks like this (values illustrative):

{
  "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 },
          { "Name": "MpesaReceiptNumber", "Value": "NLJ7RT61SV" },
          { "Name": "TransactionDate", "Value": 20191219102115 },
          { "Name": "PhoneNumber", "Value": 254708374149 }
        ]
      }
    }
  }
}

A non-zero ResultCode means the payment did not complete, and CallbackMetadata is absent. Commonly seen codes include 1032 (cancelled by the user) and 1037 (the customer's phone could not be reached in time); always store ResultDesc and treat any non-zero code as not paid.

Daraja STK callbacks do not carry a signature you can verify. Protect the endpoint with a long random token in the path, consider allowlisting Safaricom's published callback IP ranges at your firewall, and, for high-value orders, confirm with stkQuery before fulfilment.

Add the callback route to src/server.ts:

type CallbackItem = { Name: string; Value?: string | number };

app.post("/api/payments/callback/:token", async (req, res) => {
  if (req.params.token !== process.env.MPESA_CALLBACK_TOKEN) return res.status(404).end();

  // Acknowledge quickly; Safaricom does not need your business logic to finish first.
  res.json({ ResultCode: 0, ResultDesc: "Accepted" });

  const cb = req.body?.Body?.stkCallback;
  if (!cb?.CheckoutRequestID) return;

  const items: CallbackItem[] = cb.CallbackMetadata?.Item ?? [];
  const get = (name: string) => items.find((i) => i.Name === name)?.Value;
  const paid = cb.ResultCode === 0;

  // Conditional update: only an unsettled row changes, so duplicate callbacks are harmless.
  // A late callback can still attach the receipt to a row the query job marked PAID_UNCONFIRMED.
  const result = await db.query(
    `UPDATE mpesa_payments
        SET status = $1, result_code = $2, result_desc = $3,
            mpesa_receipt = $4, raw_callback = $5, updated_at = now()
      WHERE checkout_request_id = $6 AND status IN ('PENDING', 'PAID_UNCONFIRMED')
      RETURNING order_id, amount`,
    [
      paid ? "PAID" : cb.ResultCode === 1032 ? "CANCELLED" : "FAILED",
      cb.ResultCode,
      cb.ResultDesc,
      paid ? String(get("MpesaReceiptNumber")) : null,
      JSON.stringify(req.body),
      cb.CheckoutRequestID,
    ]
  ).catch((e) => { console.error("callback update failed", e); return null; });

  if (paid && result?.rowCount === 1) {
    const row = result.rows[0];
    if (Number(get("Amount")) !== Number(row.amount)) {
      console.error("Amount mismatch", cb.CheckoutRequestID); // route to manual review
      return;
    }
    await db.query("UPDATE orders SET status = 'PAID' WHERE id = $1", [row.order_id]);
  }
});

In production, persist the raw body to a separate inbox table before parsing, so that a bug in your handler never loses evidence of a payment.

Step 6: Recovering missing callbacks with STK Push Query

The query endpoint is POST /mpesa/stkpushquery/v1/query with BusinessShortCode, Password, Timestamp and CheckoutRequestID. Run a job every minute or two for rows still PENDING after roughly 90 seconds:

export async function settlePending(): Promise<void> {
  const { rows } = await db.query(
    `SELECT checkout_request_id FROM mpesa_payments
      WHERE status = 'PENDING' AND checkout_request_id IS NOT NULL
        AND created_at < now() - interval '90 seconds'
        AND created_at > now() - interval '1 day'
      LIMIT 50`
  );
  for (const { checkout_request_id } of rows) {
    try {
      const q = await stkQuery(checkout_request_id);
      const code = Number(q.ResultCode);
      if (Number.isNaN(code)) continue; // still processing
      await db.query(
        `UPDATE mpesa_payments SET status = $1, result_code = $2, result_desc = $3,
                updated_at = now()
          WHERE checkout_request_id = $4 AND status = 'PENDING'`,
        [code === 0 ? "PAID_UNCONFIRMED" : "FAILED", code, q.ResultDesc, checkout_request_id]
      );
    } catch (e) {
      // While the transaction is still in progress the query can return an error; retry later.
      console.warn("stk query deferred", checkout_request_id, (e as Error).message);
    }
  }
}

setInterval(() => settlePending().catch(console.error), 60_000);
app.listen(3000, () => console.log("Payments API listening on :3000"));

The query response does not include the receipt number, so mark these PAID_UNCONFIRMED and let the daily statement reconciliation attach the receipt. Whether you fulfil on PAID_UNCONFIRMED is a business decision based on order value.

Source code displayed on a monitorReadable, typed code is what keeps a front end maintainable as the team grows.

Step 7: C2B for customers who pay via the menu

Some customers will pay your Paybill or Till directly from the M-Pesa menu instead of via STK Push. To receive those, register confirmation and validation URLs:

POST /mpesa/c2b/v1/registerurl

{
  "ShortCode": "600000",
  "ResponseType": "Completed",
  "ConfirmationURL": "https://pay.example.co.ke/api/c2b/confirmation/LONG_RANDOM_TOKEN",
  "ValidationURL": "https://pay.example.co.ke/api/c2b/validation/LONG_RANDOM_TOKEN"
}

Notes from experience and the documentation:

  • ResponseType decides what happens if your validation URL is unreachable: Completed accepts the payment, Cancelled rejects it.
  • External validation is not active by default on production shortcodes; request it from Safaricom if you need to reject payments with invalid account numbers.
  • Avoid words such as "mpesa" or "safaricom" in your callback URLs; the documentation warns these can be rejected.
  • The confirmation payload carries TransID (the receipt), TransAmount, BillRefNumber (the account the customer typed) and BusinessShortCode. Respond with {"ResultCode": 0, "ResultDesc": "Accepted"} and match BillRefNumber to open invoices, with a manual queue for mismatches.

Step 8: Reconciliation

The API is excellent but not infallible. Download the M-Pesa organisation statement for your shortcode daily (via the M-Pesa business portal, or via the transaction status and account balance APIs if you have them enabled) and:

  1. Match each statement line to mpesa_payments.mpesa_receipt.
  2. Attach receipts to PAID_UNCONFIRMED rows by matching phone, amount and time window, then mark them PAID.
  3. Flag statement lines with no matching row (C2B payments with bad references, or missed callbacks).
  4. Flag PAID rows with no statement line, which should be rare and investigated immediately.

Step 9: Testing with a tunnel

  1. Run the server locally on port 3000.
  2. Start a tunnel: ngrok http 3000 or cloudflared tunnel --url http://localhost:3000.
  3. Set MPESA_CALLBACK_URL to the tunnel's HTTPS URL plus your callback path and token.
  4. Trigger an STK Push to the sandbox test number from the portal (or your own Safaricom line in sandbox, if the portal allows it at the time you test).
  5. Inspect the callback in the tunnel's request inspector and your database.
  6. Test the unhappy paths: cancel the prompt, let it time out, send the same request twice, kill your server before the callback arrives and confirm the query job recovers the result.

Step 10: Going live

Go-live is handled through the "Go Live" process on the Safaricom developer portal. In outline, at the time of writing:

  1. Obtain a production Paybill or Till via Safaricom's Lipa na M-Pesa onboarding, with a business administrator account on the M-Pesa organisation portal.
  2. Start Go Live on developer.safaricom.co.ke, choose your shortcode and verification method, and confirm with the one-time code sent to the administrator.
  3. Select the APIs (for example M-Pesa Express and C2B) for the production app.
  4. Receive production credentials and the M-Pesa Express passkey, typically by email to the registered contact.
  5. Switch MPESA_BASE_URL to https://api.safaricom.co.ke, update shortcode, passkey and callback URLs, and register C2B URLs again on production.
  6. Run a small real transaction and refund it before announcing launch.

Steps and requirements change; follow the portal's current instructions.

Common mistakes

  • Consumer secret or passkey in front-end code. Rotate credentials immediately if this has happened.
  • Timestamp in UTC. Generate it in EAT, and use the same timestamp for both Password and Timestamp.
  • Wrong PartyB for Till payments. For Buy Goods, PartyB is the till number, not the store number.
  • Treating the acknowledgement as payment. ResponseCode "0" means the prompt was sent, not that money moved.
  • No idempotency. Duplicate callbacks and double-clicks produce double credits and double prompts.
  • Doing slow work before responding to the callback. Acknowledge quickly and process asynchronously.
  • Callback URL behind a self-signed certificate or private network. It must be publicly reachable HTTPS with a valid certificate.
  • Logging full phone numbers everywhere. Under the Kenya Data Protection Act 2019, minimise and mask personal data in logs.

FAQ

Can I call the Daraja API directly from a React or mobile app?

No. Calls need your consumer secret and passkey, which would be exposed. The app should call your backend, and your backend calls Daraja.

Why did the customer pay but my callback never arrived?

Usually your endpoint was unreachable, returned an error, or the callback was delayed on Safaricom's side. Check your server logs and certificate, and rely on the STK Push Query job and daily statement reconciliation to recover.

Does STK Push work for Till numbers?

Yes. Use CustomerBuyGoodsOnline, the store number as BusinessShortCode for the password, and the till number as PartyB.

Do I need both STK Push and C2B?

If customers might pay from the M-Pesa menu as well as your checkout, yes. STK Push covers checkout; C2B URLs catch everything else paid to the shortcode.

How long does go-live take?

It depends on having a production shortcode and correctly configured administrator account. With those in place, the portal process itself is usually quick; obtaining the shortcode takes longer.

How TechBytes can help

TechBytes EA builds production M-Pesa integrations covering STK Push, C2B, B2C and reconciliation, with secure callback infrastructure and monitoring. We can also review an existing integration for idempotency and security gaps before your next peak season. Talk to our software development team, or see the business context in how mobile payment technologies are transforming African businesses and the card side in understanding payment gateway integration.

WhatsApp