Metadata-Version: 2.5
Name: cmi-python
Version: 1.0.0
Summary: Framework-agnostic CMI payment gateway SDK (Centre Monétique Interbancaire, Morocco) with built-in security for Python
Project-URL: Homepage, https://github.com/cmi-solutions/cmi-python
Project-URL: Issues, https://github.com/cmi-solutions/cmi-python/issues
Project-URL: Changelog, https://github.com/cmi-solutions/cmi-python/blob/main/CHANGELOG.md
Project-URL: Node.js SDK, https://github.com/cmi-solutions/cmi-node
Author: Ishak Zail
License-Expression: MIT
License-File: LICENSE
Keywords: 3d-secure,cmi,django,fastapi,flask,gateway,morocco,payment,payment-processing,secure-payments,starlette
Classifier: Development Status :: 5 - Production/Stable
Classifier: Framework :: Django
Classifier: Framework :: FastAPI
Classifier: Framework :: Flask
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Office/Business :: Financial
Classifier: Typing :: Typed
Requires-Python: >=3.10
Provides-Extra: django
Requires-Dist: django>=4.2; extra == 'django'
Provides-Extra: fastapi
Requires-Dist: starlette>=0.27; extra == 'fastapi'
Provides-Extra: flask
Requires-Dist: flask>=2.3; extra == 'flask'
Description-Content-Type: text/markdown

# cmi-python

**Python SDK for the CMI payment gateway (Centre Monétique Interbancaire, Morocco).**
It signs payment requests, verifies CMI's callbacks and calls CMI's back-office API, with
adapters for Django, Flask and FastAPI/Starlette.

