Metadata-Version: 2.1
Name: moolre
Version: 0.1.2
Summary: Official Moolre server SDK: collections, payouts, name validation, sales, SMS, WhatsApp, payment links, bulk payouts and webhook verification.
Home-page: https://docs.moolre.com/sdks
Author-email: Moolre <hello@moolre.com>
License: MIT
Keywords: moolre,payments,mobile-money,ghana,sdk
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown

# moolre

Official Moolre server SDK for Python 3.9+. Standard library only (no `requests`), fully typed-friendly, usable as a package or as the single file `moolre.py`.

It covers mobile money collections (with the OTP flow), payouts with optional `sender_name`, name validation, accounts and cursor-paginated transactions, airtime and data sales, SMS, WhatsApp, payment links, bulk payouts, webhook deliveries and `X-Moolre-Signature` verification.

> Keep credentials on your server.

## Install

```bash
pip install moolre
```

Or copy `moolre.py` next to your code.

## Quickstart

```python
import os
import moolre

client = moolre.Moolre(
    environment="sandbox",                 # "live" = https://api.moolre.com, "sandbox" = https://sandbox.moolre.com
    user=os.environ["MOOLRE_USER"],        # X-API-USER
    api_key=os.environ["MOOLRE_API_KEY"],  # X-API-KEY    (payouts, accounts, sales, bulk)
    pub_key=os.environ["MOOLRE_PUBKEY"],   # X-API-PUBKEY (collections, payment links)
    vas_key=os.environ.get("MOOLRE_VASKEY"),  # X-API-VASKEY (SMS, WhatsApp)
    account_number="10000001",             # default wallet for every call
)

result = client.payments.initiate(
    channel="MTN", currency="GHS", payer="0241234567", amount="1.00",
    external_ref="PAY-1001",
    idempotency_key=moolre.new_idempotency_key(),   # makes retries safe
)
print(result.code, result.request_id, result.notices)

if result.otp_required:                    # code TP14: the customer received an SMS code
    client.payments.verify_otp(otp_code="123456", channel="MTN", currency="GHS",
                               payer="0241234567", amount="1.00", external_ref="PAY-1001")
    # on TP17 (result.otp_verified) call initiate() once more without otp_code
```

`Moolre.from_env()` reads `MOOLRE_ENV`, `MOOLRE_USER`, `MOOLRE_API_KEY`, `MOOLRE_PUBKEY`, `MOOLRE_VASKEY` and `MOOLRE_ACCOUNT`.

Every configured credential is sent as a header (`X-API-USER`, `X-API-KEY`, `X-API-PUBKEY`, `X-API-VASKEY`) on every request, never in the URL or body. Channels are names: `MTN`, `TELECEL`, `AT`, `BANK`.

## Results, errors and notices

Every call returns a `Result` with `ok`, `status`, `code`, `message`, `data`, `go`, `request_id`, `notices`, `replayed`, `http_status` and `raw` (the untouched JSON).

When the API answers `status: 0` the SDK raises `moolre.ApiError` (or `AuthenticationError`, `IdempotencyError`, `RateLimitError`, `NotFoundError`, `ValidationError`, `ServerError`) with `code`, `api_message`, `fields`, `request_id` and `result`. Pass `throw_on_error=False` to get the result instead. Network failures raise `NetworkError` / `RequestTimeoutError`, non-JSON replies `InvalidResponseError`, bad configuration `ConfigurationError`.

```python
try:
    client.transfers.create(channel="MTN", currency="GHS", amount="5.00", receiver="0241234567", external_ref="P-1")
except moolre.ApiError as e:
    print(e.code, e.api_message, e.fields, e.request_id)
```

`request_id` and `notices` come from the `meta` object (`meta.requestid`, `meta.notices`, and `meta.replayed` on idempotent replays) that the API adds to every JSON response; the SDK falls back to the legacy top-level `request_id` / `notices`, then to the `X-Request-Id` header, so older and newer API versions both work.

Decide the outcome of a call from `status`, `code` and `data.txstatus` (0 pending, 1 succeeded, 2 failed). The codes PY01, PY02, TR01, TR02, TP11, TP18, APY10, APY16, ASL06 and SYS500 mean "unknown, may still succeed": treat them as pending, check the status and never resend blindly.

API notices (e.g. deprecation advice) are on `result.notices` and are logged once per code through `logger` (default: stderr; pass `None` to silence, or any object with `warn(message)`).

Options: `strict_http_status=True` (ask the API for real 4xx/5xx codes), `max_retries=2` (network errors and 5xx are retried only for reads and calls that carry an `idempotency_key`), `retry_delay`, `timeout=60.0`, `base_url`.

