cmi-python 1.0.0__py3-none-any.whl

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.
cmi/adapters/flask.py ADDED
@@ -0,0 +1,74 @@
1
+ """Flask adapter for CMI's callback.
2
+
3
+ ::
4
+
5
+ from cmi.adapters.flask import register_flask_callback
6
+
7
+ register_flask_callback(app, gateway, path="/cmi/callback",
8
+ validate_order=validate_order, on_success=mark_paid)
9
+
10
+ CMI posts a form-encoded body, which Flask parses by itself. If you use Flask-WTF's
11
+ ``CSRFProtect``, exempt the callback view (CMI cannot send your CSRF token).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections.abc import Callable
17
+ from typing import Any
18
+
19
+ try:
20
+ from flask import Flask, Response, request
21
+ except ImportError as error: # pragma: no cover
22
+ raise ImportError("cmi.adapters.flask needs Flask: pip install 'cmi-python[flask]'") from error
23
+
24
+ from .._log import logger
25
+ from ..standard import CallbackHandler, CallbackResult, CMIPaymentGateway
26
+
27
+ __all__ = ["create_flask_view", "register_flask_callback"]
28
+
29
+
30
+ def create_flask_view(gateway: CMIPaymentGateway, **options: Any) -> Callable[[], Response]:
31
+ """A Flask view for CMI's callback.
32
+
33
+ It verifies the HASH, runs ``validate_order``, answers CMI (``ACTION=POSTAUTH``,
34
+ ``APPROVED`` or ``FAILURE``) and runs ``on_success`` / ``on_failure`` after the answer
35
+ has been sent (``Response.call_on_close``). The handler is available as
36
+ ``view.cmi_handler``.
37
+ """
38
+ handler: CallbackHandler = gateway.create_callback_handler(**options)
39
+
40
+ def cmi_callback() -> Response:
41
+ result: CallbackResult | None = None
42
+ try:
43
+ if request.method == "GET" and handler.supports_get_method:
44
+ data = request.args.to_dict(flat=False)
45
+ else:
46
+ data = request.form.to_dict(flat=False)
47
+ result, answer = handler.evaluate(data)
48
+ except Exception as error: # noqa: BLE001 - CMI must always get an answer
49
+ logger.error("CMI: callback handler error: %s", type(error).__name__)
50
+ answer = handler.error_response()
51
+
52
+ response = Response(answer.body, status=answer.status, mimetype="text/plain")
53
+ if result is not None:
54
+ finished = result
55
+ response.call_on_close(lambda: handler.notify(finished))
56
+ return response
57
+
58
+ cmi_callback.cmi_handler = handler # type: ignore[attr-defined]
59
+ return cmi_callback
60
+
61
+
62
+ def register_flask_callback(
63
+ app: Flask,
64
+ gateway: CMIPaymentGateway,
65
+ path: str = "/cmi/callback",
66
+ *,
67
+ endpoint: str = "cmi_callback",
68
+ **options: Any,
69
+ ) -> Callable[[], Response]:
70
+ """Register the callback view on ``app`` at ``path`` (POST, plus GET with ``support_get_method``)."""
71
+ view = create_flask_view(gateway, **options)
72
+ methods = ["POST", "GET"] if options.get("support_get_method") else ["POST"]
73
+ app.add_url_rule(path, endpoint=endpoint, view_func=view, methods=methods)
74
+ return view
@@ -0,0 +1,121 @@
1
+ """Starlette / FastAPI adapter for CMI's callback.
2
+
3
+ ::
4
+
5
+ from cmi.adapters.fastapi import register_fastapi_callback
6
+
7
+ register_fastapi_callback(app, gateway, path="/cmi/callback",
8
+ validate_order=validate_order, on_success=mark_paid)
9
+
10
+ The endpoint reads the form-encoded body itself (no python-multipart needed). Hooks may be
11
+ ``async def`` or plain functions; plain functions run in Starlette's thread pool.
12
+ """
13
+
14
+ # No "from __future__ import annotations": FastAPI reads the endpoint's annotations.
15
+
16
+ from collections.abc import Awaitable, Callable
17
+ from typing import Any
18
+
19
+ try:
20
+ from starlette.background import BackgroundTask
21
+ from starlette.concurrency import run_in_threadpool
22
+ from starlette.requests import Request
23
+ from starlette.responses import PlainTextResponse, Response
24
+ except ImportError as error: # pragma: no cover
25
+ raise ImportError(
26
+ "cmi.adapters.starlette needs Starlette (or FastAPI): pip install 'cmi-python[fastapi]'"
27
+ ) from error
28
+
29
+ import inspect
30
+
31
+ from .._log import logger
32
+ from ..standard import CallbackHandler, CallbackResult, CMIPaymentGateway, parse_form_body
33
+ from . import lists_to_fields
34
+
35
+ __all__ = ["DEFAULT_MAX_BODY_SIZE", "create_starlette_endpoint", "register_fastapi_callback"]
36
+
37
+ #: CMI's callbacks are a few kilobytes; bigger bodies are refused (HTTP 413).
38
+ DEFAULT_MAX_BODY_SIZE = 100 * 1024
39
+
40
+
41
+ def _in_threadpool(hook: Callable[..., Any] | None) -> Callable[..., Any] | None:
42
+ """Run a plain function in the thread pool, so a blocking hook never blocks the event loop."""
43
+ if hook is None or inspect.iscoroutinefunction(hook):
44
+ return hook
45
+
46
+ async def threaded(result: CallbackResult) -> Any:
47
+ outcome = await run_in_threadpool(hook, result)
48
+ if inspect.isawaitable(outcome):
49
+ outcome = await outcome
50
+ return outcome
51
+
52
+ return threaded
53
+
54
+
55
+ async def _read_body(request: Request, limit: int) -> bytes | None:
56
+ declared = request.headers.get("content-length", "")
57
+ if declared.isdigit() and int(declared) > limit:
58
+ return None
59
+ chunks = []
60
+ size = 0
61
+ async for chunk in request.stream():
62
+ size += len(chunk)
63
+ if size > limit:
64
+ return None
65
+ chunks.append(chunk)
66
+ return b"".join(chunks)
67
+
68
+
69
+ def create_starlette_endpoint(
70
+ gateway: CMIPaymentGateway,
71
+ *,
72
+ max_body_size: int = DEFAULT_MAX_BODY_SIZE,
73
+ **options: Any,
74
+ ) -> Callable[[Request], Awaitable[Response]]:
75
+ """An ``async`` endpoint for CMI's callback, for Starlette routes and FastAPI.
76
+
77
+ It verifies the HASH, awaits ``validate_order``, answers CMI (``ACTION=POSTAUTH``,
78
+ ``APPROVED`` or ``FAILURE``) and runs ``on_success`` / ``on_failure`` as a background
79
+ task, after the answer has been sent. The handler is available as ``endpoint.cmi_handler``.
80
+ """
81
+ for name in ("validate_order", "on_success", "on_failure"):
82
+ if name in options:
83
+ options[name] = _in_threadpool(options[name])
84
+ handler: CallbackHandler = gateway.create_callback_handler(**options)
85
+
86
+ async def cmi_callback(request: Request) -> Response:
87
+ result: CallbackResult | None = None
88
+ try:
89
+ if request.method == "GET" and handler.supports_get_method:
90
+ data: Any = lists_to_fields(request.query_params.multi_items())
91
+ else:
92
+ body = await _read_body(request, max_body_size)
93
+ if body is None:
94
+ logger.warning("CMI: callback body larger than %d bytes refused", max_body_size)
95
+ failure = handler.error_response()
96
+ return PlainTextResponse(failure.body, status_code=413)
97
+ data = parse_form_body(body)
98
+ result, answer = await handler.evaluate_async(data)
99
+ except Exception as error: # noqa: BLE001 - CMI must always get an answer
100
+ logger.error("CMI: callback handler error: %s", type(error).__name__)
101
+ answer = handler.error_response()
102
+
103
+ background = BackgroundTask(handler.notify_async, result) if result is not None else None
104
+ return PlainTextResponse(answer.body, status_code=answer.status, background=background)
105
+
106
+ cmi_callback.cmi_handler = handler # type: ignore[attr-defined]
107
+ return cmi_callback
108
+
109
+
110
+ def register_fastapi_callback(
111
+ app: Any,
112
+ gateway: CMIPaymentGateway,
113
+ path: str = "/cmi/callback",
114
+ **options: Any,
115
+ ) -> Callable[[Request], Awaitable[Response]]:
116
+ """Register the callback endpoint on a FastAPI app (or APIRouter), hidden from the OpenAPI
117
+ schema. POST only, plus GET with ``support_get_method``."""
118
+ endpoint = create_starlette_endpoint(gateway, **options)
119
+ methods = ["POST", "GET"] if options.get("support_get_method") else ["POST"]
120
+ app.add_api_route(path, endpoint, methods=methods, include_in_schema=False)
121
+ return endpoint
cmi/api/__init__.py ADDED
@@ -0,0 +1,35 @@
1
+ """API kit: CMI's back-office XML API (CC5).
2
+
3
+ Capture (PostAuth), refund (Credit), void, order status and order history, called from
4
+ the shop's server with a CMI API user (not the store key).
5
+ """
6
+
7
+ from .._cc5 import HttpPost, HttpResponse, urllib_http_post
8
+ from ..errors import CMIApiError, CMIApiErrorCode
9
+ from .client import AsyncCMIApiClient, CMIApiClient
10
+ from .types import (
11
+ CMIApiResponse,
12
+ CMIOrderHistoryEntry,
13
+ CMIOrderHistoryResult,
14
+ CMIOrderStatus,
15
+ CMIOrderStatusResult,
16
+ CMIOrderTransaction,
17
+ CMITransactionResult,
18
+ )
19
+
20
+ __all__ = [
21
+ "AsyncCMIApiClient",
22
+ "CMIApiClient",
23
+ "CMIApiError",
24
+ "CMIApiErrorCode",
25
+ "CMIApiResponse",
26
+ "CMIOrderHistoryEntry",
27
+ "CMIOrderHistoryResult",
28
+ "CMIOrderStatus",
29
+ "CMIOrderStatusResult",
30
+ "CMIOrderTransaction",
31
+ "CMITransactionResult",
32
+ "HttpPost",
33
+ "HttpResponse",
34
+ "urllib_http_post",
35
+ ]
@@ -0,0 +1,192 @@
1
+ """Reading CMI order statuses: TRANS_STAT codes, amounts in cents, ORDERSTATUS name:value
2
+ text and the TRXn lines of an order history."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import re
7
+ from collections.abc import Mapping
8
+ from decimal import Decimal
9
+ from typing import Any, NamedTuple
10
+
11
+ from .._compat import js_trim
12
+ from .types import CMIOrderHistoryEntry, CMIOrderStatus, CMIOrderTransaction
13
+
14
+
15
+ class StatusInfo(NamedTuple):
16
+ status: CMIOrderStatus
17
+ shipment_possible: bool
18
+ transient: bool
19
+
20
+
21
+ _STATUSES: dict[str, StatusInfo] = {
22
+ "D": StatusInfo("declined", False, False),
23
+ "A": StatusInfo("preauthorized", False, False),
24
+ "C": StatusInfo("captured", True, False),
25
+ "S": StatusInfo("settled", True, False),
26
+ "V": StatusInfo("voided", False, False),
27
+ "PN": StatusInfo("pending", False, True),
28
+ "R": StatusInfo("reversal_required", False, True),
29
+ "NW": StatusInfo("processing", False, True),
30
+ "ERR": StatusInfo("error", False, False),
31
+ "CNCL": StatusInfo("cancelled", False, False),
32
+ }
33
+
34
+
35
+ def describe_status(status_code: str, charge_type: str) -> StatusInfo:
36
+ """CMI's transaction status table (TRANS_STAT x CHARGE_TYPE_CD)."""
37
+ code = js_trim(status_code).upper()
38
+ charge = js_trim(charge_type).upper()
39
+ if charge == "C" and code in ("C", "S"):
40
+ return StatusInfo("refunded", False, False)
41
+ return _STATUSES.get(code, StatusInfo("unknown", False, False))
42
+
43
+
44
+ def cents_to_amount(value: str | None) -> Decimal | None:
45
+ """ "9196" (cents) -> Decimal("91.96"). None when empty or not a whole number."""
46
+ text = js_trim(value) if value is not None else ""
47
+ if not text or not re.fullmatch(r"-?[0-9]+", text):
48
+ return None
49
+ return Decimal(int(text)) / 100
50
+
51
+
52
+ def _non_empty(value: str | None) -> str | None:
53
+ text = js_trim(value) if value is not None else ""
54
+ return text or None
55
+
56
+
57
+ _STATUS_NAME = re.compile(r"(^|\s)([A-Z][A-Z0-9_]*):")
58
+
59
+
60
+ def parse_order_status_text(text: str) -> dict[str, str]:
61
+ """Read the ORDERSTATUS text: "ORD_ID:x CHARGE_TYPE_CD:S ... AUTH_DTTM:2017-05-20 14:18:00.427 ...".
62
+
63
+ Pairs are tab-separated; spaces are accepted too (values such as dates may contain spaces,
64
+ so a new pair only starts at a name made of capitals, digits and underscores). One forward
65
+ scan: the time grows linearly with the text's size.
66
+ """
67
+ pairs: dict[str, str] = {}
68
+ names = list(_STATUS_NAME.finditer(text))
69
+ for index, match in enumerate(names):
70
+ value_end = names[index + 1].start() if index + 1 < len(names) else len(text)
71
+ pairs[match.group(2)] = js_trim(text[match.end() : value_end])
72
+ return pairs
73
+
74
+
75
+ def _transaction_fields(fields: Mapping[str, str | None]) -> dict[str, Any]:
76
+ status_code = _non_empty(fields.get("statusCode")) or ""
77
+ charge_type = _non_empty(fields.get("chargeType")) or ""
78
+ info = describe_status(status_code, charge_type)
79
+ return {
80
+ "status": info.status,
81
+ "shipment_possible": info.shipment_possible,
82
+ "transient": info.transient,
83
+ "status_code": status_code,
84
+ "charge_type": charge_type,
85
+ "original_amount": cents_to_amount(fields.get("originalAmount")),
86
+ "captured_amount": cents_to_amount(fields.get("capturedAmount")),
87
+ "authorized_at": _non_empty(fields.get("authorizedAt")),
88
+ "captured_at": _non_empty(fields.get("capturedAt")),
89
+ "auth_code": _non_empty(fields.get("authCode")),
90
+ "host_ref_num": _non_empty(fields.get("hostRefNum")),
91
+ "host_return_code": _non_empty(fields.get("hostReturnCode")),
92
+ "trans_id": _non_empty(fields.get("transId")),
93
+ "settle_id": _non_empty(fields.get("settleId")),
94
+ "xid": _non_empty(fields.get("xid")),
95
+ "cavv": _non_empty(fields.get("cavv")),
96
+ "eci": _non_empty(fields.get("eci")),
97
+ "md_status": _non_empty(fields.get("mdStatus")),
98
+ }
99
+
100
+
101
+ def transaction_from_status_fields(fields: Mapping[str, str]) -> CMIOrderTransaction:
102
+ """Build a transaction from the status fields (Extra elements, ORDERSTATUS as fallback)."""
103
+ return CMIOrderTransaction(
104
+ **_transaction_fields(
105
+ {
106
+ "statusCode": fields.get("TRANS_STAT"),
107
+ "chargeType": fields.get("CHARGE_TYPE_CD"),
108
+ "originalAmount": fields.get("ORIG_TRANS_AMT"),
109
+ "capturedAmount": fields.get("CAPTURE_AMT"),
110
+ "authorizedAt": fields.get("AUTH_DTTM"),
111
+ "capturedAt": fields.get("CAPTURE_DTTM"),
112
+ "authCode": fields.get("AUTH_CODE"),
113
+ "hostRefNum": fields.get("HOST_REF_NUM"),
114
+ "hostReturnCode": fields.get("PROC_RET_CD"),
115
+ "transId": fields.get("TRANS_ID"),
116
+ "settleId": fields.get("SETTLEID"),
117
+ "xid": fields.get("XID_3D"),
118
+ "cavv": fields.get("CAVV_3D"),
119
+ "eci": fields.get("ECI_3D"),
120
+ "mdStatus": fields.get("MDSTATUS"),
121
+ }
122
+ )
123
+ )
124
+
125
+
126
+ # The TRXn columns, in CMI's order.
127
+ _HISTORY_COLUMNS = (
128
+ "chargeType", "statusCode", "originalAmount", "capturedAmount", "authorizedAt", "capturedAt",
129
+ "voidedAt", "hostRefNum", "authCode", "hostReturnCode", "transId", "settleId", "xid", "cavv",
130
+ "eci", "mdStatus",
131
+ ) # fmt: skip
132
+ _TAIL_COLUMNS = ("hostRefNum", "authCode", "hostReturnCode", "transId", "settleId", "xid", "cavv", "eci", "mdStatus")
133
+ _DATE = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
134
+ _TIME = re.compile(r"[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]+)?")
135
+
136
+
137
+ def _history_columns(line: str) -> dict[str, str]:
138
+ """Split a TRXn line into its columns.
139
+
140
+ CMI documents the line as tab-separated, with empty columns kept. Lines where the tabs
141
+ were turned into spaces are read too: dates ("2017-05-20 14:18:00.427") are joined back,
142
+ and the dates fill the authorized / captured / voided columns in turn.
143
+ """
144
+ columns: dict[str, str] = {}
145
+ if "\t" in line:
146
+ for index, value in enumerate(line.split("\t")):
147
+ if index < len(_HISTORY_COLUMNS):
148
+ columns[_HISTORY_COLUMNS[index]] = js_trim(value)
149
+ return columns
150
+
151
+ tokens = re.split(r"\s+", js_trim(line))
152
+ values: list[str] = []
153
+ i = 0
154
+ while i < len(tokens):
155
+ if _DATE.fullmatch(tokens[i]) and i + 1 < len(tokens) and _TIME.fullmatch(tokens[i + 1]):
156
+ values.append(f"{tokens[i]} {tokens[i + 1]}")
157
+ i += 2
158
+ else:
159
+ values.append(tokens[i])
160
+ i += 1
161
+ for name, value in zip(("chargeType", "statusCode", "originalAmount", "capturedAmount"), values, strict=False):
162
+ columns[name] = value
163
+ rest = values[4:]
164
+ for date_column in ("authorizedAt", "capturedAt", "voidedAt"):
165
+ if rest and _DATE.fullmatch(rest[0].split(" ")[0]):
166
+ columns[date_column] = rest.pop(0)
167
+ else:
168
+ break
169
+ for name, value in zip(_TAIL_COLUMNS, rest, strict=False):
170
+ columns[name] = value
171
+ return columns
172
+
173
+
174
+ def parse_history_line(line: str) -> CMIOrderHistoryEntry:
175
+ """Read one TRXn line of an order history."""
176
+ columns = _history_columns(line)
177
+ return CMIOrderHistoryEntry(
178
+ **_transaction_fields(columns),
179
+ voided_at=_non_empty(columns.get("voidedAt")),
180
+ raw=line,
181
+ )
182
+
183
+
184
+ def history_lines(extra: Mapping[str, str]) -> list[str]:
185
+ """The TRX1..TRXn lines of an order history, in order (by number, not by tag order)."""
186
+ numbered = []
187
+ for key, value in extra.items():
188
+ match = re.fullmatch(r"TRX([0-9]+)", key)
189
+ if match:
190
+ numbered.append((int(match.group(1)), value))
191
+ numbered.sort(key=lambda item: item[0])
192
+ return [value for _, value in numbered if js_trim(value) != ""]
cmi/api/client.py ADDED
@@ -0,0 +1,242 @@
1
+ """API kit: CMI's back-office XML API (CC5): capture (PostAuth), refund (Credit), void,
2
+ order status and order history. Server-only: it holds the API password."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import asyncio
7
+ import re
8
+ from collections.abc import Mapping
9
+ from decimal import Decimal
10
+ from typing import Any, NoReturn, Union
11
+
12
+ from .._amount import format_amount
13
+ from .._cc5 import CC5Node, CC5Response, CC5Transport, HttpPost, require_text
14
+ from .._cc5.transport import DEFAULT_TIMEOUT
15
+ from .._security import assert_server_runtime
16
+ from ..constants import normalize_currency
17
+ from ..errors import CMIValidationError
18
+ from ._order_status import history_lines, parse_history_line, parse_order_status_text, transaction_from_status_fields
19
+ from .types import CMIOrderHistoryResult, CMIOrderStatusResult, CMITransactionResult
20
+
21
+ __all__ = ["AsyncCMIApiClient", "CMIApiClient"]
22
+
23
+ MAX_ORDER_ID_LENGTH = 64
24
+ Amount = Union[int, float, Decimal, str]
25
+
26
+
27
+ def _order_id(value: Any) -> str:
28
+ return require_text(value, "order_id", MAX_ORDER_ID_LENGTH)
29
+
30
+
31
+ def _positive_amount(value: Amount, operation: str) -> str:
32
+ amount = format_amount(value)
33
+ if amount.startswith("-") or re.fullmatch(r"0+\.00", amount):
34
+ raise CMIValidationError(f'The {operation} amount must be greater than 0 (got "{value}").')
35
+ return amount
36
+
37
+
38
+ def _optional(value: str | None) -> str | None:
39
+ return value or None
40
+
41
+
42
+ def _base(answer: CC5Response) -> dict[str, Any]:
43
+ fields, extra = answer.fields, answer.extra
44
+ return {
45
+ "response": fields.get("Response", ""),
46
+ "proc_return_code": fields.get("ProcReturnCode", ""),
47
+ "message": _optional(fields.get("ErrMsg")),
48
+ "error_code": _optional(extra.get("ERRORCODE", fields.get("ERRORCODE"))),
49
+ "order_id": _optional(fields.get("OrderId")),
50
+ "fields": fields,
51
+ "extra": extra,
52
+ }
53
+
54
+
55
+ def _is_approved(base: Mapping[str, Any]) -> bool:
56
+ return bool(base["response"] == "Approved" and base["proc_return_code"] == "00")
57
+
58
+
59
+ class CMIApiClient:
60
+ """CMI back-office API client (API kit).
61
+
62
+ It uses an **API user** (name and password created for API access in CMI's back office)
63
+ and the API URL, both given by CMI, not the store key: it is independent from the
64
+ Standard kit's :class:`~cmi.CMIPaymentGateway`. Run it on your server only.
65
+
66
+ Every operation sends one request and never retries. A refused operation is a result
67
+ (``approved=False``); a :class:`~cmi.CMIApiError` means no usable answer came back.
68
+ After a CMIApiError on ``post_auth``, ``refund`` or ``void``, CMI may still have done it:
69
+ call :meth:`order_status` (or :meth:`order_history`) before sending it again.
70
+
71
+ Example::
72
+
73
+ api = CMIApiClient(
74
+ api_url=os.environ["CMI_API_URL"],
75
+ client_id=os.environ["CMI_CLIENT_ID"],
76
+ username=os.environ["CMI_API_USER"],
77
+ password=os.environ["CMI_API_PASSWORD"],
78
+ )
79
+ status = api.order_status("ORDER-123")
80
+ if status.transaction and status.transaction.status == "preauthorized":
81
+ capture = api.post_auth("ORDER-123")
82
+ if not capture.approved:
83
+ print(capture.proc_return_code, capture.message)
84
+ """
85
+
86
+ __slots__ = ("__transport",)
87
+
88
+ def __init__(
89
+ self,
90
+ *,
91
+ api_url: str,
92
+ client_id: str,
93
+ username: str,
94
+ password: str,
95
+ timeout: float = DEFAULT_TIMEOUT,
96
+ http_post: HttpPost | None = None,
97
+ ) -> None:
98
+ """
99
+ :param api_url: URL of CMI's XML API, ``https://`` only (plain http only for localhost).
100
+ :param client_id: Merchant ID (ClientId), up to 15 characters.
101
+ :param username: API user name.
102
+ :param password: API user password (kept in a SecretString, never logged).
103
+ :param timeout: Seconds allowed for the call (connection and answer). Default 30, max 300.
104
+ :param http_post: Optional HTTP function ``(url, body, headers, timeout) -> HttpResponse``,
105
+ to use another HTTP client or a proxy. It must not follow redirects.
106
+ """
107
+ assert_server_runtime()
108
+ self.__transport = CC5Transport(
109
+ api_url=api_url,
110
+ client_id=client_id,
111
+ username=username,
112
+ password=password,
113
+ timeout=timeout,
114
+ http_post=http_post,
115
+ )
116
+
117
+ def post_auth(self, order_id: str, amount: Amount | None = None) -> CMITransactionResult:
118
+ """Capture a pre-authorized order (PostAuth). Leave ``amount`` out to capture the whole
119
+ authorized amount; a smaller amount captures part of it."""
120
+ oid = _order_id(order_id)
121
+ elements: list[tuple[str, CC5Node]] = [("Type", "PostAuth"), ("OrderId", oid)]
122
+ if amount is not None:
123
+ elements.append(("Total", _positive_amount(amount, "capture")))
124
+ return self._transaction("post_auth", oid, elements)
125
+
126
+ def refund(self, order_id: str, amount: Amount | None = None, currency: str | None = None) -> CMITransactionResult:
127
+ """Refund a captured order (Credit). Leave ``amount`` out to refund the whole order.
128
+ Several partial refunds are allowed, up to the captured amount. ``currency`` ("504" or
129
+ "MAD", default MAD) goes with ``amount`` only."""
130
+ oid = _order_id(order_id)
131
+ elements: list[tuple[str, CC5Node]] = [("Type", "Credit"), ("OrderId", oid)]
132
+ if amount is not None:
133
+ numeric = normalize_currency(currency if currency is not None else "504")
134
+ if not numeric:
135
+ raise CMIValidationError(f'Unsupported currency "{currency}".')
136
+ elements += [("Total", _positive_amount(amount, "refund")), ("Currency", numeric)]
137
+ elif currency is not None:
138
+ raise CMIValidationError(
139
+ "currency is only used with amount (a partial refund). Leave both out for a full refund, "
140
+ "or give the amount to refund."
141
+ )
142
+ return self._transaction("refund", oid, elements)
143
+
144
+ def void(self, order_id: str) -> CMITransactionResult:
145
+ """Cancel (void) an order's pre-authorization, capture, sale or refund."""
146
+ oid = _order_id(order_id)
147
+ return self._transaction("void", oid, [("Type", "Void"), ("OrderId", oid)])
148
+
149
+ def order_status(self, order_id: str) -> CMIOrderStatusResult:
150
+ """Query an order's status. Nothing changes on CMI's side.
151
+
152
+ CMI reports the order's last successful transaction, or its last failed one when none
153
+ succeeded. For a ``transient`` status (pending, reversal_required, processing), query
154
+ again later (CMI suggests every 5 minutes).
155
+ """
156
+ oid = _order_id(order_id)
157
+ answer = self.__transport.send("order_status", oid, [("OrderId", oid), ("Extra", [("ORDERSTATUS", "QUERY")])])
158
+ base = _base(answer)
159
+ if not _is_approved(base):
160
+ return CMIOrderStatusResult(**base, found=False)
161
+
162
+ # Separate Extra elements win; the ORDERSTATUS name:value text fills any gap.
163
+ merged = parse_order_status_text(answer.extra["ORDERSTATUS"]) if answer.extra.get("ORDERSTATUS") else {}
164
+ for key, value in answer.extra.items():
165
+ if value != "" or key not in merged:
166
+ merged[key] = value
167
+ return CMIOrderStatusResult(
168
+ **base,
169
+ found=True,
170
+ transaction=transaction_from_status_fields(merged),
171
+ masked_pan=_optional(answer.extra.get("PAN")),
172
+ )
173
+
174
+ def order_history(self, order_id: str) -> CMIOrderHistoryResult:
175
+ """List every transaction of an order (authorizations, captures, refunds, voids)."""
176
+ oid = _order_id(order_id)
177
+ answer = self.__transport.send("order_history", oid, [("OrderId", oid), ("Extra", [("ORDERHISTORY", "QUERY")])])
178
+ base = _base(answer)
179
+ found = _is_approved(base)
180
+ transactions = tuple(parse_history_line(line) for line in history_lines(answer.extra)) if found else ()
181
+ return CMIOrderHistoryResult(**base, found=found, transactions=transactions)
182
+
183
+ def _transaction(self, operation: str, order_id: str, elements: list[tuple[str, CC5Node]]) -> CMITransactionResult:
184
+ answer = self.__transport.send(operation, order_id, elements)
185
+ base = _base(answer)
186
+ fields, extra = answer.fields, answer.extra
187
+ return CMITransactionResult(
188
+ **base,
189
+ approved=_is_approved(base),
190
+ trans_id=_optional(fields.get("TransId")),
191
+ group_id=_optional(fields.get("GroupId")),
192
+ auth_code=_optional(fields.get("AuthCode")),
193
+ host_ref_num=_optional(fields.get("HostRefNum")),
194
+ settle_id=_optional(extra.get("SETTLEID")),
195
+ transaction_date=_optional(extra.get("TRXDATE")),
196
+ card_brand=_optional(extra.get("CARDBRAND")),
197
+ card_issuer=_optional(extra.get("CARDISSUER")),
198
+ )
199
+
200
+ def __repr__(self) -> str:
201
+ d = self.__transport.describe()
202
+ return f"CMIApiClient(api_url={d['api_url']!r}, client_id={d['client_id']!r}, password='********')"
203
+
204
+ def __reduce__(self) -> NoReturn:
205
+ raise TypeError("CMIApiClient cannot be pickled: it holds the CMI API password")
206
+
207
+
208
+ class AsyncCMIApiClient:
209
+ """:class:`CMIApiClient` for asyncio code (FastAPI, Starlette...).
210
+
211
+ Each call runs the blocking HTTP request in a worker thread (``asyncio.to_thread``),
212
+ so the event loop is never blocked. Same settings, methods and results as
213
+ :class:`CMIApiClient`.
214
+ """
215
+
216
+ __slots__ = ("_client",)
217
+
218
+ def __init__(self, **settings: Any) -> None:
219
+ self._client = CMIApiClient(**settings)
220
+
221
+ async def post_auth(self, order_id: str, amount: Amount | None = None) -> CMITransactionResult:
222
+ return await asyncio.to_thread(self._client.post_auth, order_id, amount)
223
+
224
+ async def refund(
225
+ self, order_id: str, amount: Amount | None = None, currency: str | None = None
226
+ ) -> CMITransactionResult:
227
+ return await asyncio.to_thread(self._client.refund, order_id, amount, currency)
228
+
229
+ async def void(self, order_id: str) -> CMITransactionResult:
230
+ return await asyncio.to_thread(self._client.void, order_id)
231
+
232
+ async def order_status(self, order_id: str) -> CMIOrderStatusResult:
233
+ return await asyncio.to_thread(self._client.order_status, order_id)
234
+
235
+ async def order_history(self, order_id: str) -> CMIOrderHistoryResult:
236
+ return await asyncio.to_thread(self._client.order_history, order_id)
237
+
238
+ def __repr__(self) -> str:
239
+ return "Async" + repr(self._client)
240
+
241
+ def __reduce__(self) -> NoReturn:
242
+ raise TypeError("AsyncCMIApiClient cannot be pickled: it holds the CMI API password")