Skip to main content

mpesa-daraja-core

Python

Python SDK for the Safaricom M-Pesa Daraja API. Zero-config first call: four environment variables and one client.

Install

pip install mpesa-daraja-core

Quick start

from mpesa import MpesaClient, STKPushRequest, TransactionType

client = MpesaClient.from_env()  # reads MPESA_*; sandbox by default

resp = client.stk_push(STKPushRequest(
    transaction_type=TransactionType.CUSTOMER_PAY_BILL_ONLINE,
    amount=100,
    party_a="254712345678",
    phone_number="254712345678",
    call_back_url="https://example.com/stk/callback",
    account_reference="Order42",
    transaction_desc="test",
))
print(resp.response_code, resp.checkout_request_id)

from_env() reads MPESA_CONSUMER_KEY, MPESA_CONSUMER_SECRET, MPESA_SHORTCODE and MPESA_PASSKEY. A missing variable raises ValueError naming it. MPESA_ENVIRONMENT accepts sandbox (default), production or prod; MpesaClient.from_env("prod") overrides the variable.

Accepted ≠ paid. response_code == "0" means the prompt was queued. Settle only after an stk_query bound to your stored checkout_request_id, and require result.verify_amount(order_amount).

Money is whole KES. Amounts are integers, never floats; inbound callback amounts are validated against a canonical grammar with no rounding or fractional KES. A callback amount is advisory until checked against your stored order.

One hardened core is implemented in Go, Python and TypeScript against one executable wire contract; a shared fixture corpus pins identical wire behaviour across all three engines. Go and TypeScript have no runtime dependencies; Python uses requests and cryptography.

Receiving callbacks

token_on_file, repo, client, mark_paid and mark_pending_reconcile are application code.

Daraja callbacks are unsigned; the query round-trip and stored-amount check are the settlement controls. Indeterminate results are never auto-failed — reconcile them.

A valid token proves only that the caller knows the URL; it authenticates nothing about the body or the payment. This example returns 200 for a token mismatch — a deliberate per-engine difference, not a weaker control. Malformed bodies are ACKed 200 rather than returning 5xx. Framework-level body limits (Flask MAX_CONTENT_LENGTH, express.raw() default) can still return 413 before the handler — configure them to match your policy.

from flask import Flask, request
from mpesa import ResultClass, STKQueryRequest, StkCallbackResult, callback_token_equal

app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 1 << 20


@app.post("/mpesa/callback/<token>")
def stk_callback(token: str):
    if not callback_token_equal(token_on_file, token):
        return "", 200
    try:
        result = StkCallbackResult.from_json(request.get_data())
    except ValueError:
        return "", 200  # malformed: ACK, never a 5xx
    order = repo.by_checkout(result.checkout_request_id)
    if order is None:
        return "", 200
    paid = False
    if result.classify() is ResultClass.SUCCESS:
        resp = client.stk_query(STKQueryRequest(
            checkout_request_id=result.checkout_request_id))
        if resp.result_code == "0" and result.verify_amount(order.amount):
            mark_paid(order)
            paid = True
    if not paid:
        mark_pending_reconcile(order)
    return "", 200

What is covered

STK Push/Query, B2C, C2B register/simulate, Transaction Status, Reversal, Account Balance, Dynamic QR, B2B, Tax Remittance and Bill Manager — plus typed callbacks, token refresh with 401.003.01 retry-once, and redacted credential rendering.

Documentation

Full guide and cross-engine contract: the repository README.

Metadata

Release files for mpesa-daraja-core 0.9.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mpesa-daraja-core 0.9.0
File Size Uploaded Provenance Actions
mpesa_daraja_core-0.9.0.tar.gz 84.8 kB With provenance Details for mpesa_daraja_core-0.9.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mpesa-daraja-core 0.9.0
File Interpreter ABI Platform Actions
mpesa_daraja_core-0.9.0-py3-none-any.whl Python 3 none any Details for mpesa_daraja_core-0.9.0-py3-none-any.whl

Total release size: 178.0 kB

Release files / mpesa_daraja_core-0.9.0.tar.gz

Download URL mpesa_daraja_core-0.9.0.tar.gz
Size 84.8 kB
Tags Source
SHA-256 checksum
How to use checksums
0c388cd831e6b9f2680699b27ca8c2869a8924e24ea41795087eca0f1ba96a55
BLAKE2b-256 checksum
How to use checksums
e121a755b2d4b5474b7fa371bd6d327837b1b6923caa0a41a4dd4ddfba2d289c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Release files / mpesa_daraja_core-0.9.0-py3-none-any.whl

Download URL mpesa_daraja_core-0.9.0-py3-none-any.whl
Size 93.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
780c9d7c20fbe72ff4199867533c26cbc87119418904b51c421b72974bef9fd6
BLAKE2b-256 checksum
How to use checksums
e18d3c93e68be8954deaa81002ec6147dc2ab84f209c88dbe78b803a40eff393
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Security for mpesa-daraja-core 0.9.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for mpesa_daraja_core-0.9.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.9.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page