daraja-openapi

Python

A typed Python client for Safaricom's Daraja (M-PESA) API, sync and async, built from the daraja-openapi spec and tested against it. Python 3.10+, one dependency (httpx).

pip install bytegigs-daraja
# B2C, B2B, reversal, status and balance encrypt your initiator password:
pip install "bytegigs-daraja[credential]"

STK Push

from daraja import Daraja

daraja = Daraja(
    os.environ["DARAJA_CONSUMER_KEY"],
    os.environ["DARAJA_CONSUMER_SECRET"],
    environment="sandbox",
    short_code="174379",
    passkey=os.environ["DARAJA_PASSKEY"],
)

push = daraja.stk_push(
    amount=150,
    phone="0712 345 678",  # any Kenyan format
    callback_url="https://your-app.example/daraja/callback",
    account_reference="INV-1001",
    description="Invoice 1001",
)

# Callbacks are not signed: confirm before you deliver.
status = daraja.wait_for_stk_result(push["CheckoutRequestID"])
if status.state == "paid":
    mark_paid()
elif status.state == "failed":
    print(status.meaning)  # "The customer cancelled the payment"

FastAPI and other asyncio apps use AsyncDaraja with the same methods:

async with AsyncDaraja(key, secret, short_code="174379", passkey=passkey) as daraja:
    push = await daraja.stk_push(...)

Read the callback at your callback_url:

from daraja import parse_stk_callback

result = parse_stk_callback(request.json())
if result and result.paid:
    print(result.receipt, result.amount)

Payouts and the other APIs

daraja = Daraja(
    key,
    secret,
    short_code="600996",
    initiator_name="testapi",
    initiator_password=os.environ["DARAJA_INITIATOR_PASSWORD"],
    certificate=open("SandboxCertificate.cer", "rb").read(),
)

daraja.b2c_payment(
    originator_conversation_id="refund-order-77",  # reuse on retries
    amount=150,
    phone="0712345678",
    remarks="Refund order 77",
    result_url="https://your-app.example/daraja/result",
    timeout_url="https://your-app.example/daraja/timeout",
)

# At result_url:
outcome = parse_async_result(request.json())
if outcome and outcome.ok:
    print(outcome.transaction_id, outcome.params["TransactionAmount"])

Also: c2b_register_urls, c2b_simulate, b2b_payment, reversal, transaction_status, account_balance (read with outcome.account_balances) and dynamic_qr (returns PNG bytes). parse_c2b_transaction reads C2B confirmations.

Errors are DarajaError (.status, .error_code, .is_pending, .is_rate_limited, .is_product_missing); bad input raises DarajaValidationError before anything is sent. STK Push and payouts are never retried automatically.

Testing without the sandbox

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

npx @bytegigs/daraja-mock --port 4010
Daraja(
    "mock-consumer-key",
    "mock-consumer-secret",
    base_url="http://127.0.0.1:4010",
    short_code="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.