bytegigs / daraja
A typed client for Safaricom's Daraja (M-PESA) API: STK Push, C2B, B2C, B2B, reversal, status, balance and Dynamic QR. No dependencies.
Package info
github.com/ByteGigs-Labs/daraja-openapi
Language:TypeScript
pkg:composer/bytegigs/daraja
Requires
- php: >=8.1
- ext-curl: *
- ext-json: *
- ext-mbstring: *
- ext-openssl: *
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
- dev-main
- v0.3.1
- v0.3.0
- v0.2.0
- dev-fix/cryptography-floor
- dev-fix/mock-bin-for-npm-11
- dev-fix/findings-from-kibanda
- dev-docs/sidebar-controls
- dev-docs/multi-page
- dev-release/pypi
- dev-docs/marketplace-action
- dev-ci/marketplace-action
- dev-release/skip-published
- dev-release/0.2.0
- dev-fix/security-review
- dev-docs/site-and-verified
- dev-feature/kotlin-sdk
- dev-feature/php-sdk
This package is not auto-updated.
Last update: 2026-12-04 08:34:52 UTC
README
Docs and API reference: https://bytegigs-labs.github.io/daraja-openapi/
A verified OpenAPI spec for Safaricom's Daraja (M-PESA) API, clients for TypeScript, Python, PHP, Kotlin and Swift, and a mock that sends real callbacks, for local tests and CI.
Safaricom doesn't publish a machine-readable description of Daraja, so every M-PESA library re-reads the docs and guesses. This project writes the API down once, as an OpenAPI 3.1 spec, checks it against the Daraja sandbox every night, and generates clients from it. When Daraja changes, the spec changes, and every client follows.
| Package | What it is |
|---|---|
spec/daraja.openapi.yaml |
The spec: OAuth, M-PESA Express (STK Push and Query), C2B, B2C, B2B, reversal, transaction status, account balance and Dynamic QR, with every callback body |
@bytegigs/daraja |
TypeScript client for Node.js 20+, no runtime dependencies |
bytegigs-daraja for Python |
Sync and async client on httpx, Python 3.10+ |
bytegigs/daraja for PHP |
No dependencies, PHP 8.1+; Laravel, WordPress, plain PHP |
com.bytegigs:daraja for Kotlin |
Coroutines client for Ktor and Spring, JDK 17+ |
Daraja for Swift |
Swift 6 client generated with swift-openapi-generator, on AsyncHTTPClient |
@bytegigs/daraja-mock |
A local Daraja that sends STK callbacks, with test numbers for every outcome |
actions/daraja-mock |
The mock as a GitHub Action, for testing M-PESA code in CI with no sandbox keys |
This project is independent and is not made or endorsed by Safaricom.
Quick start
npm install @bytegigs/daraja
import { Daraja } from "@bytegigs/daraja"; const daraja = new Daraja({ consumerKey: process.env.DARAJA_CONSUMER_KEY!, consumerSecret: process.env.DARAJA_CONSUMER_SECRET!, environment: "sandbox", // or "production" shortCode: process.env.DARAJA_SHORTCODE!, passkey: process.env.DARAJA_PASSKEY!, }); const { CheckoutRequestID } = await daraja.stkPush({ amount: 150, phone: "0712 345 678", // any Kenyan format works callbackUrl: "https://your-app.example/mpesa/callback", accountReference: "INV-1001", // up to 12 characters description: "Invoice 1001", // up to 13 characters });
The client handles the parts that trip people up:
- It caches the access token and shares one refresh between concurrent requests.
- It builds the STK password and the timestamp in Kenyan time, whatever time zone your server runs in.
- It accepts phone numbers in any common Kenyan format.
- It checks field limits before sending, so Daraja never sees a bad request.
It never retries an STK Push by itself, because a retry would send the customer a second prompt.
Handling the callback
Daraja POSTs the result to your callbackUrl. These callbacks are not signed, so treat one as a notification, and confirm the payment before you deliver anything.
import { parseStkCallback } from "@bytegigs/daraja"; app.post("/mpesa/callback", async (req, res) => { res.sendStatus(200); // answer Daraja first const result = parseStkCallback(req.body); if (!result) return; // not an STK Push result: ignore it // result.paid, result.amount, result.receipt, result.meaning ("The customer cancelled the payment") try { const confirmed = await daraja.stkQuery({ checkoutRequestId: result.checkoutRequestId }); if (confirmed.state === "paid") await markOrderPaid(result.checkoutRequestId, result.receipt); } catch (error) { // A 429 or "still processing": leave the order open and check again later. // The response is already sent, so nothing may escape here: in Node it would crash the process. console.warn("payment not confirmed yet:", error.message); } });
Callbacks can also go missing. waitForStkResult polls the STK Push Query until the customer answers, which also recovers payments whose callback never arrived:
const status = await daraja.waitForStkResult({ checkoutRequestId, timeoutMs: 90_000 });
Don't query straight after the push. The nightly sandbox run found that Daraja answers HTTP 429 to an STK Push Query sent seconds after the STK Push. waitForStkResult waits before its first query and backs off on 429. If you call stkQuery yourself, check error.isRateLimited and error.retryAfterMs.
Paying out, and the other APIs
B2C, B2B, reversal, transaction status and account balance act as your API
initiator. Give the client the initiator name, its password and Safaricom's
certificate (sandbox and production certificates differ; download them from the
Daraja portal). The SDK encrypts the password into Daraja's SecurityCredential;
the password never leaves your server.
const daraja = new Daraja({ consumerKey, consumerSecret, environment: "sandbox", shortCode: "600996", initiatorName: "testapi", initiatorPassword: process.env.DARAJA_INITIATOR_PASSWORD, certificate: readFileSync("SandboxCertificate.cer"), }); // Refund a customer. Reuse the ID on retries so you never pay twice. await daraja.b2cPayment({ originatorConversationId: "refund-order-77", amount: 150, phone: "0708 374 149", remarks: "Refund order 77", resultUrl: "https://your-app.example/daraja/result", timeoutUrl: "https://your-app.example/daraja/timeout", }); // Later, at resultUrl: const result = parseAsyncResult(req.body); if (result?.ok) markRefunded(result.originatorConversationId, result.transactionId);
These APIs answer at resultUrl, not in the response. parseAsyncResult reads
any of them; parseAccountBalance turns the balance string into numbers, and
parseC2bTransaction reads C2B confirmations. Dynamic QR answers straight away
with a base64 PNG.
| Operation | Method | Verified against the sandbox |
|---|---|---|
| STK Push, STK Push Query | stkPush, stkQuery, waitForStkResult |
✅ |
| Dynamic QR | dynamicQr |
✅ |
| C2B register URLs, simulate | c2bRegisterUrls, c2bSimulate |
✅ |
| B2C, B2B | b2cPayment, b2bPayment |
✅ |
| Reversal, transaction status, account balance | reversal, transactionStatus, accountBalance |
✅ |
Testing without the sandbox
The mock behaves like Daraja and then sends the STK callback to your app, which the real sandbox can't do in CI. The phone number picks the outcome:
| Phone number | Result |
|---|---|
254700000001 |
Cancelled by the customer (1032) |
254700000002 |
Insufficient balance (1) |
254700000003 |
Phone unreachable or no response (1037) |
254700000004 |
Wrong PIN (2001) |
254700000005 |
Paid, but the callback is never sent, to test your reconciliation |
| any other valid number | Paid |
The mock also serves every other operation and sends their results to your
ResultURL. Paid STK, C2B and B2C transactions get receipts that transaction status
and reversal can find. For B2C, 254700000002 fails with insufficient funds and
254700000005 times out in the queue (only QueueTimeOutURL is called).
Locally:
npx @bytegigs/daraja-mock --port 4010
Then point the client at it with baseUrl: "http://127.0.0.1:4010". The mock accepts mock-consumer-key / mock-consumer-secret and Daraja's public sandbox passkey.
In GitHub Actions, with Daraja Mock Server from the Marketplace:
- id: daraja uses: ByteGigs-Labs/daraja-mock-action@v1 - run: npm test env: DARAJA_BASE_URL: ${{ steps.daraja.outputs.url }}
How the spec stays true
- Every operation says whether it is verified.
x-daraja-verifiedholds the date its contract test last passed against the sandbox, ornulluntil it has. - A nightly sandbox run checks the spec against the real sandbox (workflow). If Daraja behaves differently, the workflow opens a
spec-driftissue through the GitHub API. - The mock is tested against the spec's own schemas, so it can't drift from the spec either.
- CI fails if the spec changes without the generated types being regenerated.
To change the spec:
- Edit
spec/daraja.openapi.yaml. - Run
npm run generate. - Run
npm run lint:spec && npm test. - Open a pull request.
Development
npm install npm run lint:spec # Spectral npm run generate # regenerate TypeScript types from the spec npm run typecheck npm run build npm test # SDK and mock tests, including spec conformance npm run test:contract # against the real sandbox; needs DARAJA_* variables
Roadmap
- Spec: Bill Manager, Ratiba (standing orders) and the B2C account top-up.
Security
Keep consumer secrets and passkeys in environment variables or a secret manager, never in source code or in a mobile app. The client never includes credentials when it is logged or serialised. To report a vulnerability, see SECURITY.md.
License
Apache License 2.0. See NOTICE: the licence covers the code and spec.