## Payouts and name validation

```python
who = client.transfers.validate_name(channel="MTN", currency="GHS", receiver="0241234567")

client.transfers.create(channel="MTN", currency="GHS", amount="25.00", receiver="0241234567",
                        external_ref="PAYOUT-77", sender_name="Acme", idempotency_key="payout-77")
client.transfers.status(external_ref="PAYOUT-77")
```

## Transactions with cursor pagination

```python
for tx in client.accounts.iterate_transactions(status=1, page_size=200):
    print(tx["transactionid"], tx["amount"])
```

The iterator walks the id cursor (`endid`/`startid`), so pages never overlap. `whatsapp.iterate_templates()`, `webhooks.iterate_deliveries()`, `bulk.iterate_batches()`, `bulk.iterate_items()` and `invoices.iterate()` work the same way.

## Bulk payouts

```python
batch = client.bulk.create(
    currency="GHS", batch_ref="payroll-2026-11", idempotency_key="payroll-2026-11",
    items=[
        {"external_ref": "p-1", "receiver": "0241234567", "channel": "MTN", "amount": "10.00"},
        {"external_ref": "p-2", "receiver": "0201234567", "channel": "TELECEL", "amount": "5.50", "sender_name": "Acme"},
    ],
)
print(batch.data["accepted"], batch.data["rejected"])   # rejected rows carry index, code, message, externalref
progress = client.bulk.status(batch_ref="payroll-2026-11")          # counts + a page of items
for item in client.bulk.iterate_items(batch_ref="payroll-2026-11", status="failed"):
    print(item["externalref"], item["code"])
```

Up to 500 items per batch, validated on submit; `atomic=True` queues nothing if any row is rejected. Sending the same `batch_ref` and body again replays the original batch (`BLK02`, `replayed=True`). A `bulk_payout.completed` webhook is sent when every item is final, and each payout also sends its own `payout.succeeded` / `payout.failed`.

## Invoices

```python
inv = client.invoices.create(
    currency="GHS", invoice_name="Term 1 fees", customer={"name": "Ama Mensah", "phone": "0244000111"},
    items=[{"description": "Tuition", "quantity": 1, "amount": "450.00"}],
    due_date="2026-12-31", reference="INV-1001",
)
print(inv.data["payment_link"])            # give this to the customer
client.invoices.status(reference="INV-1001")
for i in client.invoices.iterate(status="pending"):
    print(i["invoiceid"])
client.invoices.cancel(inv.data["invoiceid"])
```

## Verify webhooks

Moolre signs each callback: `X-Moolre-Signature: t=<unix>,v1=<hex HMAC-SHA256(wallet secret, "<t>.<raw body>")>`. Verify the **raw** body (not re-serialised JSON) and dedupe on `event_id`.

```python
# Flask example
@app.post("/moolre/webhook")
def webhook():
    try:
        event = moolre.construct_event(request.get_data(), request.headers.get("X-Moolre-Signature"),
                                       os.environ["MOOLRE_WALLET_SECRET"])
    except moolre.WebhookSignatureError as e:      # e.reason: malformed | mismatch | timestamp
        return "", 400
    if event.event == "payment.succeeded":
        ...                                        # fulfil once per event.event_id
    return "", 200
```

`moolre.verify_webhook(raw_body, header, secret, tolerance_sec=300)` returns a boolean. The comparison is constant-time and a timestamp further than `tolerance_sec` from now is rejected (`0` disables the time check). `moolre.parse_webhook(raw_body)` returns `event_id`, `event`, `created`, `data`, `notices`, `raw` without verifying.

## Other services

```python
client.sales.airtime(channel="MTN", receiver="233240000000", amount="2.00", external_ref="A-1")
client.sms.send(sender_id="Moolre", messages=[{"recipient": "0241234567", "message": "Hello", "ref": "m-1"}])
client.whatsapp.send(template_name="feedback", language="en",
                     messages=[{"recipient": "233531419000", "ref": "w-1", "placeholders": ["Ama"]}])
client.payment_links.create(amount="50.00", email="shop@example.com", external_ref="LINK-1",
                            currency="GHS", expiration_time=60)
client.webhooks.test()                         # send a signed webhook.test event to your callback URL
client.webhooks.resend("evt_0123456789abcdef01234567")
```

## Development

```bash
python -m unittest discover -s tests          # local mock server + shared webhook vectors
python scripts/build.py                        # dist/: single file, wheel, sdist (stdlib only)
```
