SDKs
Kotlin
A coroutine-based client for Safaricom's Daraja (M-PESA) API for server-side Kotlin: Ktor, Spring, Micronaut. JDK 17+, built from the daraja-openapi spec and tested against its mock.
Never call Daraja from an Android app. The app would carry your consumer secret and passkey to every phone. Call your own server, and let it call Daraja.
dependencies {
implementation("com.bytegigs:daraja:0.2.0")
}
STK Push
val daraja = Daraja(
System.getenv("DARAJA_CONSUMER_KEY"),
System.getenv("DARAJA_CONSUMER_SECRET"),
environment = DarajaEnvironment.SANDBOX,
shortCode = "174379",
passkey = System.getenv("DARAJA_PASSKEY"),
)
val push = daraja.stkPush(
amount = 150,
phone = "0712 345 678",
callbackUrl = "https://your-app.example/daraja/callback",
accountReference = "INV-1001",
description = "Invoice 1001",
)
// Callbacks are not signed: confirm before you deliver.
val status = daraja.waitForStkResult(push["CheckoutRequestID"]!!.jsonPrimitive.content)
when (status.state) {
StkState.PAID -> markPaid()
StkState.FAILED -> println(status.meaning) // "The customer cancelled the payment"
StkState.PENDING -> {} // still waiting; reconcile later
}
Read the callback at your callbackUrl with Callbacks.stk(body).
Payouts and the other APIs
val daraja = Daraja(key, secret, shortCode = "600996",
initiatorName = "testapi",
initiatorPassword = System.getenv("DARAJA_INITIATOR_PASSWORD"),
certificate = File("SandboxCertificate.cer").readBytes())
val urls = ResultUrls("https://your-app.example/daraja/result", "https://your-app.example/daraja/timeout")
daraja.b2cPayment("refund-order-77", 150, "0712345678", "Refund order 77", urls)
// At the result URL:
val outcome = Callbacks.asyncResult(body)
if (outcome?.ok == true) println(outcome.params["TransactionAmount"])
Also: c2bRegisterUrls, c2bSimulate, b2bPayment, reversal,
transactionStatus, accountBalance (read with outcome.accountBalances)
and dynamicQr (returns PNG bytes). Callbacks.c2b(body) reads C2B
confirmations.
Errors are DarajaException (status, errorCode, isPending,
isRateLimited, isProductMissing); bad input throws
DarajaValidationException before anything is sent.
Tests
npx @bytegigs/daraja-mock --port 4010 &
DARAJA_MOCK_URL=http://127.0.0.1:4010 gradle test