cmi-python 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. cmi_python-1.0.0/.gitignore +13 -0
  2. cmi_python-1.0.0/CHANGELOG.md +36 -0
  3. cmi_python-1.0.0/LICENSE +21 -0
  4. cmi_python-1.0.0/PKG-INFO +461 -0
  5. cmi_python-1.0.0/README.md +424 -0
  6. cmi_python-1.0.0/pyproject.toml +118 -0
  7. cmi_python-1.0.0/src/cmi/__init__.py +92 -0
  8. cmi_python-1.0.0/src/cmi/_amount.py +58 -0
  9. cmi_python-1.0.0/src/cmi/_cc5/__init__.py +19 -0
  10. cmi_python-1.0.0/src/cmi/_cc5/transport.py +255 -0
  11. cmi_python-1.0.0/src/cmi/_cc5/xml.py +211 -0
  12. cmi_python-1.0.0/src/cmi/_compat.py +125 -0
  13. cmi_python-1.0.0/src/cmi/_log.py +16 -0
  14. cmi_python-1.0.0/src/cmi/_php.py +169 -0
  15. cmi_python-1.0.0/src/cmi/_security.py +88 -0
  16. cmi_python-1.0.0/src/cmi/_validation.py +89 -0
  17. cmi_python-1.0.0/src/cmi/adapters/__init__.py +27 -0
  18. cmi_python-1.0.0/src/cmi/adapters/django.py +97 -0
  19. cmi_python-1.0.0/src/cmi/adapters/fastapi.py +15 -0
  20. cmi_python-1.0.0/src/cmi/adapters/flask.py +74 -0
  21. cmi_python-1.0.0/src/cmi/adapters/starlette.py +121 -0
  22. cmi_python-1.0.0/src/cmi/api/__init__.py +35 -0
  23. cmi_python-1.0.0/src/cmi/api/_order_status.py +192 -0
  24. cmi_python-1.0.0/src/cmi/api/client.py +242 -0
  25. cmi_python-1.0.0/src/cmi/api/types.py +144 -0
  26. cmi_python-1.0.0/src/cmi/constants.py +146 -0
  27. cmi_python-1.0.0/src/cmi/errors.py +52 -0
  28. cmi_python-1.0.0/src/cmi/py.typed +0 -0
  29. cmi_python-1.0.0/src/cmi/standard/__init__.py +20 -0
  30. cmi_python-1.0.0/src/cmi/standard/_builder.py +191 -0
  31. cmi_python-1.0.0/src/cmi/standard/_form.py +235 -0
  32. cmi_python-1.0.0/src/cmi/standard/_hash.py +53 -0
  33. cmi_python-1.0.0/src/cmi/standard/_sanitize.py +77 -0
  34. cmi_python-1.0.0/src/cmi/standard/_validators.py +389 -0
  35. cmi_python-1.0.0/src/cmi/standard/callback.py +417 -0
  36. cmi_python-1.0.0/src/cmi/standard/gateway.py +216 -0
  37. cmi_python-1.0.0/tests/__init__.py +0 -0
  38. cmi_python-1.0.0/tests/conftest.py +58 -0
  39. cmi_python-1.0.0/tests/fixtures/php_parity.json +576 -0
  40. cmi_python-1.0.0/tests/test_adapters.py +248 -0
  41. cmi_python-1.0.0/tests/test_api_client.py +608 -0
  42. cmi_python-1.0.0/tests/test_callback.py +254 -0
  43. cmi_python-1.0.0/tests/test_gateway.py +470 -0
  44. cmi_python-1.0.0/tests/test_helpers.py +159 -0
  45. cmi_python-1.0.0/tests/test_php_parity.py +169 -0
  46. cmi_python-1.0.0/tests/test_xml.py +73 -0
