daraja-openapi

TypeScript

@bytegigs/daraja is a typed client for Node.js 20 and later, with no runtime dependencies. Its types are generated from the spec.

npm install @bytegigs/daraja

Create a client

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", or baseUrl for the mock
  shortCode: "174379",
  passkey: process.env.DARAJA_PASSKEY,
});

Methods

MethodOperation
accessToken()Access token (cached)
stkPush()STK Push
stkQuery(), waitForStkResult()STK Push Query
c2bRegisterUrls(), c2bSimulate()C2B
b2cPayment()B2C
b2bPayment()B2B
reversal()Reversal
transactionStatus()Transaction status
accountBalance()Account balance
dynamicQr()Dynamic QR

Reading callbacks

FunctionReads
parseStkCallback(body)STK Push callbacks
parseC2bTransaction(body)C2B validation and confirmation
parseAsyncResult(body)Results of B2C, B2B, reversal, status and balance
parseAccountBalance(value)The AccountBalance result parameter

Each returns null for a body it doesn't recognise.

Errors

DarajaError has status, errorCode, isPending, isRateLimited, retryAfterMs and isProductMissing. DarajaValidationError names the field that was refused. See errors and rate limits.

Testing

const daraja = new Daraja({
  consumerKey: "mock-consumer-key",
  consumerSecret: "mock-consumer-secret",
  baseUrl: "http://127.0.0.1:4010",
  shortCode: "174379",
  passkey: "bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919",
});

See testing with the mock.

View the source of this page

Built by ByteGigs Labs. Apache 2.0. M-PESA, Daraja and Safaricom are trademarks of Safaricom PLC; this project is independent and not endorsed by Safaricom.