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.
@@ -0,0 +1,417 @@
1
+ """Verification of CMI's callbacks, and the framework-agnostic callback handler."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ from collections.abc import Awaitable, Callable, Mapping
7
+ from dataclasses import dataclass, field
8
+ from decimal import Decimal, InvalidOperation
9
+ from typing import TYPE_CHECKING, Any, Literal, Union
10
+ from urllib.parse import parse_qsl
11
+
12
+ from .._compat import js_parse_float_prefix, to_field_string
13
+ from .._log import logger
14
+ from .._security import SecretString, timing_safe_compare
15
+ from ..constants import ConfirmationMode
16
+ from . import _hash
17
+
18
+ if TYPE_CHECKING:
19
+ from .gateway import CMIPaymentGateway
20
+
21
+ __all__ = [
22
+ "CallbackAnswer",
23
+ "CallbackHandler",
24
+ "CallbackResult",
25
+ "CallbackStatus",
26
+ "OrderData",
27
+ "parse_form_body",
28
+ ]
29
+
30
+ CallbackStatus = Literal["ACTION=POSTAUTH", "APPROVED", "DECLINED", "FAILURE"]
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class OrderData:
35
+ """The payment details CMI sent. Card and customer fields are left out of ``repr()``:
36
+ log the order id, not the whole object."""
37
+
38
+ order_id: str | None
39
+ #: The amount CMI processed, as an exact Decimal (compare it with your order's amount).
40
+ amount: Decimal
41
+ currency: str | None
42
+ #: Bank transaction ID (TransId). None when absent, e.g. on failure callbacks.
43
+ transaction_id: str | None = None
44
+ # Always present (success and failure)
45
+ #: Bank/gateway return code, "00" = approved (ProcReturnCode).
46
+ return_code: str | None = None
47
+ #: "Approved", "Declined" or "Error" (Response).
48
+ response: str | None = None
49
+ #: 3-D Secure status (mdStatus).
50
+ md_status: str | None = None
51
+ error_message: str | None = None
52
+ error_code: str | None = None
53
+ #: Order id echoed back by CMI (ReturnOid).
54
+ return_oid: str | None = None
55
+ client_ip: str | None = field(default=None, repr=False)
56
+ # Present on success
57
+ auth_code: str | None = None
58
+ #: EXTRA.TRXDATE, as sent by CMI.
59
+ transaction_date: str | None = None
60
+ masked_pan: str | None = field(default=None, repr=False)
61
+ card_holder_name: str | None = field(default=None, repr=False)
62
+ payment_type: str | None = None
63
+ card_brand: str | None = None
64
+ card_issuer: str | None = None
65
+ card_exp_year: str | None = field(default=None, repr=False)
66
+ card_exp_month: str | None = field(default=None, repr=False)
67
+ host_ref_num: str | None = None
68
+ acq_stan: str | None = None
69
+ eci: str | None = None
70
+ tx_status: str | None = None
71
+
72
+
73
+ @dataclass(frozen=True)
74
+ class CallbackResult:
75
+ """Result of a callback verification.
76
+
77
+ ====================================== ========= ========== =================================
78
+ Callback from CMI success verified status
79
+ ====================================== ========= ========== =================================
80
+ Authentic, approved (ProcReturnCode 00) True True ``ACTION=POSTAUTH`` / ``APPROVED``
81
+ Authentic, declined False True ``DECLINED``
82
+ Approved, refused by validate_order False True ``FAILURE``
83
+ Missing or wrong HASH False False ``FAILURE``
84
+ ====================================== ========= ========== =================================
85
+ """
86
+
87
+ #: True only for an authentic, approved payment (ProcReturnCode "00").
88
+ success: bool
89
+ status: CallbackStatus
90
+ #: True when the HASH matched, i.e. the data really comes from CMI.
91
+ verified: bool
92
+ message: str
93
+ order_data: OrderData | None = None
94
+ error_code: str | None = None
95
+ error_message: str | None = None
96
+
97
+
98
+ @dataclass(frozen=True)
99
+ class CallbackAnswer:
100
+ """HTTP status and body to answer CMI with."""
101
+
102
+ status: int
103
+ body: str
104
+
105
+
106
+ def parse_form_body(body: bytes | str) -> dict[str, list[str]]:
107
+ """Parse an ``application/x-www-form-urlencoded`` body (CMI's callback) into lists of values.
108
+
109
+ Pass the result to :meth:`CMIPaymentGateway.verify_callback`: a repeated field keeps its
110
+ last value, like PHP's ``$_POST``.
111
+ """
112
+ text = body.decode("utf-8", "replace") if isinstance(body, (bytes, bytearray)) else body
113
+ fields: dict[str, list[str]] = {}
114
+ for key, value in parse_qsl(text, keep_blank_values=True, max_num_fields=2000):
115
+ fields.setdefault(key, []).append(value)
116
+ return fields
117
+
118
+
119
+ def _resolve(fields: Mapping[str, str], *keys: str) -> str | None:
120
+ """The first non-empty value among several spellings of a field."""
121
+ for key in keys:
122
+ value = fields.get(key)
123
+ if value:
124
+ return value
125
+ return None
126
+
127
+
128
+ def _parse_amount(value: str | None) -> Decimal:
129
+ """``parseFloat()`` semantics ("10.25" -> 10.25, "abc" -> 0), as an exact Decimal."""
130
+ prefix = js_parse_float_prefix(value)
131
+ if prefix is None or "Infinity" in prefix:
132
+ return Decimal(0)
133
+ try:
134
+ return Decimal(prefix)
135
+ except InvalidOperation: # pragma: no cover - the prefix is always a valid number
136
+ return Decimal(0)
137
+
138
+
139
+ class CallbackVerifier:
140
+ """Checks the HASH of a callback and reads its fields."""
141
+
142
+ __slots__ = ("__store_key", "_confirmation_mode")
143
+
144
+ def __init__(self, *, store_key: SecretString, confirmation_mode: ConfirmationMode) -> None:
145
+ self.__store_key = store_key
146
+ self._confirmation_mode = confirmation_mode
147
+
148
+ def verify(self, raw_params: Mapping[str, Any]) -> CallbackResult:
149
+ try:
150
+ # Read every field as text exactly once, so the hash and order_data use the same
151
+ # values. A repeated field (oid=A&oid=B, a list) keeps its last value, like $_POST.
152
+ fields = {str(key): to_field_string(raw_params[key]) for key in raw_params}
153
+
154
+ received_hash = fields.get("HASH") or fields.get("hash")
155
+ if not received_hash:
156
+ return CallbackResult(False, "FAILURE", False, "Hash not found in callback")
157
+
158
+ # Recalculate the hash over every received field, exactly as CMI's callback.php does.
159
+ calculated = _hash.generate_for_callback(fields, self.__store_key)
160
+ if not timing_safe_compare(received_hash, calculated):
161
+ return CallbackResult(False, "FAILURE", False, "Hash verification failed - possible tampering")
162
+
163
+ return_code = fields.get("ProcReturnCode", fields.get("ReturnCode", ""))
164
+ error_message = _resolve(fields, "ErrMsg", "errMsg", "ERRMSG")
165
+ core: dict[str, Any] = {
166
+ "order_id": fields.get("oid"),
167
+ "amount": _parse_amount(fields.get("amount")),
168
+ "currency": fields.get("currency"),
169
+ "transaction_id": _resolve(fields, "TransId", "transId"),
170
+ "return_code": return_code,
171
+ "response": _resolve(fields, "Response", "response"),
172
+ "md_status": _resolve(fields, "mdStatus", "MdStatus", "MDSTATUS"),
173
+ "error_message": error_message,
174
+ "error_code": _resolve(fields, "ErrCode", "errcode", "ERRCODE"),
175
+ "return_oid": _resolve(fields, "ReturnOid", "returnOid", "RETURNOID"),
176
+ "client_ip": _resolve(fields, "ClientIp", "clientIp", "CLIENTIP"),
177
+ }
178
+
179
+ if return_code == "00":
180
+ order_data = OrderData(
181
+ **core,
182
+ auth_code=_resolve(fields, "AuthCode", "authCode", "AUTHCODE"),
183
+ transaction_date=_resolve(fields, "EXTRA.TRXDATE", "EXTRA.trxdate", "extra.trxdate"),
184
+ masked_pan=_resolve(fields, "MaskedPan", "maskedPan", "MASKEDPAN"),
185
+ card_holder_name=_resolve(fields, "cardHolderName", "CardHolderName", "CARDHOLDERNAME"),
186
+ payment_type=_resolve(fields, "paymentType", "PaymentType", "PAYMENTTYPE"),
187
+ card_brand=_resolve(fields, "EXTRA.CARDBRAND", "EXTRA.cardbrand", "extra.cardbrand"),
188
+ card_issuer=_resolve(fields, "EXTRA.CARDISSUER", "EXTRA.cardissuer", "extra.cardissuer"),
189
+ card_exp_year=_resolve(fields, "EcomPaymentCardExpDateYear", "ecomPaymentCardExpDateYear"),
190
+ card_exp_month=_resolve(fields, "EcomPaymentCardExpDateMonth", "ecomPaymentCardExpDateMonth"),
191
+ host_ref_num=_resolve(fields, "HostRefNum", "hostRefNum", "HOSTREFNUM"),
192
+ acq_stan=_resolve(fields, "acqStan", "AcqStan", "ACQSTAN"),
193
+ eci=_resolve(fields, "eci", "Eci", "ECI"),
194
+ tx_status=_resolve(fields, "txstatus", "txStatus", "TXSTATUS"),
195
+ )
196
+ status: CallbackStatus = "ACTION=POSTAUTH" if self._confirmation_mode == "auto" else "APPROVED"
197
+ return CallbackResult(True, status, True, "Payment successful", order_data)
198
+
199
+ # Authentic callback for a failed attempt (ProcReturnCode other than "00", or missing).
200
+ # CMI expects the acknowledgement "APPROVED" (see CallbackHandler.get_response).
201
+ return CallbackResult(
202
+ success=False,
203
+ status="DECLINED",
204
+ verified=True,
205
+ message=f"Payment failed with return code: {return_code}",
206
+ order_data=OrderData(**core),
207
+ error_code=return_code,
208
+ error_message=error_message,
209
+ )
210
+ except Exception as error: # noqa: BLE001 - a broken callback must answer FAILURE, never crash
211
+ logger.error("CMI: error verifying callback: %s", type(error).__name__)
212
+ return CallbackResult(False, "FAILURE", False, f"Error verifying callback: {error}")
213
+
214
+
215
+ CallbackHook = Callable[[CallbackResult], Union[Any, Awaitable[Any]]]
216
+
217
+
218
+ class CallbackHandler:
219
+ """Framework-agnostic handling of CMI's callback.
220
+
221
+ It verifies the HASH, runs ``validate_order`` before CMI is answered, works out the
222
+ answer CMI expects, and runs ``on_success`` / ``on_failure``.
223
+
224
+ Use :meth:`handle` / :meth:`evaluate` from synchronous code (Django, Flask) and
225
+ :meth:`handle_async` / :meth:`evaluate_async` from async code (FastAPI, Starlette);
226
+ the async methods accept both ``async def`` and plain functions as hooks.
227
+
228
+ The HASH proves the data comes from CMI, but a valid callback can be **replayed**:
229
+ check in ``validate_order`` that the order exists, is not already paid and has this
230
+ amount, and make your "paid" update idempotent.
231
+ """
232
+
233
+ def __init__(
234
+ self,
235
+ gateway: CMIPaymentGateway,
236
+ *,
237
+ validate_order: Callable[[CallbackResult], bool | Awaitable[bool]] | None = None,
238
+ on_success: CallbackHook | None = None,
239
+ on_failure: CallbackHook | None = None,
240
+ success_response: str = "",
241
+ failure_response: str = "FAILURE",
242
+ declined_response: str = "APPROVED",
243
+ support_get_method: bool = False,
244
+ ) -> None:
245
+ self._gateway = gateway
246
+ self._validate_order = validate_order
247
+ self._on_success = on_success
248
+ self._on_failure = on_failure
249
+ self._success_response = success_response
250
+ self._failure_response = failure_response
251
+ self._declined_response = declined_response
252
+ self._support_get_method = bool(support_get_method)
253
+ self._warned_no_validate_order = False
254
+ if self._support_get_method:
255
+ logger.warning(
256
+ "CMI: 'support_get_method' is enabled. Callback parameters (payment data included) "
257
+ "will be accepted from URL query strings: make sure your access logs and CDN do not keep them."
258
+ )
259
+
260
+ @property
261
+ def supports_get_method(self) -> bool:
262
+ """Whether callback parameters may be read from the query string of a GET request."""
263
+ return self._support_get_method
264
+
265
+ # ------------------------------------------------------------------ answers
266
+
267
+ def get_response(self, result: CallbackResult) -> CallbackAnswer:
268
+ """The answer CMI expects for this result (as in CMI's reference callback.php):
269
+
270
+ - approved payment: ``ACTION=POSTAUTH`` or ``APPROVED`` (confirmation mode), or ``success_response``
271
+ - authentic decline: ``APPROVED`` (acknowledgement), or ``declined_response``
272
+ - invalid hash, technical error or rejected order: ``FAILURE``, or ``failure_response``
273
+ """
274
+ if result.success:
275
+ return CallbackAnswer(200, self._success_response or result.status)
276
+ if result.status == "DECLINED" and result.verified:
277
+ return CallbackAnswer(200, self._declined_response)
278
+ return CallbackAnswer(200, self._failure_response)
279
+
280
+ def error_response(self) -> CallbackAnswer:
281
+ """The answer sent when handling the callback raised unexpectedly."""
282
+ return CallbackAnswer(500, self._failure_response)
283
+
284
+ # ------------------------------------------------------------------ order check
285
+
286
+ def _without_validate_order(self, result: CallbackResult) -> CallbackResult:
287
+ if not self._warned_no_validate_order:
288
+ self._warned_no_validate_order = True
289
+ mode = self._gateway.confirmation_mode
290
+ effect = (
291
+ "Payments are captured"
292
+ if mode == "auto"
293
+ else "Payments are approved (and on_success runs for every replayed callback)"
294
+ )
295
+ logger.warning(
296
+ "CMI: confirmation_mode is '%s' but no validate_order was given. %s without checking that "
297
+ "the order exists, matches the amount and was not already paid. Pass validate_order to "
298
+ "check the order before CMI is answered.",
299
+ mode,
300
+ effect,
301
+ )
302
+ return result
303
+
304
+ @staticmethod
305
+ def _order_checked(result: CallbackResult, accepted: Any, reason: str) -> CallbackResult:
306
+ if accepted is True:
307
+ return result
308
+ return CallbackResult(
309
+ success=False,
310
+ status="FAILURE",
311
+ verified=result.verified,
312
+ message=f"Order validation failed ({reason})",
313
+ order_data=result.order_data,
314
+ error_code=result.error_code,
315
+ error_message=result.error_message,
316
+ )
317
+
318
+ def _verify_and_validate(self, params: Mapping[str, Any]) -> CallbackResult:
319
+ result = self._gateway.verify_callback(params)
320
+ if not result.success:
321
+ return result
322
+ if self._validate_order is None:
323
+ return self._without_validate_order(result)
324
+ accepted: Any = False
325
+ reason = "validate_order did not return True"
326
+ try:
327
+ accepted = self._validate_order(result)
328
+ if inspect.isawaitable(accepted):
329
+ _discard(accepted)
330
+ accepted = False
331
+ reason = "validate_order is async: use handle_async()/evaluate_async() or the Starlette adapter"
332
+ logger.error("CMI: %s", reason)
333
+ except Exception as error: # noqa: BLE001 - a failing check refuses the payment
334
+ reason = f"validate_order raised {type(error).__name__}: {error}"
335
+ logger.error("CMI: order validation error: %s", reason)
336
+ return self._order_checked(result, accepted, reason)
337
+
338
+ async def _verify_and_validate_async(self, params: Mapping[str, Any]) -> CallbackResult:
339
+ result = self._gateway.verify_callback(params)
340
+ if not result.success:
341
+ return result
342
+ if self._validate_order is None:
343
+ return self._without_validate_order(result)
344
+ accepted: Any = False
345
+ reason = "validate_order did not return True"
346
+ try:
347
+ accepted = self._validate_order(result)
348
+ if inspect.isawaitable(accepted):
349
+ accepted = await accepted
350
+ except Exception as error: # noqa: BLE001 - a failing check refuses the payment
351
+ reason = f"validate_order raised {type(error).__name__}: {error}"
352
+ logger.error("CMI: order validation error: %s", reason)
353
+ return self._order_checked(result, accepted, reason)
354
+
355
+ # ------------------------------------------------------------------ public API
356
+
357
+ def evaluate(self, params: Mapping[str, Any]) -> tuple[CallbackResult, CallbackAnswer]:
358
+ """Verify the callback and work out the answer for CMI, without running
359
+ ``on_success`` / ``on_failure``. Send the answer first, then call :meth:`notify`,
360
+ so a slow hook cannot delay CMI's answer."""
361
+ result = self._verify_and_validate(params)
362
+ return result, self.get_response(result)
363
+
364
+ async def evaluate_async(self, params: Mapping[str, Any]) -> tuple[CallbackResult, CallbackAnswer]:
365
+ """Async :meth:`evaluate`: ``validate_order`` may be an ``async def``."""
366
+ result = await self._verify_and_validate_async(params)
367
+ return result, self.get_response(result)
368
+
369
+ def notify(self, result: CallbackResult) -> None:
370
+ """Run ``on_success`` or ``on_failure``. Their exceptions are logged and never propagate."""
371
+ hook = self._on_success if result.success else self._on_failure
372
+ if hook is None:
373
+ return
374
+ try:
375
+ outcome = hook(result)
376
+ if inspect.isawaitable(outcome):
377
+ _discard(outcome)
378
+ logger.error(
379
+ "CMI: %s is async: use handle_async()/notify_async() or the Starlette adapter",
380
+ "on_success" if result.success else "on_failure",
381
+ )
382
+ except Exception as error: # noqa: BLE001 - the answer to CMI must not depend on user code
383
+ logger.error("CMI: callback hook error (CMI answer not affected): %s: %s", type(error).__name__, error)
384
+
385
+ async def notify_async(self, result: CallbackResult) -> None:
386
+ """Async :meth:`notify`: hooks may be ``async def`` or plain functions."""
387
+ hook = self._on_success if result.success else self._on_failure
388
+ if hook is None:
389
+ return
390
+ try:
391
+ outcome = hook(result)
392
+ if inspect.isawaitable(outcome):
393
+ await outcome
394
+ except Exception as error: # noqa: BLE001 - the answer to CMI must not depend on user code
395
+ logger.error("CMI: callback hook error (CMI answer not affected): %s: %s", type(error).__name__, error)
396
+
397
+ def handle(self, params: Mapping[str, Any]) -> CallbackResult:
398
+ """Verify, check the order and run the hooks; return the result.
399
+
400
+ Answer CMI with ``handler.get_response(result)`` afterwards.
401
+ """
402
+ result, _ = self.evaluate(params)
403
+ self.notify(result)
404
+ return result
405
+
406
+ async def handle_async(self, params: Mapping[str, Any]) -> CallbackResult:
407
+ """Async :meth:`handle`."""
408
+ result, _ = await self.evaluate_async(params)
409
+ await self.notify_async(result)
410
+ return result
411
+
412
+
413
+ def _discard(awaitable: Any) -> None:
414
+ """Close a coroutine that will never be awaited (avoids a "never awaited" warning)."""
415
+ close = getattr(awaitable, "close", None)
416
+ if callable(close):
417
+ close()
@@ -0,0 +1,216 @@
1
+ """CMIPaymentGateway: the Standard kit's entry point (CMI's hosted payment page)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any, NoReturn
7
+
8
+ from .._log import logger
9
+ from .._security import SecretString, assert_server_runtime
10
+ from ..constants import AccountType, ConfirmationMode
11
+ from ._builder import PaymentBuilder
12
+ from ._form import generate_form, generate_inputs
13
+ from ._validators import normalize_config, validate_account_type, validate_config, validate_confirmation_mode
14
+ from .callback import CallbackHandler, CallbackResult, CallbackVerifier
15
+
16
+ __all__ = ["MIN_STORE_KEY_LENGTH", "CMIPaymentGateway"]
17
+
18
+ #: Below this length a warning is logged: CMI's ver3 hash is unsalted, so a short store key
19
+ #: can be guessed offline from any one payment form.
20
+ MIN_STORE_KEY_LENGTH = 16
21
+ _warned_weak_key = False
22
+
23
+
24
+ def _warn_if_weak_store_key(store_key: SecretString) -> None:
25
+ global _warned_weak_key
26
+ if _warned_weak_key or len(store_key) >= MIN_STORE_KEY_LENGTH:
27
+ return
28
+ _warned_weak_key = True
29
+ logger.warning(
30
+ "CMI store key is shorter than %d characters. The hash in every payment form can be used to "
31
+ "guess a short key offline: set a long random store key in the CMI back office.",
32
+ MIN_STORE_KEY_LENGTH,
33
+ )
34
+
35
+
36
+ class CMIPaymentGateway:
37
+ """CMI payment gateway, Standard kit: the customer pays on CMI's hosted payment page.
38
+
39
+ 1. Build the signed parameters: :meth:`create_payment_params`.
40
+ 2. Answer the browser with the auto-submitting form: :meth:`generate_payment_form`.
41
+ 3. The customer pays on CMI's page (3-D Secure included).
42
+ 4. CMI posts the result to your ``callback_url``, server to server: verify it with
43
+ :meth:`verify_callback` or a :class:`CallbackHandler` / framework adapter, and answer CMI.
44
+ 5. CMI sends the customer back to your ``okUrl`` or ``failUrl``.
45
+
46
+ The store key is a secret: whoever has it can forge a "paid" callback. It is kept in a
47
+ :class:`SecretString`, never logged, and masked in ``repr()``; the gateway cannot be pickled.
48
+
49
+ Example::
50
+
51
+ gateway = CMIPaymentGateway(
52
+ store_key=os.environ["CMI_STORE_KEY"],
53
+ client_id=os.environ["CMI_CLIENT_ID"],
54
+ gateway_url="https://testpayment.cmi.co.ma/fim/est3Dgate",
55
+ storetype="3d_pay_hosting",
56
+ trantype="PreAuth",
57
+ callback_url="https://api.example.ma/cmi/callback",
58
+ confirmation_mode="auto",
59
+ )
60
+ """
61
+
62
+ __slots__ = (
63
+ "__store_key",
64
+ "_account_type",
65
+ "_builder",
66
+ "_callback_url",
67
+ "_client_id",
68
+ "_confirmation_mode",
69
+ "_gateway_url",
70
+ "_storetype",
71
+ "_trantype",
72
+ "_verifier",
73
+ )
74
+
75
+ def __init__(
76
+ self,
77
+ *,
78
+ store_key: str,
79
+ client_id: str | int,
80
+ gateway_url: str,
81
+ storetype: str,
82
+ trantype: str,
83
+ callback_url: str | None = None,
84
+ confirmation_mode: ConfirmationMode | str | None = None,
85
+ account_type: AccountType | str | None = None,
86
+ ) -> None:
87
+ """
88
+ :param store_key: Secret key from CMI. Read it from a server-side environment variable.
89
+ :param client_id: Merchant ID from CMI (digits only).
90
+ :param gateway_url: CMI gateway URL, ``https://`` only (plain http only for localhost).
91
+ :param storetype: ``3d_pay_hosting``, ``3d``, ``pay_hosting``... (case-insensitive).
92
+ :param trantype: ``PreAuth``, ``Auth``... (case-insensitive).
93
+ :param callback_url: Where CMI posts the result, ``https://`` only. Without it, confirm
94
+ payments in CMI's back office.
95
+ :param confirmation_mode: ``"auto"``: approved payments are captured (CMI is answered
96
+ ``ACTION=POSTAUTH``). ``"manual"`` (default): they stay pre-authorized (``APPROVED``);
97
+ capture them later with the API kit or the back office.
98
+ :param account_type: ``"inshore"`` (default, MAD) or ``"offshore"`` (foreign currency).
99
+ """
100
+ assert_server_runtime()
101
+ key, client, url, store_type, tran_type, callback = validate_config(
102
+ store_key=store_key,
103
+ client_id=client_id,
104
+ gateway_url=gateway_url,
105
+ storetype=storetype,
106
+ trantype=trantype,
107
+ callback_url=callback_url,
108
+ )
109
+ self._confirmation_mode: ConfirmationMode = validate_confirmation_mode(confirmation_mode)
110
+ self._account_type: AccountType = validate_account_type(account_type)
111
+ self.__store_key = SecretString(key)
112
+ _warn_if_weak_store_key(self.__store_key)
113
+
114
+ self._client_id = client
115
+ self._gateway_url = url
116
+ self._storetype = store_type
117
+ self._trantype = tran_type
118
+ self._callback_url = callback
119
+ self._builder = PaymentBuilder(
120
+ client_id=client,
121
+ store_key=self.__store_key,
122
+ storetype=store_type,
123
+ trantype=tran_type,
124
+ account_type=self._account_type,
125
+ callback_url=callback,
126
+ )
127
+ self._verifier = CallbackVerifier(store_key=self.__store_key, confirmation_mode=self._confirmation_mode)
128
+
129
+ @classmethod
130
+ def from_dict(cls, config: Mapping[str, Any]) -> CMIPaymentGateway:
131
+ """Create a gateway from a mapping (a settings dict, a parsed JSON or YAML file...).
132
+
133
+ Keys are matched case-insensitively and with or without underscores, so cmi-node's
134
+ ``storeKey`` / ``gatewayUrl`` spellings work too. Unknown or duplicate keys are
135
+ rejected, so a typo fails at startup.
136
+ """
137
+ return cls(**normalize_config(config))
138
+
139
+ # ------------------------------------------------------------------ payment page
140
+
141
+ def create_payment_params(self, request: Mapping[str, Any] | None = None, /, **fields: Any) -> dict[str, str]:
142
+ """Build the parameters to post to CMI, ``hash`` included.
143
+
144
+ Give the fields as a mapping, as keyword arguments, or both. Field names are CMI's
145
+ (``amount``, ``currency``, ``BillToName``, ``email``, ``okUrl``, ``failUrl``,
146
+ ``shopUrl``, ``oid``, ``lang``...), compared case-insensitively. Other fields
147
+ (``id1``, ``qty1``, ``price1``...) are posted as they are and included in the hash.
148
+
149
+ :returns: Exactly what is posted to CMI, every value as text.
150
+ :raises CMIValidationError: when a field is missing or invalid.
151
+ """
152
+ merged: dict[str, Any] = dict(request) if request is not None else {}
153
+ for key, value in fields.items():
154
+ if key in merged:
155
+ raise TypeError(f"Field {key!r} given both in the mapping and as a keyword argument")
156
+ merged[key] = value
157
+ return self._builder.build(merged)
158
+
159
+ def generate_payment_form(self, params: Mapping[str, Any], *, nonce: str | None = None) -> str:
160
+ """The HTML page that posts ``params`` to CMI by itself (with a "Continue" button
161
+ when JavaScript is off). Pass your CSP ``nonce`` under a strict Content-Security-Policy."""
162
+ return generate_form(self._gateway_url, params, nonce)
163
+
164
+ def generate_payment_inputs(self, params: Mapping[str, Any]) -> list[str]:
165
+ """Only the escaped hidden ``<input>`` elements, to build your own form."""
166
+ return generate_inputs(params)
167
+
168
+ # ------------------------------------------------------------------ callback
169
+
170
+ def verify_callback(self, params: Mapping[str, Any]) -> CallbackResult:
171
+ """Verify a callback (or okUrl/failUrl request) from CMI: check its HASH and read it.
172
+
173
+ ``params`` are the posted form fields; list values (a repeated field) keep their
174
+ last value. Use :func:`cmi.parse_form_body` for a raw request body.
175
+ """
176
+ return self._verifier.verify(params)
177
+
178
+ def create_callback_handler(self, **options: Any) -> CallbackHandler:
179
+ """A :class:`CallbackHandler` for this gateway (``validate_order``, ``on_success``,
180
+ ``on_failure``, ``success_response``, ``failure_response``, ``declined_response``,
181
+ ``support_get_method``)."""
182
+ return CallbackHandler(self, **options)
183
+
184
+ # ------------------------------------------------------------------ settings
185
+
186
+ @property
187
+ def confirmation_mode(self) -> ConfirmationMode:
188
+ return self._confirmation_mode
189
+
190
+ def get_confirmation_mode(self) -> ConfirmationMode:
191
+ return self._confirmation_mode
192
+
193
+ @property
194
+ def gateway_url(self) -> str:
195
+ return self._gateway_url
196
+
197
+ def get_config(self) -> dict[str, Any]:
198
+ """The settings, without the store key."""
199
+ return {
200
+ "client_id": self._client_id,
201
+ "gateway_url": self._gateway_url,
202
+ "storetype": self._storetype,
203
+ "trantype": self._trantype,
204
+ "callback_url": self._callback_url,
205
+ "confirmation_mode": self._confirmation_mode,
206
+ "account_type": self._account_type,
207
+ }
208
+
209
+ def __repr__(self) -> str:
210
+ return (
211
+ f"CMIPaymentGateway(client_id={self._client_id!r}, gateway_url={self._gateway_url!r}, "
212
+ f"store_key='********', confirmation_mode={self._confirmation_mode!r})"
213
+ )
214
+
215
+ def __reduce__(self) -> NoReturn:
216
+ raise TypeError("CMIPaymentGateway cannot be pickled: it holds the CMI store key")