@@ -0,0 +1,13 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ venv/
5
+ build/
6
+ dist/
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ .mypy_cache/
10
+ .ruff_cache/
11
+ .coverage
12
+ htmlcov/
13
+ .env
@@ -0,0 +1,36 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [1.0.0] - 2026-11-24
9
+
10
+ First release: the Python port of [cmi-node](https://github.com/cmi-solutions/cmi-node) 2.1.0.
11
+
12
+ ### Added
13
+ - **Standard kit** (`cmi.standard`): `CMIPaymentGateway` with `create_payment_params()`,
14
+ `generate_payment_form()` (CSP nonce support), `generate_payment_inputs()` and `verify_callback()`;
15
+ `CallbackHandler` with `validate_order` (run before CMI is answered), `on_success` / `on_failure`,
16
+ custom answers, and sync (`handle`, `evaluate`, `notify`) and async (`handle_async`,
17
+ `evaluate_async`, `notify_async`) methods; `parse_form_body()` for raw callback bodies.
18
+ - Byte-identical `ver3` hashes with CMI's reference PHP scripts and with cmi-node: `natcasesort()`
19
+ field order, `str_without_accents()` billing cleaning, PHP `trim()`, `html_entity_decode()` and the
20
+ trailing-newline rule on callbacks, the "document" anti-XSS rule, half-up rounding to the cent.
21
+ Tested against the PHP-computed vectors used by cmi-node.
22
+ - **API kit** (`cmi.api`): `CMIApiClient` and `AsyncCMIApiClient` for CMI's back-office XML API (CC5):
23
+ `post_auth()`, `refund()`, `void()`, `order_status()` and `order_history()`. https only, redirects
24
+ refused, answers over 1 MB rejected, no automatic retry, pluggable `http_post` transport. CMI's XML is
25
+ read by a single-pass parser that refuses DOCTYPE and entity declarations.
26
+ - **Adapters** (`cmi.adapters`): Django (`create_django_view`, exempt from CSRF and from Django 5.1's
27
+ `LoginRequiredMiddleware`, usable as is in Django REST framework projects), Flask
28
+ (`create_flask_view`, `register_flask_callback`) and FastAPI/Starlette (`create_starlette_endpoint`,
29
+ `register_fastapi_callback`, 100 KB body limit). Each answers CMI first, then runs the hooks.
30
+ - Secrets kept in `SecretString` (masked in `repr`/`str`/f-strings, not picklable); the gateway and the
31
+ API clients refuse to be pickled; the API request body is never chained to exceptions.
32
+ - Amounts as exact `Decimal` in callback results and order statuses; `CMIValidationError` (a
33
+ `ValueError`) for invalid settings and requests; logging through the standard `"cmi"` logger.
34
+ - No runtime dependencies, fully typed (`py.typed`, `mypy --strict`), Python 3.10+.
35
+
36
+ [1.0.0]: https://github.com/cmi-solutions/cmi-python/releases/tag/v1.0.0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ishak Zail
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,461 @@
1
+ Metadata-Version: 2.5
2
+ Name: cmi-python
3
+ Version: 1.0.0
4
+ Summary: Framework-agnostic CMI payment gateway SDK (Centre Monétique Interbancaire, Morocco) with built-in security for Python
5
+ Project-URL: Homepage, https://github.com/cmi-solutions/cmi-python
6
+ Project-URL: Issues, https://github.com/cmi-solutions/cmi-python/issues
7
+ Project-URL: Changelog, https://github.com/cmi-solutions/cmi-python/blob/main/CHANGELOG.md
8
+ Project-URL: Node.js SDK, https://github.com/cmi-solutions/cmi-node
9
+ Author: Ishak Zail
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: 3d-secure,cmi,django,fastapi,flask,gateway,morocco,payment,payment-processing,secure-payments,starlette
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Framework :: Django
15
+ Classifier: Framework :: FastAPI
16
+ Classifier: Framework :: Flask
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Programming Language :: Python :: 3.14
26
+ Classifier: Topic :: Internet :: WWW/HTTP
27
+ Classifier: Topic :: Office/Business :: Financial
28
+ Classifier: Typing :: Typed
29
+ Requires-Python: >=3.10
30
+ Provides-Extra: django
31
+ Requires-Dist: django>=4.2; extra == 'django'
32
+ Provides-Extra: fastapi
33
+ Requires-Dist: starlette>=0.27; extra == 'fastapi'
34
+ Provides-Extra: flask
35
+ Requires-Dist: flask>=2.3; extra == 'flask'
36
+ Description-Content-Type: text/markdown
37
+
38
+ # cmi-python
39
+
40
+ **Python SDK for the CMI payment gateway (Centre Monétique Interbancaire, Morocco).**
41
+ It signs payment requests, verifies CMI's callbacks and calls CMI's back-office API, with
42
+ adapters for Django, Flask and FastAPI/Starlette.
43
+
44
+ This is the Python port of [cmi-node](https://github.com/cmi-solutions/cmi-node) 2.1: it has the same
45
+ kits, the same rules and the same security model, and it produces **byte-identical hashes**. It is
46
+ tested against the vectors computed by CMI's reference PHP scripts.
47
+
48
+ - **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.
49
+ - **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.
50
+ - **No runtime dependencies**, fully typed (`py.typed`, `mypy --strict`). Requires **Python 3.10+**.
51
+
52
+ ---
53
+
54
+ ## Contents
55
+
56
+ - [Installation](#installation)
57
+ - [Kits](#kits)
58
+ - [Standard kit: payment page](#standard-kit-payment-page)
59
+ - [API kit: capture, refund, void, order status](#api-kit-capture-refund-void-order-status)
60
+ - [Logging](#logging)
61
+ - [Security](#security)
62
+ - [Troubleshooting](#troubleshooting)
63
+ - [Differences from cmi-node](#differences-from-cmi-node)
64
+ - [Development](#development)
65
+
66
+ ---
67
+
68
+ ## Installation
69
+
70
+ ```bash
71
+ pip install cmi-python
72
+ # with a framework adapter's dependency:
73
+ pip install "cmi-python[django]" # or [flask], [fastapi]
74
+ ```
75
+
76
+ | | |
77
+ |---|---|
78
+ | Python | 3.10 or newer (3.10 to 3.14) |
79
+ | Runtime dependencies | None (the HTTP client and the XML reader are the standard library's) |
80
+ | Frameworks (optional) | Django 4.2+, Flask 2.3+, FastAPI / Starlette 0.27+ |
81
+ | Where it runs | Server code only. It refuses to start in a browser (Pyodide, PyScript) |
82
+
83
+ ## Kits
84
+
85
+ | Kit | What it does | Import from |
86
+ |---|---|---|
87
+ | **Standard kit** | Redirects the customer to CMI's payment page with a signed form, then verifies CMI's callback | `cmi` or `cmi.standard` |
88
+ | **API kit** | Back-office operations through CMI's XML API: capture, refund, void, order status and history | `cmi` or `cmi.api` |
89
+ | **Adapters** | CMI's callback as a Django view, a Flask view or a FastAPI/Starlette endpoint | `cmi.adapters.django`, `.flask`, `.fastapi`, `.starlette` |
90
+
91
+ ---
92
+
93
+ ## Standard kit: payment page
94
+
95
+ ### How a payment works
96
+
97
+ 1. Your server builds the signed payment parameters: `gateway.create_payment_params(...)`.
98
+ 2. It answers the browser with an auto-submitting form: `gateway.generate_payment_form(params)`.
99
+ 3. The customer pays on CMI's page (3-D Secure included).
100
+ 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`).
101
+ 5. CMI sends the customer back to your `okUrl` or `failUrl`.
102
+
103
+ Without a `callback_url`, step 4 does not happen and payments must be confirmed in CMI's back office.
104
+
105
+ ### Configuration
106
+
107
+ ```python
108
+ import os
109
+ from cmi import CMIPaymentGateway
110
+
111
+ gateway = CMIPaymentGateway(
112
+ store_key=os.environ["CMI_STORE_KEY"], # secret: server only
113
+ client_id=os.environ["CMI_CLIENT_ID"],
114
+ gateway_url="https://testpayment.cmi.co.ma/fim/est3Dgate",
115
+ storetype="3d_pay_hosting",
116
+ trantype="PreAuth",
117
+ callback_url="https://api.yoursite.ma/cmi/callback",
118
+ confirmation_mode="auto", # "auto" | "manual" (default "manual")
119
+ )
120
+ ```
121
+
122
+ | Argument | Required | Description |
123
+ |---|---|---|
124
+ | `store_key` | ✅ | Secret key from CMI. Read it from a server-side environment variable |
125
+ | `client_id` | ✅ | Merchant ID from CMI (digits only) |
126
+ | `gateway_url` | ✅ | CMI gateway URL. `https://` only (plain `http://` only for localhost) |
127
+ | `storetype` | ✅ | `3d_pay_hosting`, `3d`, `pay_hosting`, … (case-insensitive) |
128
+ | `trantype` | ✅ | `PreAuth`, `Auth`, … (case-insensitive) |
129
+ | `callback_url` | | Where CMI posts the result. `https://` only. Without it, confirm payments in CMI's back office |
130
+ | `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 |
131
+ | `account_type` | | `"inshore"` (default, MAD) or `"offshore"` (foreign processing currency) |
132
+
133
+ The arguments are keyword-only, so a typo fails at startup. `CMIPaymentGateway.from_dict(settings)` takes the
134
+ same settings from a mapping; it accepts cmi-node's spellings too (`storeKey`, `gatewayUrl`…) and rejects
135
+ unknown or duplicate keys.
136
+
137
+ ### Django example
138
+
139
+ ```python
140
+ # payments/views.py
141
+ from django.http import HttpResponse
142
+ from cmi.adapters.django import create_django_view
143
+ from .cmi import gateway # the CMIPaymentGateway above
144
+ from .models import Order
145
+
146
+ def pay(request):
147
+ order = Order.objects.create(amount="150.00")
148
+ params = gateway.create_payment_params(
149
+ oid=str(order.id),
150
+ amount=order.amount, # Decimal, str, int or float
151
+ currency="504", # MAD
152
+ BillToName="Ishak Zail",
153
+ email="customer@example.com",
154
+ okUrl="https://yoursite.ma/payment/ok",
155
+ failUrl="https://yoursite.ma/payment/fail",
156
+ shopUrl="https://yoursite.ma",
157
+ lang="fr", # "fr" | "en" | "ar"
158
+ )
159
+ return HttpResponse(gateway.generate_payment_form(params))
160
+
161
+ # Runs BEFORE CMI is answered. Return True to accept; anything else (or an exception) answers
162
+ # FAILURE, so CMI does not capture. This is your amount check and your replay protection.
163
+ def validate_order(result):
164
+ order = Order.objects.filter(pk=result.order_data.order_id).first()
165
+ return order is not None and order.status != "paid" and order.amount == result.order_data.amount
166
+
167
+ # Runs after CMI has been answered: record the payment (idempotently).
168
+ def mark_paid(result):
169
+ Order.objects.filter(pk=result.order_data.order_id).exclude(status="paid").update(
170
+ status="paid", transaction_id=result.order_data.transaction_id
171
+ )
172
+
173
+ cmi_callback = create_django_view(gateway, validate_order=validate_order, on_success=mark_paid)
174
+
175
+ # urls.py
176
+ # path("pay", views.pay),
177
+ # path("cmi/callback", views.cmi_callback), # exactly the path of callback_url (no extra "/")
178
+ ```
179
+
180
+ `result.order_data.amount` is an exact `Decimal`: compare it with your `DecimalField` directly.
181
+
182
+ The view is exempt from CSRF and from `LoginRequiredMiddleware` (CMI's server can neither send your CSRF token
183
+ nor log in): the HASH is its protection. Under ASGI it works too (Django runs it in a thread).
184
+
185
+ ### Django REST framework
186
+
187
+ Mount `create_django_view(...)` in `urls.py` as above. It is a plain Django view, so DRF's
188
+ `DEFAULT_AUTHENTICATION_CLASSES`, `DEFAULT_PERMISSION_CLASSES` (`IsAuthenticated`), parsers and throttles do not
189
+ apply to it: rate-limit that path at your proxy instead. To start a payment from a JSON API (React, mobile app),
190
+ return the signed fields and let the front end post them as a form:
191
+
192
+ ```python
193
+ from rest_framework.response import Response
194
+ from rest_framework.views import APIView
195
+
196
+ class StartPaymentView(APIView):
197
+ def post(self, request):
198
+ order = Order.objects.get(pk=request.data["order_id"], user=request.user)
199
+ params = gateway.create_payment_params(oid=str(order.pk), amount=order.amount, currency="504", ...)
200
+ return Response({"action": gateway.gateway_url, "fields": params}) # every value is a string
201
+ ```
202
+
203
+ Returning the payment page from a DRF view? Use `HttpResponse(gateway.generate_payment_form(params))`: DRF's
204
+ `Response` would send the HTML as a JSON string. If you prefer to handle the callback in your own `APIView`, give it
205
+ `authentication_classes = []`, `permission_classes = [AllowAny]` and `parser_classes = [FormParser]`, call
206
+ `handler.evaluate(dict(request.data.lists()))`, and answer with an `HttpResponse(answer.body, status=answer.status)`.
207
+
208
+ ### Other frameworks
209
+
210
+ Every adapter takes the same options (`validate_order`, `on_success`, `on_failure`, …), answers CMI
211
+ first, then runs `on_success` / `on_failure` once the answer has been sent.
212
+
213
+ ```python
214
+ # Flask
215
+ from cmi.adapters.flask import register_flask_callback
216
+ register_flask_callback(app, gateway, "/cmi/callback", validate_order=validate_order, on_success=mark_paid)
217
+ # With Flask-WTF's CSRFProtect, exempt the view: csrf.exempt(app.view_functions["cmi_callback"])
218
+
219
+ # FastAPI (hooks may be async def; plain functions run in the thread pool)
220
+ from cmi.adapters.fastapi import register_fastapi_callback
221
+ register_fastapi_callback(app, gateway, "/cmi/callback", validate_order=validate_order, on_success=mark_paid)
222
+
223
+ # Starlette
224
+ from starlette.routing import Route
225
+ from cmi.adapters.starlette import create_starlette_endpoint
226
+ routes = [Route("/cmi/callback", create_starlette_endpoint(gateway, on_success=mark_paid), methods=["POST"])]
227
+ ```
228
+
229
+ Any other framework: give the posted form fields to a `CallbackHandler` and send its answer yourself.
230
+
231
+ ```python
232
+ handler = gateway.create_callback_handler(validate_order=validate_order, on_success=mark_paid)
233
+
234
+ result, answer = handler.evaluate(form_fields) # or: await handler.evaluate_async(form_fields)
235
+ send_response(answer.status, answer.body) # answer CMI first...
236
+ handler.notify(result) # ...then run on_success / on_failure
237
+
238
+ # Raw body? cmi.parse_form_body(body_bytes) gives the fields.
239
+ ```
240
+
241
+ ### Callback results
242
+
243
+ | Callback from CMI | `success` | `verified` | `status` | Answer sent to CMI |
244
+ |---|---|---|---|---|
245
+ | Authentic, approved (`ProcReturnCode` `00`) | `True` | `True` | `ACTION=POSTAUTH` (auto) or `APPROVED` (manual) | same as `status` |
246
+ | Authentic, declined | `False` | `True` | `DECLINED` | `APPROVED` (an acknowledgement, as in CMI's `callback.php`) |
247
+ | Approved, but your `validate_order` refused it | `False` | `True` | `FAILURE` | `FAILURE` (CMI does not capture) |
248
+ | Missing or wrong `HASH` (forged or altered) | `False` | `False` | `FAILURE` | `FAILURE` |
249
+
250
+ `on_failure` runs for the last three rows: check `result.verified` to tell a real decline from a forged callback.
251
+ `result.order_data` holds `order_id`, `amount` (Decimal), `currency`, `transaction_id`, `return_code`, `response`,
252
+ `error_message`, `auth_code`, `masked_pan`, `card_brand` and more. Card and customer fields are left out of its
253
+ `repr()`: log the order id, not the whole object.
254
+
255
+ To verify a callback without a handler: `gateway.verify_callback(fields)` returns the same result.
256
+
257
+ **Handler options**
258
+
259
+ | Option | Default | Description |
260
+ |---|---|---|
261
+ | `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 |
262
+ | `on_success` / `on_failure` | — | Your code for approved / other callbacks. Their exceptions are logged and never change CMI's answer |
263
+ | `success_response` / `failure_response` / `declined_response` | `ACTION=POSTAUTH` or `APPROVED` / `FAILURE` / `APPROVED` | Override an answer |
264
+ | `support_get_method` | `False` | Also read GET query strings. ⚠️ Query strings end up in access logs and caches: enable only if CMI requires it |
265
+
266
+ Use `handle()` / `evaluate()` / `notify()` from synchronous code and `handle_async()` / `evaluate_async()` /
267
+ `notify_async()` from async code. The sync methods refuse `async def` hooks (they answer `FAILURE` and log an
268
+ error rather than silently skipping your check).
269
+
270
+ ### Payment request fields
271
+
272
+ Give them as keyword arguments, as a mapping, or both: `create_payment_params(order_fields, lang="en")`.
273
+
274
+ | Field | Required | Notes |
275
+ |---|---|---|
276
+ | `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` |
277
+ | `currency` | ✅ | `"504"` or `"MAD"` |
278
+ | `BillToName` | ✅ | Up to 255 characters |
279
+ | `email` | ✅ | Up to 64 characters |
280
+ | `okUrl`, `failUrl`, `shopUrl` | ✅ | Where CMI sends the customer back (http(s) or a mobile deeplink) |
281
+ | `oid` | | Your order ID, up to 64 characters (generated if omitted) |
282
+ | `lang` | | `fr` (default), `en`, `ar` |
283
+ | `tel`, `description` | | Up to 32 and 125 characters |
284
+ | `rnd` | | Random value, up to 20 characters (generated if omitted) |
285
+ | `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 |
286
+ | `amountCur` + `symbolCur` | | Show the amount in another currency (inshore only), e.g. `symbolCur="840"` |
287
+ | `BillToCompany`, `BillToStreet1..3`, `BillToCity`, `BillToStateProv`, `BillToPostalCode`, `BillToCountry`, `BillToTelVoice` | | Billing address |
288
+ | `id1`, `itemnumber1`, `productcode1`, `qty1`, `desc1`, `price1`, `total1`, … | | Order lines (numbered) |
289
+
290
+ Other fields are passed to CMI as they are, field names are case-insensitive, and `None` means "not given".
291
+ `create_payment_params()` returns exactly what is posted, every value as text (`True` becomes `"true"`, as CMI
292
+ expects). Like CMI's PHP script, the SDK removes accents and other characters from `BillToName`, `BillToCompany`,
293
+ `BillToStreet1`, `BillToCity`, `BillToStateProv`, `BillToPostalCode` and `BillToCountry` (`Zoé` → `Zoe`; Arabic
294
+ letters are dropped), so a `BillToName` written only in Arabic is refused. Invalid input raises
295
+ `cmi.CMIValidationError` (a `ValueError`).
296
+
297
+ **Strict CSP?** `generate_payment_form(params, nonce=nonce)` adds your nonce to its inline style and script, or
298
+ build your own form from `gateway.generate_payment_inputs(params)` (escaped hidden inputs).
299
+
300
+ ---
301
+
302
+ ## API kit: capture, refund, void, order status
303
+
304
+ `CMIApiClient` calls CMI's XML API from your server, after the payment page:
305
+
306
+ | Method | CMI operation | Use it to |
307
+ |---|---|---|
308
+ | `post_auth(order_id, amount=None)` | PostAuth | Capture a pre-authorized order, fully or partly |
309
+ | `refund(order_id, amount=None, currency=None)` | Credit | Refund a captured order: fully (no amount) or partly (several partial refunds allowed) |
310
+ | `void(order_id)` | Void | Cancel a pre-authorization, capture, sale or refund |
311
+ | `order_status(order_id)` | ORDERSTATUS | Check an order, e.g. when CMI's callback never arrived |
312
+ | `order_history(order_id)` | ORDERHISTORY | List every transaction of an order |
313
+
314
+ It uses an **API user** (name and password created for API access in CMI's back office) and the API URL, both
315
+ given by CMI, not the `store_key`.
316
+
317
+ ```python
318
+ import os
319
+ from cmi import CMIApiClient, CMIApiError
320
+
321
+ api = CMIApiClient(
322
+ api_url=os.environ["CMI_API_URL"], # https:// only (http for localhost)
323
+ client_id=os.environ["CMI_CLIENT_ID"],
324
+ username=os.environ["CMI_API_USER"],
325
+ password=os.environ["CMI_API_PASSWORD"], # secret: server only
326
+ timeout=30, # seconds, optional
327
+ )
328
+
329
+ # confirmation_mode "manual" leaves payments pre-authorized: capture when you ship
330
+ capture = api.post_auth("ORDER-123")
331
+ if not capture.approved:
332
+ log.warning("Capture refused: %s %s", capture.proc_return_code, capture.message)
333
+
334
+ api.refund("ORDER-123", amount="50.00") # partial refund (currency defaults to MAD)
335
+ api.refund("ORDER-124") # full refund
336
+
337
+ status = api.order_status("ORDER-123")
338
+ if status.found and status.transaction and status.transaction.shipment_possible:
339
+ ... # captured or settled: safe to ship
340
+ ```
341
+
342
+ In async code, `AsyncCMIApiClient` takes the same settings and has the same methods, as coroutines (each call
343
+ runs in a worker thread, so the event loop is never blocked).
344
+
345
+ **Results.** A refused operation is a result, not an exception: `approved` is `False`, and `response`
346
+ (`Declined` / `Error`), `proc_return_code` (`00` approved, `99` gateway error, other values are bank codes),
347
+ `message` and `error_code` say why. `fields` and `extra` hold CMI's whole answer.
348
+
349
+ **Order statuses.** `order_status()` returns the order's last successful transaction (or its last failed one),
350
+ with amounts converted from cents to `Decimal`. `order_history()` returns the same details for every transaction.
351
+
352
+ | `status` | CMI code | Can ship? | `transient` (query again later) |
353
+ |---|---|---|---|
354
+ | `preauthorized` | A | no | no |
355
+ | `captured` / `settled` | C / S | **yes** | no |
356
+ | `refunded` | C or S on a refund line | no | no |
357
+ | `voided` / `declined` | V / D | no | no |
358
+ | `pending` / `reversal_required` / `processing` | PN / R / NW | no | **yes** |
359
+ | `error` / `cancelled` | ERR / CNCL | no | no (recurring orders) |
360
+
361
+ **Errors.** `CMIApiError` means no usable answer came back: `code` is `TIMEOUT`, `NETWORK`, `HTTP_STATUS` or
362
+ `INVALID_RESPONSE`. The client never retries by itself. Wrong settings (an `http://` URL, a missing or too long
363
+ value, a control character in the credentials, a currency without an amount) raise `CMIValidationError` before
364
+ anything is sent.
365
+
366
+ > **After any `CMIApiError` on a capture, refund or void, check before retrying.** The request may have reached
367
+ > CMI even though the answer was lost. Call `order_status()` (or `order_history()` for refunds) first, or the
368
+ > money may move twice.
369
+
370
+ **Your own HTTP client.** The default transport is `urllib` (certificates verified, redirects refused, answers
371
+ over 1 MB rejected). To use a proxy or another client, pass `http_post=`: a function
372
+ `(url, body, headers, timeout) -> cmi.HttpResponse` that must not follow redirects.
373
+
374
+ ---
375
+
376
+ ## Logging
377
+
378
+ The SDK logs through the standard `logging` module, under the `"cmi"` logger, and adds a `NullHandler` like
379
+ every library: configure it in your application. It never logs secrets, the hash input or customer data.
380
+
381
+ ```python
382
+ import logging
383
+ logging.getLogger("cmi").setLevel(logging.WARNING) # warnings: missing validate_order, short store key...
384
+ ```
385
+
386
+ ---
387
+
388
+ ## Security
389
+
390
+ - **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.
391
+ - **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.
392
+ - **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.
393
+ - **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'`).
394
+ - **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").
395
+ - **Rate-limit** your callback endpoint. The Starlette/FastAPI adapter refuses bodies over 100 KB (`max_body_size`).
396
+
397
+ ---
398
+
399
+ ## Troubleshooting
400
+
401
+ | Problem | Fix |
402
+ |---|---|
403
+ | `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 |
404
+ | 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) |
405
+ | 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` |
406
+ | 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 |
407
+ | 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 |
408
+ | `Amount must be greater than or equal to 1` | CMI requires at least 1 (MAD) |
409
+ | 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()` |
410
+ | API `TIMEOUT` / `NETWORK` on a capture or refund | Call `order_status()` before trying again |
411
+
412
+ ---
413
+
414
+ ## Differences from cmi-node
415
+
416
+ The protocol behaviour (hashes, answers, validation rules, rounding) is the same. The API is Pythonic:
417
+
418
+ | cmi-node | cmi-python |
419
+ |---|---|
420
+ | `new CMIPaymentGateway({ storeKey, clientId, ... })` | `CMIPaymentGateway(store_key=..., client_id=..., ...)` (or `.from_dict()`) |
421
+ | `createPaymentParams()`, `generatePaymentForm(params, { nonce })` | `create_payment_params()`, `generate_payment_form(params, nonce=...)` |
422
+ | `result.orderData.orderId`, `amount: number` | `result.order_data.order_id`, `amount: Decimal` |
423
+ | `validateOrder`, `onSuccess`, `onFailure` | `validate_order`, `on_success`, `on_failure` |
424
+ | `api.postAuth({ orderId, amount })`, `timeoutMs` | `api.post_auth(order_id, amount)`, `timeout` (seconds) |
425
+ | `configureLogger(...)` | the standard `logging` module (`"cmi"` logger) |
426
+ | Express, Fastify, Hono, Next.js, NestJS adapters | Django, Flask, FastAPI/Starlette adapters |
427
+ | `Error` on invalid input | `CMIValidationError` (a `ValueError`) |
428
+
429
+ ---
430
+
431
+ ## Development
432
+
433
+ ```bash
434
+ python -m venv .venv && . .venv/bin/activate # Windows: .venv\Scripts\activate
435
+ pip install -e . pytest ruff mypy django flask fastapi httpx
436
+ pytest # unit, PHP-parity, transport and adapter tests
437
+ ruff check src tests && ruff format --check src tests
438
+ mypy # strict
439
+ ```
440
+
441
+ `tests/fixtures/php_parity.json` holds hashes computed by CMI's reference PHP scripts (the same vectors as
442
+ cmi-node): never edit them by hand.
443
+
444
+ ### Releasing
445
+
446
+ `.github/workflows/publish.yml` publishes on PyPI with
447
+ [Trusted Publishing](https://docs.pypi.org/trusted-publishers/) (no token stored in the repository).
448
+
449
+ 1. One-time: on pypi.org (and test.pypi.org), *Account → Publishing → Add a pending publisher*: project
450
+ `cmi-python`, owner `cmi-solutions`, repository `cmi-python`, workflow `publish.yml`, environment `pypi`
451
+ (`testpypi` on TestPyPI).
452
+ 2. Optional dry run: *Actions → Publish to PyPI → Run workflow* publishes the current version on TestPyPI.
453
+ 3. Set the version in `pyproject.toml` and `src/cmi/__init__.py`, add it to `CHANGELOG.md`, then tag and push:
454
+ `git tag v1.0.0 && git push origin v1.0.0`. The workflow checks that the tag matches the version, runs the
455
+ lint, type check and tests, builds, and publishes.
456
+
457
+ PyPI never accepts the same version twice: bump the version for every new upload, TestPyPI included.
458
+
459
+ ## License
460
+
461
+ [MIT](./LICENSE)