← Back to dashboard
daraja-apipaymentsfreshReader view (for NotebookLM)

Daraja API (Safaricom M-Pesa) Integration Guide

How M-Pesa STK Push works

The real model

Async STK Push → idempotent callback. Get the non-negotiables right and the rest is plumbing.

The non-negotiables: phone format is `254XXXXXXXXX` (no `+`, no leading `0`); amount is whole KES between 1 and 250,000 (`100`, not `100.00`); the access token lasts `expires_in` = 3599s and each new token request invalidates the previous one, so cache one shared token and refresh once on "Invalid Access Token". The callback URL must be public HTTPS and must not contain "mpesa" or "safaricom" (Safaricom's URL rules) — allowlist Safaricom's 12 gateway IPs, because callbacks aren't signed. Daraja does NOT retry a callback your server missed (the gateway logs a 503 and discards it), so store `CheckoutRequestID` the moment STK Push returns, dedupe on it, and run a reconciliation job that calls STK Query for anything still pending. Sandbox shortcode is 174379, test phone 254708374149. Offload anything slow (SMS receipts, downstream API calls) to a queue (Upstash QStash, etc.) so the callback handler returns in <1s.

The five-step lifecycle

Each call has its own failure mode. Tap a card for the gotchas that show up in production.

Walk the happy and unhappy paths

Press ▶ Start payment and the simulator walks through the same lifecycle a real STK Push takes. When the customer is deciding, branch the flow — confirm, cancel, or simply walk away — and the terminal note shows what your server should do for that exact ResultCode.

STK Push simulatorphase: idle
  1. Fetch token
    POST /oauth/v1/generate
  2. STK Push
    POST /mpesa/stkpush/v1/processrequest
  3. Customer decides
    Phone prompt → PIN
  4. Callback
    POST → your /api/payments/stk/callback
  5. Reconcile
    Dedupe + DB write + ACK 200

The biggest production trap isn't “cancelled” — it's the third button. When no callback arrives, you cannot assume failure: the customer may have paid. Always reconcile with stkpushquery before refunding.

Text
██████╗  █████╗ ██████╗  █████╗      ██╗ █████╗
██╔══██╗██╔══██╗██╔══██╗██╔══██╗     ██║██╔══██╗
██║  ██║███████║██████╔╝███████║     ██║███████║
██║  ██║██╔══██║██╔══██╗██╔══██║██   ██║██╔══██║
██████╔╝██║  ██║██║  ██║██║  ██║╚█████╔╝██║  ██║
╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═╝╚═╝  ╚═╝ ╚════╝ ╚═╝  ╚═╝

Daraja API (Safaricom M-Pesa) Integration Guide

Focus: Adding M-Pesa mobile money to Kenya-targeted codeAmani projects from Claude Code: STK Push, C2B, B2C, status queries, reversals, balance checks, and safe callback handling with the Safaricom Daraja API.

Overview

Daraja is Safaricom's developer platform for M-Pesa, Kenya's leading mobile money network. Its REST APIs cover:

  • M-Pesa Express (STK Push, also called Lipa na M-Pesa Online): sends a payment prompt to the customer's phone.
  • C2B: notifies you when customers pay your Paybill or Till themselves.
  • B2C: pays money out to customers.
  • Transaction Status, Reversals and Account Balance: operations on your own shortcode.
  • Business Pay Bill / Buy Goods, Dynamic QR, Pull Transactions and M-Pesa Ratiba (standing orders), among others.

Daraja runs only in Kenya. Its FAQ says M-Pesa in each Vodacom market is a separate provider with its own APIs.

Portal (Daraja 3.0, launched Nov 2025). The developer portal is self-service and lives at developer.safaricom.co.ke. API docs are at /apis/<ApiName> (for example /apis/MpesaExpressSimulate and /apis/CustomerToBusiness). Apps and keys are under /dashboard/myapps, go-live is at /dashboard/golive, and C2B URL deletion is at /dashboard/urlmanagement. Some links inside Safaricom's own docs still point at daraja.safaricom.co.ke, which does not resolve. Use developer.safaricom.co.ke instead. The API hosts are unchanged: sandbox.safaricom.co.ke and api.safaricom.co.ke.

Here's how the pieces fit together:

Official Documentation

There is no official Safaricom npm SDK, which is why packages: []. Call the REST API with fetch (see examples/). Community wrappers exist, but treat them as unvetted dependencies.


Authentication

Daraja uses the OAuth 2.0 client-credentials flow. You send GET /oauth/v1/generate?grant_type=client_credentials with Authorization: Basic base64(consumerKey:consumerSecret). The response is { "access_token": "...", "expires_in": 3599 }, so a token lasts about 1 hour.

Three things the docs say that change how you cache the token:

  1. Read expires_in instead of hard-coding 3600.
  2. Daraja's FAQ says "each request invalidates the previous token". Don't fetch a token per request. If you run many serverless instances, cache the token in a shared store (Vercel KV/Upstash, or a database row) so instances don't keep invalidating each other's tokens.
  3. An expired token is not always an HTTP 401. STK Push returns HTTP 404 with errorCode: "404.001.03", C2B returns 400.003.01, and Account Balance returns 401.002.01. Retry once with a fresh token whenever errorMessage says "Invalid Access Token".
TypeScript
// lib/mpesa-auth.ts (full version with retry: examples/mpesa-auth.ts)
let cache: { value: string; expiresAt: number } | null = null;

export async function getMpesaToken(forceRefresh = false): Promise<string> {
  if (!forceRefresh && cache && Date.now() < cache.expiresAt - 60_000) return cache.value;

  const credentials = Buffer.from(
    `${process.env.MPESA_CONSUMER_KEY}:${process.env.MPESA_CONSUMER_SECRET}`,
  ).toString("base64");
  const base =
    process.env.MPESA_ENV === "production" ? "https://api.safaricom.co.ke" : "https://sandbox.safaricom.co.ke";

  const res = await fetch(`${base}/oauth/v1/generate?grant_type=client_credentials`, {
    headers: { Authorization: `Basic ${credentials}` },
  });
  if (!res.ok) throw new Error(`Daraja auth failed: ${res.status} ${await res.text()}`);

  const data = (await res.json()) as { access_token?: string; expires_in?: string | number };
  if (!data.access_token) throw new Error("No access_token in Daraja response");
  cache = { value: data.access_token, expiresAt: Date.now() + Number(data.expires_in ?? 3599) * 1000 };
  return cache.value;
}

cURL token request

Bash
# Sandbox token (reads keys from your shell env; never paste real keys into scripts)
curl -s "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials" \
  -u "$MPESA_CONSUMER_KEY:$MPESA_CONSUMER_SECRET" | jq .

Core API Integration

M-Pesa Express (STK Push)

STK Push sends a PIN prompt to the customer's phone. The flow is asynchronous: the HTTP response only means the request was accepted, and the real outcome arrives later at your CallBackURL.

Here's the full lifecycle:

Request rules (from the official parameter table):

FieldRule
BusinessShortCodePaybill, or the HO/store number used at Go Live for tills
Passwordbase64(BusinessShortCode + Passkey + Timestamp)
TimestampYYYYMMDDHHmmss. Use the same value as in the Password; we generate it in EAT (UTC+3)
TransactionTypeCustomerPayBillOnline (Paybill) or CustomerBuyGoodsOnline (Till)
AmountWhole KES, min 1, max 250,000 per transaction
PartyA / PhoneNumber2547XXXXXXXX / 2541XXXXXXXX (12 digits, no +)
PartyBPaybill number, or the till number for Buy Goods
CallBackURLPublic HTTPS URL. Keep mpesa/safaricom out of it (see URL rules)
AccountReferenceMax 12 chars. The customer sees it on the prompt
TransactionDescMax 13 chars (the only optional field)
TypeScript
// lib/payments/stk.ts (full version: examples/stk-push.ts)
import { darajaPost } from "./mpesa-auth";

const eatTimestamp = () =>
  new Date(Date.now() + 3 * 3600_000).toISOString().replace(/[^0-9]/g, "").slice(0, 14);

export async function stkPush(phone: string, amount: number, accountReference: string) {
  if (!/^254\d{9}$/.test(phone)) throw new Error("Phone must be 254XXXXXXXXX");
  if (!Number.isInteger(amount) || amount < 1 || amount > 250_000) throw new Error("Whole KES, 1–250,000");

  const shortcode = process.env.MPESA_SHORTCODE!;
  const timestamp = eatTimestamp();
  return darajaPost<{ CheckoutRequestID: string; MerchantRequestID: string; ResponseCode: string }>(
    "/mpesa/stkpush/v1/processrequest",
    {
      BusinessShortCode: shortcode,
      Password: Buffer.from(`${shortcode}${process.env.MPESA_PASSKEY}${timestamp}`).toString("base64"),
      Timestamp: timestamp,
      TransactionType: "CustomerPayBillOnline",
      Amount: amount,
      PartyA: phone,
      PartyB: shortcode,
      PhoneNumber: phone,
      CallBackURL: `${process.env.APP_URL}/api/payments/stk/callback`,
      AccountReference: accountReference.slice(0, 12),
      TransactionDesc: "Payment",
    },
  );
  // → { MerchantRequestID, CheckoutRequestID: "ws_CO_…", ResponseCode: "0", ResponseDescription, CustomerMessage }
  // Persist CheckoutRequestID + the phone you sent BEFORE returning to the client.
}

STK Push status query

Call POST /mpesa/stkpushquery/v1/query with BusinessShortCode, Password, Timestamp and CheckoutRequestID. The response carries both ResponseCode (whether the query was accepted) and ResultCode/ResultDesc (the payment's outcome: 0 paid, 1032 cancelled or timed out, and so on). See stkQuery() in examples/stk-push.ts.

STK callback handler

The callback body is { Body: { stkCallback: { MerchantRequestID, CheckoutRequestID, ResultCode, ResultDesc, CallbackMetadata? } } }. CallbackMetadata.Item appears only on success. It holds Amount (a decimal, e.g. 1.0), MpesaReceiptNumber, TransactionDate (as a number, YYYYMMDDHHmmss), PhoneNumber, and sometimes Balance.

TypeScript
// app/api/payments/stk/callback/route.ts (full version: examples/stk-callback.ts)
import { makeStkCallbackHandler } from "@/lib/payments/stk-callback";
import { paymentStore } from "@/lib/payments/store"; // your Supabase/Neon implementation

export const POST = makeStkCallbackHandler(paymentStore, {
  enforceIpAllowlist: process.env.MPESA_ENV === "production",
});
// Inside: IP allowlist → parse → ignore unknown CheckoutRequestIDs → idempotent
// finalize → always return 200 { ResultCode: 0, ResultDesc: "Accepted" }.
// Anything slow (SMS receipt, fulfilment, AI) goes on a queue, not in this handler.

Callback result codes (official M-Pesa Express errors table):

ResultCodeMeaningWhat to do
0PaidMark paid, store MpesaReceiptNumber
1Insufficient balance (or customer declined Fuliza)Ask them to top up
1032Cancelled by the user, or the prompt timed out (1–3 min depending on phone)Offer a retry
1037"DS timeout user cannot be reached": the prompt never got to the phone (offline, old SIM) or the reply came back lateTell the customer before re-pushing
2001Wrong M-PESA PIN (initiator information invalid)Let them retry
1019Transaction expiredRe-initiate
1001Subscriber locked: another USSD/STK session is in progressWait 2–3 min, one push per user at a time
1025 / 9999Error sending the push (system error, or the prompt text was over 182 chars)Retry; keep AccountReference short

C2B: register URLs, validation & confirmation

C2B covers payments the customer starts from the M-Pesa menu, app, USSD or a QR code, to your Paybill or Till. You register two URLs once per shortcode:

  • The Validation URL is called before the debit, and only if Safaricom has enabled External Validation for your shortcode. Answer within about 8 s, or M-PESA applies your ResponseType.
  • The Confirmation URL is called after the money moves. Record it; you can't reject it.
TypeScript
// lib/payments/c2b.ts (full version incl. handlers: examples/c2b.ts)
export async function registerC2BUrls(appUrl: string, shortCode: string) {
  return darajaPost("/mpesa/c2b/v2/registerurl", {
    ShortCode: shortCode,
    ResponseType: "Completed", // exactly "Completed" | "Cancelled", sentence case
    ConfirmationURL: `${appUrl}/api/payments/c2b/confirm`,
    ValidationURL: `${appUrl}/api/payments/c2b/validate`,
  }); // → { OriginatorCoversationID, ResponseCode: "0", ResponseDescription: "Success" }
}

What changed and what to watch:

  • Use C2B v2 everywhere. The C2B doc's Environments table lists /mpesa/c2b/v2/registerurl and /mpesa/c2b/v2/simulate for both sandbox and production. The old "sandbox v1 / production v2" split is gone. The difference is the payer number: v1 sends a SHA-256-hashed MSISDN, while v2 sends a masked one ("2547 ***** 126"). Simulate works only in the sandbox.
  • Masking is official. The v2 MSISDN field is documented as "masked number of the customer". The CBK-approved masking went live on 24 Mar 2026. Never use MSISDN as an identity key. Key on BillRefNumber (the account the customer typed, up to 20 chars) and dedupe on TransID. FirstName/MiddleName/LastName can be empty.
  • Validation reply: {"ResultCode":"0","ResultDesc":"Accepted"} accepts. To reject, send {"ResultCode":"C2B00012","ResultDesc":"Rejected"}, choosing from C2B00011–C2B00016 (invalid MSISDN, account number, amount, KYC, shortcode, other). External validation is off by default: email apisupport@safaricom.co.ke to enable it. The docs give the turnaround as about 6 h in one place and 24 working hours in another.
  • Production registration is one-time. To change URLs, delete them in Dashboard → URL Management (two org-portal Business Manager/Admin approvals), then register again. If you get "Duplicate notification info", the URLs are still registered on the older VPN aggregator ("Broker") platform: ask Safaricom to delete them there first.
  • Missed notifications aren't redelivered. Use the Pull Transactions API or the M-PESA Org portal (org.ke.m-pesa.com) to backfill.

B2C (Business to Customer)

POST /mpesa/b2c/v3/paymentrequest. You need a B2C or "one account" shortcode, because an ordinary Paybill can't disburse. You also need an API operator with the ORG B2C API initiator role and a SecurityCredential (see below).

TypeScript
// Full version: examples/org-apis.ts → b2cPayment()
await darajaPost("/mpesa/b2c/v3/paymentrequest", {
  OriginatorConversationID: payoutId,      // YOUR unique id: Daraja rejects duplicates (500.002.1001)
  InitiatorName: process.env.MPESA_INITIATOR_NAME,
  SecurityCredential: securityCredential,  // RSA-encrypted initiator password
  CommandID: "BusinessPayment",            // | "SalaryPayment" | "PromotionPayment"
  Amount: 500,                             // whole KES, min 10, max 250,000
  PartyA: process.env.MPESA_SHORTCODE,
  PartyB: "254708374149",                  // 12-digit MSISDN, no "+"
  Remarks: "Refund order 1042",            // 2–100 chars
  QueueTimeOutURL: `${process.env.APP_URL}/api/payments/b2c/timeout`,
  ResultURL: `${process.env.APP_URL}/api/payments/b2c/result`,
  Occassion: "",                           // sic: Safaricom's spelling, optional
});

The Result POSTed to ResultURL has ResultCode plus ResultParameters: TransactionReceipt, TransactionAmount, ReceiverPartyPublicName, B2CUtilityAccountAvailableFunds, and so on. Common failures:

CodeMeaning
1Not enough money in the Utility account. B2C debits Utility, not Working/MMF
2 / 3Below the minimum / above the maximum amount
4 / 8Would exceed the customer's daily limit / maximum balance (KES 500,000 each)
21API user lacks the B2C initiator role
2001Bad initiator name, password, or encryption (wrong certificate or padding)
2040Recipient isn't a registered M-Pesa customer
8006Security credential locked after failed attempts. The Business Admin unlocks it
SFC_IC0003Phone number doesn't exist on M-PESA

B2C payouts cannot be reversed via the API. Reversing one is a manual job on the org portal.

Transaction Status, Reversal, Account Balance

All three are asynchronous, initiator-based, and send results to your ResultURL.

APIEndpointKey fields
Transaction StatusPOST /mpesa/transactionstatus/v1/queryCommandID: "TransactionStatusQuery", TransactionID (receipt) or OriginalConversationID, PartyA, IdentifierType: "4"
ReversalPOST /mpesa/reversal/v1/requestCommandID: "TransactionReversal", TransactionID, Amount, ReceiverParty, RecieverIdentifierType: "11" (sic). Works for C2B and STK payments, not B2C. Results R000001 already reversed, R000002 invalid id
Account BalancePOST /mpesa/accountbalance/v1/queryCommandID: "AccountBalance", PartyA, IdentifierType: "4". The result is a pipe-delimited string per account: alias|KES|current|available|reserved|uncleared, joined by &

Transaction Status is the official secondary reconciliation tool when a callback never arrives. It works for C2B, B2B, B2C, reversals and IMT.

Security credential (initiator APIs)

Per the Getting Started page, you RSA-encrypt the initiator password with PKCS #1 v1.5 padding (not OAEP) using the environment's M-Pesa public certificate, then base64 the result. You can do this in Node directly. Earlier versions of this guide said "generate it on the portal only"; the portal tool is just a convenience.

TypeScript
// examples/security-credential.ts
import { constants, publicEncrypt, X509Certificate } from "node:crypto";

export function buildSecurityCredential(initiatorPassword: string, certPem: string): string {
  const key = new X509Certificate(certPem).publicKey;
  return publicEncrypt({ key, padding: constants.RSA_PKCS1_PADDING }, Buffer.from(initiatorPassword))
    .toString("base64");
}
// Certs: https://developer.safaricom.co.ke/certificates/SandboxCertificate.cer
//        https://developer.safaricom.co.ke/certificates/ProductionCertificate.cer

The API user's password expires every 90 days on the org portal. When you rotate it, regenerate the credential, or calls start failing with 2001 and then 8006.

M-Pesa Ratiba (standing orders)

POST /standingorder/v1/createStandingOrderExternal (sandbox) lets a customer approve a recurring debit once with their PIN. Use it for subscriptions, SACCO contributions, loan repayments, and hire purchase.

  • It's a commercial API. Test in the sandbox, then email apisupport@safaricom.co.ke and sign a contract before Go Live. Production endpoints are sent to you then.
  • Pricing: 5% of the transaction value, capped at KES 5 per executed standing order, excluding VAT, plus normal C2B tariffs on the receiving shortcode.
  • Key fields: StandingOrderName (unique per customer), StartDate/EndDate (yyyymmdd), and Frequency (1 one-off, 2 daily, 3 weekly, 4 bi-weekly, 5 monthly, 6 bi-monthly, 7 quarterly, 8 half-yearly, 9 yearly). Also TransactionType ("Standing Order Pay Bill External Third Party" or "Standing Order Pay Merchant External Third Party"), ReceiverPartyIdentifierType (4 paybill, 2 till), a UUID request id, and CallBackURL.
  • The doc's own sample body has typos (StandingOrderNameName, CustomStoId vs CustomstdoId). Confirm field names in the portal simulator before you build.

Callback security & URL rules

These are Safaricom's official rules, and they apply to every callback, result and timeout URL:

  • Allowlist the gateway IPs. Daraja doesn't sign callbacks. Accept callbacks only from these addresses, listed on the Getting Started page (2026-10-20): 196.201.214.200, 196.201.214.206, 196.201.213.114, 196.201.214.207, 196.201.214.208, 196.201.213.44, 196.201.212.127, 196.201.212.138, 196.201.212.129, 196.201.212.136, 196.201.212.74, 196.201.212.69. Also ignore any CheckoutRequestID/OriginatorConversationID you didn't create.
  • Use HTTPS in production. The sandbox accepts HTTP.
  • Banned words in URLs: M-PESA, mpesa, Safaricom, exe, exec, cmd, sql, query, in any case. This is why the examples use /api/payments/... instead of /api/mpesa/....
  • Avoid public tunnels (ngrok, mockbin, requestbin), "especially on production; they are usually blocked". The Getting Started page still suggests ngrok/LocalTunnel for localhost testing, so the docs contradict each other. If sandbox callbacks don't arrive through a tunnel, use a deployed preview URL. Make sure Vercel Deployment Protection is off for that path, because Safaricom can't get past it.
  • There are no retries. If your server is unavailable, "the API Gateway logs a 503 error and discards the results", and the Account Balance FAQ adds that M-PESA "does not automatically retry the callback". Return 200 fast. Then run a reconciliation job that queries every payment still pending after about 2 minutes, using STK Query or Transaction Status.

Limits & fees (re-verify before launch)

ItemValueSource
STK Push amountKES 1 – 250,000 per transactionM-Pesa Express FAQ
B2C amountKES 10 – 250,000 per transactionB2C FAQ
Customer walletMax balance KES 500,000; max daily value KES 500,000Daraja FAQs + safaricom.co.ke M-PESA charges (updated 4 Aug 2026)
Token TTLexpires_in: 3599 sAuthorization doc
ThroughputNot published. Exceeding it returns 500.003.02 Spike Arrest Violation / 500.003.03 Quota ViolationError tables
Same-subscriber pushesOne at a time; wait ≥ 1 min after "Unable to lock subscriber"STK error table
Buy Goods (Till) merchant feeFree up to KES 500; 0.55% for KES 501–36,363; KES 200 flat above that. Customers pay nothingsafaricom.co.ke M-PESA charges
Paybill feeDepends on the tariff you pick (Mgao, Business Bouquet or Customer Bouquet). Total per transaction runs from KES 0 to KES 108Safaricom Paybill Standard Tariff PDF (undated)
B2C fee (registered users)KES 0–13 per payout, paid by the businessSafaricom B2C registered users PDF (undated)
Ratiba5% capped at KES 5 per execution, excluding VATRatiba doc

Using Daraja itself costs nothing extra as far as published docs show: you pay M-PESA tariffs on the money moved. Confirm commercial terms with your Safaricom account manager.


Configuration

Secrets go in the vault, .env.local or Vercel env, and are server-only:

Bash
MPESA_CONSUMER_KEY=your_consumer_key          # Daraja app → Keys
MPESA_CONSUMER_SECRET=your_consumer_secret    # Daraja app → Keys
MPESA_PASSKEY=your_lnm_passkey                # STK only; emailed at Go Live (sandbox: simulator test data)
MPESA_INITIATOR_PASSWORD=your_api_operator_pw # initiator APIs only; rotate every 90 days

Non-secret settings can go in plain env or config:

VariableExampleNotes
MPESA_ENVsandbox / productionPicks the base host and certificate
MPESA_SHORTCODE174379 (sandbox STK)Paybill, or the HO/store number for tills
MPESA_TILL_NUMBER(optional)PartyB for Buy Goods STK
MPESA_INITIATOR_NAMEsandbox value from the simulator's test dataAPI operator username (case-sensitive)
APP_URLhttps://pay.example.co.kePublic HTTPS base for callbacks. No mpesa/safaricom in it

Sandbox test data

FieldValue
STK (Lipa na M-Pesa Online) shortcode174379
Test MSISDN254708374149
Passkey, InitiatorName, InitiatorPassword, other test shortcodesLog in → simulator / test credentials for your app

Sandbox STK test funds are auto-reversed at 06:00 the next day (Daraja FAQ). A single app can hold B2C or C2B, not both, so create separate apps.


Automation Workflows

Claude Code slash command: test STK Push

.claude/commands/mpesa-test.md:

Markdown
Send a sandbox M-Pesa Express (STK Push) to the test MSISDN 254708374149 using
`lib/payments/stk.ts` via `npx tsx scripts/stk-smoke.ts`. Report the
CheckoutRequestID and ResponseCode, wait 60s, then call stkQuery() with that
CheckoutRequestID and report ResultCode/ResultDesc. Never print keys or the passkey.

Usage: /project:mpesa-test

GitHub Actions: sandbox integration tests

YAML
# .github/workflows/mpesa-tests.yml
name: M-Pesa Sandbox Tests
on: [pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: '22' }
      - run: npm ci
      - name: Run M-Pesa sandbox tests
        env:
          MPESA_CONSUMER_KEY: ${{ secrets.MPESA_SANDBOX_CONSUMER_KEY }}
          MPESA_CONSUMER_SECRET: ${{ secrets.MPESA_SANDBOX_CONSUMER_SECRET }}
          MPESA_PASSKEY: ${{ secrets.MPESA_SANDBOX_PASSKEY }}
          MPESA_SHORTCODE: "174379"
          MPESA_ENV: sandbox
          APP_URL: ${{ vars.PREVIEW_CALLBACK_BASE }}   # a reachable HTTPS preview, not a public bin
        run: npm run test:mpesa

Common Use Cases

Use caseApproach
Checkout / one-off paymentSTK Push, then the callback, then STK Query for stragglers
Customer pays from the M-Pesa menu (Paybill/Till)C2B v2 register + confirmation (and validation if enabled)
Recurring / subscription billingM-Pesa Ratiba (commercial; customer approves once). For a one-off monthly charge, use an STK Push per cycle
Refund a customer paymentReversal API (C2B/STK receipts), or a B2C payout if the reversal window has passed
Payout / disbursementB2C (BusinessPayment) from a B2C/one-account shortcode
"Did this payment happen?"STK Query (STK) or Transaction Status (any receipt)
Missed C2B notificationsPull Transactions API / org portal
Float monitoring before payoutsAccount Balance (check the Utility account)

Troubleshooting

IssueFix
404.001.03 / 400.003.01 / 401.002.01 "Invalid Access Token"Token expired, or replaced by a newer token request. Refresh once and retry, and share the token cache across instances
400.002.02 Bad Request – Invalid BusinessShortCodeMissing Content-Type: application/json, a misspelled field, or the wrong shortcode
500.001.1001 Wrong credentials (STK)Password isn't base64(shortcode+passkey+timestamp), or the shortcode/timestamp in the body doesn't match the ones you encoded
500.001.1001 Merchant does not existUse the shortcode you went live with as BusinessShortCode
500.001.1001 Unable to lock subscriberA push is already open for that phone. Wait ≥ 1 min
500.003.02 Spike Arrest / 500.003.03 Quota ViolationYou're over the TPS/quota limit, or your endpoints are erroring a lot. Throttle and fix the failing callbacks
"Invalid API call as no apiproduct match found"Enable the right product on the app (e.g. "M-PESA Express Sandbox", "Lipa na M-PESA" in production)
No callbacks arrivingMust be public HTTPS, have no mpesa/safaricom in the URL, and not be blocked by a firewall, Vercel Deployment Protection, or your IP allowlist
C2B "Urls are already registered"Delete them in Dashboard → URL Management, then register again
B2C 2001 initiator invalidWrong operator username, password, certificate, or padding (must be PKCS#1 v1.5)
B2C 1 insufficient balance despite fundsMoney is in Working/MMF. Move it to Utility (org portal, or B2B BusinessTransferFromMMFToUtility)
STK prompt shows the org number, not the nameExpected when the customer pays through Fuliza
Phone shows masked (2547 ***** 126)Expected with C2B v2 since the March 2026 masking change. Reconcile on BillRefNumber + TransID

codeAmani notes

  • Use this only for Kenya-targeted projects. Stripe is the default rail for codeAmani's US-first products. Add Daraja only when a project's primary users are in Kenya (e.g. the six WhatsApp + M-Pesa apps in codeAmani-labs-projects/).
  • Keep it all server-side. Consumer key/secret, passkey and initiator password live in the vault (Hazina) or .env.local, never in client bundles. Token fetches, STK Push and callbacks run in route handlers or server actions only.
  • Route naming conflict. The workspace CLAUDE.md file structure suggests app/api/mpesa/, but Safaricom's URL rules forbid "mpesa" in callback URLs. Put the callback routes under a neutral path such as app/api/payments/.... Code modules can keep lib/mpesa-*.ts names, since those never appear in a URL.
  • Conventions: phone 254XXXXXXXXX, whole KES, cached 1-hour token, HTTPS callbacks, store CheckoutRequestID on the STK response and dedupe on it in the callback. Sandbox shortcode 174379, test phone 254708374149.
  • Callbacks are fire-and-forget. Keep the handler under about 1 s. Push SMS receipts, WhatsApp messages, fulfilment, and any AI calls (Claude by AI routing policy) onto a queue such as Upstash QStash.
  • African-market UX: users are mostly on Android, often on 2G/3G. Show "Check your phone for the M-Pesa prompt" immediately, poll your own DB (not Daraja) from the client, and offer "Resend prompt" only after 1032/1037 or about 90 s with no answer.
  • Compliance: M-Pesa phone numbers and names are personal data under KDPA 2019 (see COMPLIANCE_GUIDE.md). Store the minimum and never log full payloads with names in plain text.
  • See root MPESA_PATTERNS.md, AFRICAN_MARKET_GUIDE.md and this folder's PATTERNS.md / examples/ for the full lifecycle.