This is the Python port of [cmi-node](https://github.com/cmi-solutions/cmi-node) 2.1: it has the same
kits, the same rules and the same security model, and it produces **byte-identical hashes**. It is
tested against the vectors computed by CMI's reference PHP scripts.

- **Two kits, one package**: the **Standard kit** sends the customer to CMI's payment page; the **API kit** captures, refunds, voids and checks orders from your server.
- **Secure by default**: SHA-512 (`ver3`) hashes, timing-safe verification, secrets masked in `repr()`, logs and pickles, https-only URLs, no redirects followed with API credentials.
- **No runtime dependencies**, fully typed (`py.typed`, `mypy --strict`). Requires **Python 3.10+**.

---

## Contents

- [Installation](#installation)
- [Kits](#kits)
- [Standard kit: payment page](#standard-kit-payment-page)
- [API kit: capture, refund, void, order status](#api-kit-capture-refund-void-order-status)
- [Logging](#logging)
- [Security](#security)
- [Troubleshooting](#troubleshooting)
- [Differences from cmi-node](#differences-from-cmi-node)
- [Development](#development)

---

## Installation

```bash
pip install cmi-python
# with a framework adapter's dependency:
pip install "cmi-python[django]"     # or [flask], [fastapi]
```

| | |
|---|---|
| Python | 3.10 or newer (3.10 to 3.14) |
| Runtime dependencies | None (the HTTP client and the XML reader are the standard library's) |
| Frameworks (optional) | Django 4.2+, Flask 2.3+, FastAPI / Starlette 0.27+ |
| Where it runs | Server code only. It refuses to start in a browser (Pyodide, PyScript) |

## Kits

| Kit | What it does | Import from |
|---|---|---|
| **Standard kit** | Redirects the customer to CMI's payment page with a signed form, then verifies CMI's callback | `cmi` or `cmi.standard` |
| **API kit** | Back-office operations through CMI's XML API: capture, refund, void, order status and history | `cmi` or `cmi.api` |
| **Adapters** | CMI's callback as a Django view, a Flask view or a FastAPI/Starlette endpoint | `cmi.adapters.django`, `.flask`, `.fastapi`, `.starlette` |

---

## Standard kit: payment page

### How a payment works

1. Your server builds the signed payment parameters: `gateway.create_payment_params(...)`.
2. It answers the browser with an auto-submitting form: `gateway.generate_payment_form(params)`.
3. The customer pays on CMI's page (3-D Secure included).
4. CMI posts the result to your **`callback_url`**, server to server. The SDK checks the `HASH`, runs your `validate_order`, and answers CMI (`ACTION=POSTAUTH`, `APPROVED` or `FAILURE`).
5. CMI sends the customer back to your `okUrl` or `failUrl`.

Without a `callback_url`, step 4 does not happen and payments must be confirmed in CMI's back office.

### Configuration

```python
import os
from cmi import CMIPaymentGateway

gateway = CMIPaymentGateway(
    store_key=os.environ["CMI_STORE_KEY"],        # secret: server only
    client_id=os.environ["CMI_CLIENT_ID"],
    gateway_url="https://testpayment.cmi.co.ma/fim/est3Dgate",
    storetype="3d_pay_hosting",
    trantype="PreAuth",
    callback_url="https://api.yoursite.ma/cmi/callback",
    confirmation_mode="auto",                    # "auto" | "manual" (default "manual")
)
```

| Argument | Required | Description |
|---|---|---|
| `store_key` | ✅ | Secret key from CMI. Read it from a server-side environment variable |
| `client_id` | ✅ | Merchant ID from CMI (digits only) |
| `gateway_url` | ✅ | CMI gateway URL. `https://` only (plain `http://` only for localhost) |
| `storetype` | ✅ | `3d_pay_hosting`, `3d`, `pay_hosting`, … (case-insensitive) |
| `trantype` | ✅ | `PreAuth`, `Auth`, … (case-insensitive) |
| `callback_url` | | Where CMI posts the result. `https://` only. Without it, confirm payments in CMI's back office |
| `confirmation_mode` | | `"auto"`: approved payments are captured (`ACTION=POSTAUTH`). `"manual"` (default): they stay pre-authorized (`APPROVED`); capture them later with the [API kit](#api-kit-capture-refund-void-order-status) or the back office |
| `account_type` | | `"inshore"` (default, MAD) or `"offshore"` (foreign processing currency) |

The arguments are keyword-only, so a typo fails at startup. `CMIPaymentGateway.from_dict(settings)` takes the
same settings from a mapping; it accepts cmi-node's spellings too (`storeKey`, `gatewayUrl`…) and rejects
unknown or duplicate keys.

### Django example

```python
# payments/views.py
from django.http import HttpResponse
from cmi.adapters.django import create_django_view
from .cmi import gateway                      # the CMIPaymentGateway above
from .models import Order

def pay(request):
    order = Order.objects.create(amount="150.00")
    params = gateway.create_payment_params(
        oid=str(order.id),
        amount=order.amount,                  # Decimal, str, int or float
        currency="504",                       # MAD
        BillToName="Ishak Zail",
        email="customer@example.com",
        okUrl="https://yoursite.ma/payment/ok",
        failUrl="https://yoursite.ma/payment/fail",
        shopUrl="https://yoursite.ma",
        lang="fr",                            # "fr" | "en" | "ar"
    )
    return HttpResponse(gateway.generate_payment_form(params))

# Runs BEFORE CMI is answered. Return True to accept; anything else (or an exception) answers
# FAILURE, so CMI does not capture. This is your amount check and your replay protection.
def validate_order(result):
    order = Order.objects.filter(pk=result.order_data.order_id).first()
    return order is not None and order.status != "paid" and order.amount == result.order_data.amount

# Runs after CMI has been answered: record the payment (idempotently).
def mark_paid(result):
    Order.objects.filter(pk=result.order_data.order_id).exclude(status="paid").update(
        status="paid", transaction_id=result.order_data.transaction_id
    )

cmi_callback = create_django_view(gateway, validate_order=validate_order, on_success=mark_paid)

# urls.py
#   path("pay", views.pay),
#   path("cmi/callback", views.cmi_callback),   # exactly the path of callback_url (no extra "/")
```

`result.order_data.amount` is an exact `Decimal`: compare it with your `DecimalField` directly.

The view is exempt from CSRF and from `LoginRequiredMiddleware` (CMI's server can neither send your CSRF token
nor log in): the HASH is its protection. Under ASGI it works too (Django runs it in a thread).

### Django REST framework

Mount `create_django_view(...)` in `urls.py` as above. It is a plain Django view, so DRF's
`DEFAULT_AUTHENTICATION_CLASSES`, `DEFAULT_PERMISSION_CLASSES` (`IsAuthenticated`), parsers and throttles do not
apply to it: rate-limit that path at your proxy instead. To start a payment from a JSON API (React, mobile app),
return the signed fields and let the front end post them as a form:

```python
from rest_framework.response import Response
from rest_framework.views import APIView

class StartPaymentView(APIView):
    def post(self, request):
        order = Order.objects.get(pk=request.data["order_id"], user=request.user)
        params = gateway.create_payment_params(oid=str(order.pk), amount=order.amount, currency="504", ...)
        return Response({"action": gateway.gateway_url, "fields": params})   # every value is a string
```

Returning the payment page from a DRF view? Use `HttpResponse(gateway.generate_payment_form(params))`: DRF's
`Response` would send the HTML as a JSON string. If you prefer to handle the callback in your own `APIView`, give it
`authentication_classes = []`, `permission_classes = [AllowAny]` and `parser_classes = [FormParser]`, call
`handler.evaluate(dict(request.data.lists()))`, and answer with an `HttpResponse(answer.body, status=answer.status)`.

### Other frameworks

Every adapter takes the same options (`validate_order`, `on_success`, `on_failure`, …), answers CMI
first, then runs `on_success` / `on_failure` once the answer has been sent.

```python
# Flask
from cmi.adapters.flask import register_flask_callback
register_flask_callback(app, gateway, "/cmi/callback", validate_order=validate_order, on_success=mark_paid)
# With Flask-WTF's CSRFProtect, exempt the view: csrf.exempt(app.view_functions["cmi_callback"])

# FastAPI (hooks may be async def; plain functions run in the thread pool)
from cmi.adapters.fastapi import register_fastapi_callback
register_fastapi_callback(app, gateway, "/cmi/callback", validate_order=validate_order, on_success=mark_paid)

# Starlette
from starlette.routing import Route
from cmi.adapters.starlette import create_starlette_endpoint
routes = [Route("/cmi/callback", create_starlette_endpoint(gateway, on_success=mark_paid), methods=["POST"])]
```

Any other framework: give the posted form fields to a `CallbackHandler` and send its answer yourself.

```python
handler = gateway.create_callback_handler(validate_order=validate_order, on_success=mark_paid)

result, answer = handler.evaluate(form_fields)   # or: await handler.evaluate_async(form_fields)
send_response(answer.status, answer.body)        # answer CMI first...
handler.notify(result)                           # ...then run on_success / on_failure

# Raw body? cmi.parse_form_body(body_bytes) gives the fields.
```

### Callback results

| Callback from CMI | `success` | `verified` | `status` | Answer sent to CMI |
|---|---|---|---|---|
| Authentic, approved (`ProcReturnCode` `00`) | `True` | `True` | `ACTION=POSTAUTH` (auto) or `APPROVED` (manual) | same as `status` |
| Authentic, declined | `False` | `True` | `DECLINED` | `APPROVED` (an acknowledgement, as in CMI's `callback.php`) |
| Approved, but your `validate_order` refused it | `False` | `True` | `FAILURE` | `FAILURE` (CMI does not capture) |
| Missing or wrong `HASH` (forged or altered) | `False` | `False` | `FAILURE` | `FAILURE` |

`on_failure` runs for the last three rows: check `result.verified` to tell a real decline from a forged callback.
`result.order_data` holds `order_id`, `amount` (Decimal), `currency`, `transaction_id`, `return_code`, `response`,
`error_message`, `auth_code`, `masked_pan`, `card_brand` and more. Card and customer fields are left out of its
`repr()`: log the order id, not the whole object.

To verify a callback without a handler: `gateway.verify_callback(fields)` returns the same result.

**Handler options**

| Option | Default | Description |
|---|---|---|
| `validate_order` | — | Runs before CMI is answered, for authentic approved payments. Return `True` to accept; anything else (or an exception) answers `FAILURE`. Check the order exists, is not already paid and has this amount. The SDK warns once when it is missing |
| `on_success` / `on_failure` | — | Your code for approved / other callbacks. Their exceptions are logged and never change CMI's answer |
| `success_response` / `failure_response` / `declined_response` | `ACTION=POSTAUTH` or `APPROVED` / `FAILURE` / `APPROVED` | Override an answer |
| `support_get_method` | `False` | Also read GET query strings. ⚠️ Query strings end up in access logs and caches: enable only if CMI requires it |

Use `handle()` / `evaluate()` / `notify()` from synchronous code and `handle_async()` / `evaluate_async()` /
`notify_async()` from async code. The sync methods refuse `async def` hooks (they answer `FAILURE` and log an
error rather than silently skipping your check).

### Payment request fields

Give them as keyword arguments, as a mapping, or both: `create_payment_params(order_fields, lang="en")`.

| Field | Required | Notes |
|---|---|---|
| `amount` | ✅ | At least 1. More than 2 decimals are rounded half-up to the cent, as CMI does (`"125.6578"` → `125.66`). Prefer `Decimal` or `str` |
| `currency` | ✅ | `"504"` or `"MAD"` |
| `BillToName` | ✅ | Up to 255 characters |
| `email` | ✅ | Up to 64 characters |
| `okUrl`, `failUrl`, `shopUrl` | ✅ | Where CMI sends the customer back (http(s) or a mobile deeplink) |
| `oid` | | Your order ID, up to 64 characters (generated if omitted) |
| `lang` | | `fr` (default), `en`, `ar` |
| `tel`, `description` | | Up to 32 and 125 characters |
| `rnd` | | Random value, up to 20 characters (generated if omitted) |
| `AutoRedirect`, `redirectGet`, `sessiontimeout`, `CallbackResponse` | | Redirect without the receipt page, return with GET instead of POST, page timeout in seconds (30–2700, default 1800), `False` turns the callback off for this payment |
| `amountCur` + `symbolCur` | | Show the amount in another currency (inshore only), e.g. `symbolCur="840"` |
| `BillToCompany`, `BillToStreet1..3`, `BillToCity`, `BillToStateProv`, `BillToPostalCode`, `BillToCountry`, `BillToTelVoice` | | Billing address |
| `id1`, `itemnumber1`, `productcode1`, `qty1`, `desc1`, `price1`, `total1`, … | | Order lines (numbered) |

Other fields are passed to CMI as they are, field names are case-insensitive, and `None` means "not given".
`create_payment_params()` returns exactly what is posted, every value as text (`True` becomes `"true"`, as CMI
expects). Like CMI's PHP script, the SDK removes accents and other characters from `BillToName`, `BillToCompany`,
`BillToStreet1`, `BillToCity`, `BillToStateProv`, `BillToPostalCode` and `BillToCountry` (`Zoé` → `Zoe`; Arabic
letters are dropped), so a `BillToName` written only in Arabic is refused. Invalid input raises
`cmi.CMIValidationError` (a `ValueError`).

**Strict CSP?** `generate_payment_form(params, nonce=nonce)` adds your nonce to its inline style and script, or
build your own form from `gateway.generate_payment_inputs(params)` (escaped hidden inputs).

---

## API kit: capture, refund, void, order status

`CMIApiClient` calls CMI's XML API from your server, after the payment page:

| Method | CMI operation | Use it to |
|---|---|---|
| `post_auth(order_id, amount=None)` | PostAuth | Capture a pre-authorized order, fully or partly |
| `refund(order_id, amount=None, currency=None)` | Credit | Refund a captured order: fully (no amount) or partly (several partial refunds allowed) |
| `void(order_id)` | Void | Cancel a pre-authorization, capture, sale or refund |
| `order_status(order_id)` | ORDERSTATUS | Check an order, e.g. when CMI's callback never arrived |
| `order_history(order_id)` | ORDERHISTORY | List every transaction of an order |

It uses an **API user** (name and password created for API access in CMI's back office) and the API URL, both
given by CMI, not the `store_key`.

```python
import os
from cmi import CMIApiClient, CMIApiError

api = CMIApiClient(
    api_url=os.environ["CMI_API_URL"],          # https:// only (http for localhost)
    client_id=os.environ["CMI_CLIENT_ID"],
    username=os.environ["CMI_API_USER"],
    password=os.environ["CMI_API_PASSWORD"],    # secret: server only
    timeout=30,                                 # seconds, optional
)

# confirmation_mode "manual" leaves payments pre-authorized: capture when you ship
capture = api.post_auth("ORDER-123")
if not capture.approved:
    log.warning("Capture refused: %s %s", capture.proc_return_code, capture.message)

api.refund("ORDER-123", amount="50.00")          # partial refund (currency defaults to MAD)
api.refund("ORDER-124")                          # full refund

status = api.order_status("ORDER-123")
if status.found and status.transaction and status.transaction.shipment_possible:
    ...  # captured or settled: safe to ship
```

In async code, `AsyncCMIApiClient` takes the same settings and has the same methods, as coroutines (each call
runs in a worker thread, so the event loop is never blocked).

**Results.** A refused operation is a result, not an exception: `approved` is `False`, and `response`
(`Declined` / `Error`), `proc_return_code` (`00` approved, `99` gateway error, other values are bank codes),
`message` and `error_code` say why. `fields` and `extra` hold CMI's whole answer.

**Order statuses.** `order_status()` returns the order's last successful transaction (or its last failed one),
with amounts converted from cents to `Decimal`. `order_history()` returns the same details for every transaction.

| `status` | CMI code | Can ship? | `transient` (query again later) |
|---|---|---|---|
| `preauthorized` | A | no | no |
| `captured` / `settled` | C / S | **yes** | no |
| `refunded` | C or S on a refund line | no | no |
| `voided` / `declined` | V / D | no | no |
| `pending` / `reversal_required` / `processing` | PN / R / NW | no | **yes** |
| `error` / `cancelled` | ERR / CNCL | no | no (recurring orders) |

**Errors.** `CMIApiError` means no usable answer came back: `code` is `TIMEOUT`, `NETWORK`, `HTTP_STATUS` or
`INVALID_RESPONSE`. The client never retries by itself. Wrong settings (an `http://` URL, a missing or too long
value, a control character in the credentials, a currency without an amount) raise `CMIValidationError` before
anything is sent.

> **After any `CMIApiError` on a capture, refund or void, check before retrying.** The request may have reached
> CMI even though the answer was lost. Call `order_status()` (or `order_history()` for refunds) first, or the
> money may move twice.

**Your own HTTP client.** The default transport is `urllib` (certificates verified, redirects refused, answers
over 1 MB rejected). To use a proxy or another client, pass `http_post=`: a function
`(url, body, headers, timeout) -> cmi.HttpResponse` that must not follow redirects.

---

## Logging

The SDK logs through the standard `logging` module, under the `"cmi"` logger, and adds a `NullHandler` like
every library: configure it in your application. It never logs secrets, the hash input or customer data.

```python
import logging
logging.getLogger("cmi").setLevel(logging.WARNING)   # warnings: missing validate_order, short store key...
```

---

## Security

- **Keep secrets on the server.** The `store_key` signs every payment and callback: whoever has it can forge a "paid" callback. The API password can capture and refund. Read both from server-side environment variables or a secret manager, never commit them.
- **The SDK never outputs them.** They are kept in a `SecretString`, masked in `repr()`, `str()` and f-strings, never logged, and the gateway and API clients refuse to be pickled (so they never land in a cache). The API request body is never chained to exceptions, so error reporters do not capture it. Python has no truly private attributes: this protects against accidents, not against code that digs for the key on purpose. If a real key was ever committed, change it in CMI's back office.
- **Use a long random store key.** CMI's `ver3` hash is unsalted, so a short key can be guessed from one payment form. The SDK warns below 16 characters.
- **Callbacks are verified** with a timing-safe SHA-512 comparison. A valid callback can still be **replayed**: do the order, amount and "not already paid" checks in `validate_order`, and make your update idempotent (`UPDATE orders SET status = 'paid' WHERE id = %s AND status <> 'paid'`).
- **API calls** use https only, refuse redirects (so credentials are never resent elsewhere) and reject answers over 1 MB; CMI's XML answers are read by a small parser that refuses `DOCTYPE` and entity declarations (no XXE, no "billion laughs").
- **Rate-limit** your callback endpoint. The Starlette/FastAPI adapter refuses bodies over 100 KB (`max_body_size`).

---

## Troubleshooting

| Problem | Fix |
|---|---|
| `Hash verification failed` on callbacks | Use the exact store key of that CMI environment (test or production), and give the verifier the posted form fields as received |
| CMI shows "3D-1004 Code de sécurité erroné" | The `store_key` does not match the `client_id` (wrong key, or a key with extra characters) |
| The callback never reaches you in development | CMI cannot call `localhost`: use a tunnel such as `ngrok http 8000` and its https URL as `callback_url` |
| Django answers 403 or 302 to CMI | The adapter's view is exempt from CSRF and `LoginRequiredMiddleware`; make sure no other middleware or decorator wraps it again |
| Django answers 301 to CMI | `callback_url` and the route differ by a trailing slash (`APPEND_SLASH`): CMI does not follow redirects, so make them identical |
| `Amount must be greater than or equal to 1` | CMI requires at least 1 (MAD) |
| Approved callbacks answer `FAILURE` | Your `validate_order` did not return `True` (or raised). With an `async def validate_order`, use the FastAPI adapter or `handle_async()` |
| API `TIMEOUT` / `NETWORK` on a capture or refund | Call `order_status()` before trying again |

---

## Differences from cmi-node

The protocol behaviour (hashes, answers, validation rules, rounding) is the same. The API is Pythonic:

| cmi-node | cmi-python |
|---|---|
| `new CMIPaymentGateway({ storeKey, clientId, ... })` | `CMIPaymentGateway(store_key=..., client_id=..., ...)` (or `.from_dict()`) |
| `createPaymentParams()`, `generatePaymentForm(params, { nonce })` | `create_payment_params()`, `generate_payment_form(params, nonce=...)` |
| `result.orderData.orderId`, `amount: number` | `result.order_data.order_id`, `amount: Decimal` |
| `validateOrder`, `onSuccess`, `onFailure` | `validate_order`, `on_success`, `on_failure` |
| `api.postAuth({ orderId, amount })`, `timeoutMs` | `api.post_auth(order_id, amount)`, `timeout` (seconds) |
| `configureLogger(...)` | the standard `logging` module (`"cmi"` logger) |
| Express, Fastify, Hono, Next.js, NestJS adapters | Django, Flask, FastAPI/Starlette adapters |
| `Error` on invalid input | `CMIValidationError` (a `ValueError`) |

---

## Development

```bash
python -m venv .venv && . .venv/bin/activate      # Windows: .venv\Scripts\activate
pip install -e . pytest ruff mypy django flask fastapi httpx
pytest                       # unit, PHP-parity, transport and adapter tests
ruff check src tests && ruff format --check src tests
mypy                         # strict
```

`tests/fixtures/php_parity.json` holds hashes computed by CMI's reference PHP scripts (the same vectors as
cmi-node): never edit them by hand.

### Releasing

`.github/workflows/publish.yml` publishes on PyPI with
[Trusted Publishing](https://docs.pypi.org/trusted-publishers/) (no token stored in the repository).

1. One-time: on pypi.org (and test.pypi.org), *Account → Publishing → Add a pending publisher*: project
   `cmi-python`, owner `cmi-solutions`, repository `cmi-python`, workflow `publish.yml`, environment `pypi`
   (`testpypi` on TestPyPI).
2. Optional dry run: *Actions → Publish to PyPI → Run workflow* publishes the current version on TestPyPI.
3. Set the version in `pyproject.toml` and `src/cmi/__init__.py`, add it to `CHANGELOG.md`, then tag and push:
   `git tag v1.0.0 && git push origin v1.0.0`. The workflow checks that the tag matches the version, runs the
   lint, type check and tests, builds, and publishes.

PyPI never accepts the same version twice: bump the version for every new upload, TestPyPI included.

## License

[MIT](./LICENSE)
