Metadata-Version: 2.4
Name: mpesa-daraja-core
Version: 0.9.0
Summary: M-Pesa Daraja SDK for Python — one hardened core shared with Go and TypeScript under a single executable wire contract.
Home-page: https://github.com/anthrodjear/mpesa-sdk
Author: mpesa-sdk maintainers
License: MIT
Project-URL: Source, https://github.com/anthrodjear/mpesa-sdk
Project-URL: Issues, https://github.com/anthrodjear/mpesa-sdk/issues
Project-URL: Changelog, https://github.com/anthrodjear/mpesa-sdk/blob/main/CHANGES.md
Keywords: mpesa,daraja,safaricom,stk-push,payments,mobile-money,kenya
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Office/Business :: Financial
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.11
Description-Content-Type: text/markdown
Requires-Dist: requests<3,>=2.32.4
Requires-Dist: cryptography<51,>=48.0.1
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: pytest-cov>=6; extra == "dev"
Dynamic: author
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: license
Dynamic: project-url
Dynamic: provides-extra
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# mpesa-daraja-core

[![Python](https://img.shields.io/badge/Python-3.11+-3776AB?logo=python)](https://pypi.org/project/mpesa-daraja-core/)

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

## Install

```sh
pip install mpesa-daraja-core
```

## Quick start

```python
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.

```python
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](https://github.com/anthrodjear/mpesa-sdk#readme).
