daraja-openapi

Swift

A Swift 6 client for Safaricom's Daraja (M-PESA) API, for server-side Swift (Vapor, Hummingbird) and Apple platforms. The client and its types are generated from the spec by swift-openapi-generator and sent with AsyncHTTPClient. DarajaClient adds what a spec can't express: token caching, the STK password, Kenyan timestamps, phone formats and pending STK results.

Install

.package(url: "https://github.com/ByteGigs-Labs/daraja-openapi", from: "0.2.0"),
// …
.product(name: "Daraja", package: "daraja-openapi"),

STK Push

import Daraja

let daraja = try DarajaClient(
    consumerKey: env("DARAJA_CONSUMER_KEY"),
    consumerSecret: env("DARAJA_CONSUMER_SECRET"),
    environment: .sandbox,
    shortCode: "174379",
    passkey: env("DARAJA_PASSKEY")
)

let push = try await daraja.stkPush(
    amount: 150,
    phone: "0712 345 678",
    callbackURL: "https://your-app.example/daraja/callback",
    accountReference: "INV-1001",
    description: "Invoice 1001"
)

// Confirm before you deliver: callbacks are not signed.
switch try await daraja.waitForStkResult(checkoutRequestID: push.CheckoutRequestID) {
case .paid: try await markPaid()
case let .failed(_, _, meaning): print(meaning)   // "The customer cancelled the payment"
case .pending: break                              // still waiting; reconcile later
}

Read the callback Daraja sends to your callbackURL:

let result = try StkResult(json: requestBody)
if result.paid { print(result.receipt ?? "", result.amount ?? 0) }

Payouts and the other APIs

B2C, account balance and transaction status need your API initiator and its SecurityCredential: the initiator password encrypted with Safaricom's certificate. Make it once and keep it in your secrets:

printf %s "$INITIATOR_PASSWORD" \
  | openssl pkeyutl -encrypt -certin -inkey SandboxCertificate.cer -pkeyopt rsa_padding_mode:pkcs1 \
  | base64 -w0
let daraja = try DarajaClient(
    consumerKey: key, consumerSecret: secret, shortCode: "600996",
    initiator: .init(name: "testapi", securityCredential: env("DARAJA_SECURITY_CREDENTIAL"))
)
let urls = ResultURLs(result: "https://your-app.example/daraja/result",
                      timeout: "https://your-app.example/daraja/timeout")

try await daraja.b2cPayment(originatorConversationID: "refund-77", amount: 150,
                            phone: "0712345678", remarks: "Refund order 77", urls: urls)

// At urls.result:
let outcome = try AsyncResult(json: requestBody)
if outcome.ok { print(outcome.transactionID ?? "", outcome.params["TransactionAmount"] ?? "") }

Also: c2bRegisterURLs, accountBalance (read with outcome.accountBalances), transactionStatus and dynamicQR (returns PNG bytes). Everything else in the spec is on daraja.raw, the generated client.

Testing

Run @bytegigs/daraja-mock and point the client at it:

npx @bytegigs/daraja-mock --port 4010 &
DARAJA_MOCK_URL=http://127.0.0.1:4010 swift test
let daraja = try DarajaClient(consumerKey: "mock-consumer-key", consumerSecret: "mock-consumer-secret",
                          baseURL: URL(string: "http://127.0.0.1:4010")!, shortCode: "174379",
                          passkey: "bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919")

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.