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/api/types.py ADDED
@@ -0,0 +1,144 @@
1
+ """Result types of the API kit (CMI's back-office XML API, CC5)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from dataclasses import dataclass, field
7
+ from decimal import Decimal
8
+ from typing import Literal
9
+
10
+ __all__ = [
11
+ "CMIApiResponse",
12
+ "CMIOrderHistoryEntry",
13
+ "CMIOrderHistoryResult",
14
+ "CMIOrderStatus",
15
+ "CMIOrderStatusResult",
16
+ "CMIOrderTransaction",
17
+ "CMITransactionResult",
18
+ ]
19
+
20
+ #: Status of an order transaction, from CMI's TRANS_STAT and CHARGE_TYPE_CD.
21
+ #:
22
+ #: - ``declined`` (D), ``preauthorized`` (A), ``captured`` (C), ``settled`` (S)
23
+ #: - ``refunded`` (C or S on a refund line), ``voided`` (V)
24
+ #: - ``pending`` (PN), ``reversal_required`` (R), ``processing`` (NW): not final yet, query again
25
+ #: - ``error`` (ERR) and ``cancelled`` (CNCL): recurring orders
26
+ #: - ``unknown``: a code this SDK does not know
27
+ CMIOrderStatus = Literal[
28
+ "declined",
29
+ "preauthorized",
30
+ "captured",
31
+ "settled",
32
+ "refunded",
33
+ "voided",
34
+ "pending",
35
+ "reversal_required",
36
+ "processing",
37
+ "error",
38
+ "cancelled",
39
+ "unknown",
40
+ ]
41
+
42
+
43
+ @dataclass(frozen=True, kw_only=True)
44
+ class CMIApiResponse:
45
+ """What every CMI API answer carries."""
46
+
47
+ #: CMI's ``Response``: "Approved", "Declined" or "Error".
48
+ response: str
49
+ #: CMI's ``ProcReturnCode``: "00" approved, "99" gateway error, other values are bank codes.
50
+ proc_return_code: str
51
+ #: ``ErrMsg``: the error text, or for queries "Record(s) found for ...".
52
+ message: str | None = None
53
+ #: ``Extra.ERRORCODE``, when CMI sends one (e.g. "CORE-2008").
54
+ error_code: str | None = None
55
+ #: ``OrderId`` as answered by CMI.
56
+ order_id: str | None = None
57
+ #: Every top-level element of the answer, as text.
58
+ fields: Mapping[str, str] = field(default_factory=dict, repr=False)
59
+ #: Every child of ``<Extra>``, as text.
60
+ extra: Mapping[str, str] = field(default_factory=dict, repr=False)
61
+
62
+
63
+ @dataclass(frozen=True, kw_only=True)
64
+ class CMITransactionResult(CMIApiResponse):
65
+ """Answer to a PostAuth (capture), refund (Credit) or Void."""
66
+
67
+ #: True when CMI answered ``Response=Approved`` with ``ProcReturnCode=00``.
68
+ approved: bool = False
69
+ trans_id: str | None = None
70
+ group_id: str | None = None
71
+ auth_code: str | None = None
72
+ host_ref_num: str | None = None
73
+ #: ``Extra.SETTLEID``.
74
+ settle_id: str | None = None
75
+ #: ``Extra.TRXDATE``, as sent by CMI ("yyyyMMdd HH:mm:ss", Morocco time).
76
+ transaction_date: str | None = None
77
+ #: ``Extra.CARDBRAND``, e.g. "VISA".
78
+ card_brand: str | None = None
79
+ #: ``Extra.CARDISSUER``.
80
+ card_issuer: str | None = None
81
+
82
+
83
+ @dataclass(frozen=True, kw_only=True)
84
+ class CMIOrderTransaction:
85
+ """One transaction of an order, as reported by the status and history queries."""
86
+
87
+ status: CMIOrderStatus
88
+ #: CMI's TRANS_STAT code (D, A, C, S, PN, V, R, NW, ERR, CNCL).
89
+ status_code: str
90
+ #: CMI's CHARGE_TYPE_CD: "S" for an authorization/capture, "C" for a refund.
91
+ charge_type: str
92
+ #: True when the goods can be shipped (captured or settled payment).
93
+ shipment_possible: bool
94
+ #: True for a temporary state (pending, reversal required, processing): query again later.
95
+ transient: bool
96
+ #: Authorized amount (ORIG_TRANS_AMT, converted from cents).
97
+ original_amount: Decimal | None = None
98
+ #: Captured amount (CAPTURE_AMT, converted from cents).
99
+ captured_amount: Decimal | None = None
100
+ #: AUTH_DTTM, as sent by CMI ("yyyy-MM-dd HH:mm:ss.S", Morocco time).
101
+ authorized_at: str | None = None
102
+ #: CAPTURE_DTTM, as sent by CMI.
103
+ captured_at: str | None = None
104
+ #: VOID_DTTM (history only), as sent by CMI.
105
+ voided_at: str | None = None
106
+ auth_code: str | None = None
107
+ host_ref_num: str | None = None
108
+ #: PROC_RET_CD: the bank's return code for this transaction ("00" approved).
109
+ host_return_code: str | None = None
110
+ trans_id: str | None = None
111
+ settle_id: str | None = None
112
+ xid: str | None = None
113
+ cavv: str | None = None
114
+ eci: str | None = None
115
+ md_status: str | None = None
116
+
117
+
118
+ @dataclass(frozen=True, kw_only=True)
119
+ class CMIOrderStatusResult(CMIApiResponse):
120
+ """Answer to an order status query."""
121
+
122
+ #: True when CMI found the order.
123
+ found: bool = False
124
+ #: The order's last successful transaction, or its last failed one when none succeeded.
125
+ transaction: CMIOrderTransaction | None = None
126
+ #: Masked card number (Extra.PAN), e.g. "4000 00** **** 0010".
127
+ masked_pan: str | None = field(default=None, repr=False)
128
+
129
+
130
+ @dataclass(frozen=True, kw_only=True)
131
+ class CMIOrderHistoryEntry(CMIOrderTransaction):
132
+ """One line of an order history."""
133
+
134
+ #: The TRXn line as sent by CMI.
135
+ raw: str = ""
136
+
137
+
138
+ @dataclass(frozen=True, kw_only=True)
139
+ class CMIOrderHistoryResult(CMIApiResponse):
140
+ """Answer to an order history query."""
141
+
142
+ found: bool = False
143
+ #: Every transaction of the order, in CMI's TRX1..TRXn order.
144
+ transactions: tuple[CMIOrderHistoryEntry, ...] = ()
cmi/constants.py ADDED
@@ -0,0 +1,146 @@
1
+ """Values CMI accepts: currencies, languages, store types, transaction types and modes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from types import MappingProxyType
6
+ from typing import Any, Literal, NamedTuple
7
+
8
+ __all__ = [
9
+ "SUPPORTED_ACCOUNT_TYPES",
10
+ "SUPPORTED_CONFIRMATION_MODES",
11
+ "SUPPORTED_CURRENCIES",
12
+ "SUPPORTED_LANGUAGES",
13
+ "SUPPORTED_STORE_TYPES",
14
+ "SUPPORTED_TRAN_TYPES",
15
+ "AccountType",
16
+ "ConfirmationMode",
17
+ "CurrencyInfo",
18
+ "get_currency_info",
19
+ "is_moroccan_dirham",
20
+ "is_supported_currency",
21
+ "is_supported_language",
22
+ "normalize_currency",
23
+ "normalize_currency_code",
24
+ "normalize_language",
25
+ ]
26
+
27
+
28
+ class CurrencyInfo(NamedTuple):
29
+ code: str
30
+ numeric: str
31
+ name: str
32
+ decimals: int
33
+
34
+
35
+ _CURRENCIES = [
36
+ CurrencyInfo("USD", "840", "United States Dollar", 2),
37
+ CurrencyInfo("EUR", "978", "Euro", 2),
38
+ CurrencyInfo("JPY", "392", "Japanese Yen", 0),
39
+ CurrencyInfo("GBP", "826", "British Pound Sterling", 2),
40
+ CurrencyInfo("CNY", "156", "Chinese Yuan", 2),
41
+ CurrencyInfo("AUD", "036", "Australian Dollar", 2),
42
+ CurrencyInfo("CAD", "124", "Canadian Dollar", 2),
43
+ CurrencyInfo("CHF", "756", "Swiss Franc", 2),
44
+ CurrencyInfo("HKD", "344", "Hong Kong Dollar", 2),
45
+ CurrencyInfo("SGD", "702", "Singapore Dollar", 2),
46
+ CurrencyInfo("SEK", "752", "Swedish Krona", 2),
47
+ CurrencyInfo("KRW", "410", "South Korean Won", 0),
48
+ CurrencyInfo("NOK", "578", "Norwegian Krone", 2),
49
+ CurrencyInfo("NZD", "554", "New Zealand Dollar", 2),
50
+ CurrencyInfo("INR", "356", "Indian Rupee", 2),
51
+ CurrencyInfo("MXN", "484", "Mexican Peso", 2),
52
+ CurrencyInfo("TWD", "901", "New Taiwan Dollar", 2),
53
+ CurrencyInfo("ZAR", "710", "South African Rand", 2),
54
+ CurrencyInfo("BRL", "986", "Brazilian Real", 2),
55
+ CurrencyInfo("DKK", "208", "Danish Krone", 2),
56
+ CurrencyInfo("PLN", "985", "Polish Zloty", 2),
57
+ CurrencyInfo("THB", "764", "Thai Baht", 2),
58
+ CurrencyInfo("IDR", "360", "Indonesian Rupiah", 2),
59
+ CurrencyInfo("HUF", "348", "Hungarian Forint", 2),
60
+ CurrencyInfo("CZK", "203", "Czech Koruna", 2),
61
+ CurrencyInfo("ILS", "376", "Israeli New Shekel", 2),
62
+ CurrencyInfo("CLP", "152", "Chilean Peso", 0),
63
+ CurrencyInfo("PHP", "608", "Philippine Peso", 2),
64
+ CurrencyInfo("AED", "784", "UAE Dirham", 2),
65
+ CurrencyInfo("COP", "170", "Colombian Peso", 2),
66
+ CurrencyInfo("MAD", "504", "Moroccan Dirham", 2),
67
+ CurrencyInfo("SAR", "682", "Saudi Riyal", 2),
68
+ CurrencyInfo("TRY", "949", "Turkish Lira", 2),
69
+ CurrencyInfo("EGP", "818", "Egyptian Pound", 2),
70
+ ]
71
+
72
+ #: Currencies by alphabetic code ("MAD" -> CurrencyInfo("MAD", "504", ...)).
73
+ SUPPORTED_CURRENCIES: MappingProxyType[str, CurrencyInfo] = MappingProxyType({c.code: c for c in _CURRENCIES})
74
+ _BY_NUMERIC = {c.numeric: c for c in _CURRENCIES}
75
+
76
+
77
+ def get_currency_info(value: Any) -> CurrencyInfo | None:
78
+ """Currency details from an alphabetic ("MAD", "mad") or numeric ("504") code."""
79
+ if isinstance(value, bool) or not isinstance(value, (str, int)):
80
+ return None
81
+ text = str(value).upper()
82
+ return SUPPORTED_CURRENCIES.get(text) or _BY_NUMERIC.get(text)
83
+
84
+
85
+ def normalize_currency(currency: Any) -> str | None:
86
+ """Numeric code ("504") of a currency given as "MAD", "504", "mad"..., or None."""
87
+ info = get_currency_info(currency)
88
+ return info.numeric if info else None
89
+
90
+
91
+ def normalize_currency_code(currency: Any) -> str | None:
92
+ """Alphabetic code ("MAD") of a currency given as "MAD", "504", "mad"..., or None."""
93
+ info = get_currency_info(currency)
94
+ return info.code if info else None
95
+
96
+
97
+ def is_moroccan_dirham(currency: Any) -> bool:
98
+ info = get_currency_info(currency)
99
+ return info is not None and info.code == "MAD"
100
+
101
+
102
+ def is_supported_currency(currency: Any) -> bool:
103
+ return normalize_currency(currency) is not None
104
+
105
+
106
+ SUPPORTED_LANGUAGES: tuple[str, ...] = (
107
+ "en", "tr", "ar", "fr", "de", "es", "it", "pt", "ru",
108
+ "zh", "ja", "ko", "nl", "pl", "sv", "no", "da", "fi",
109
+ "cs", "el", "he", "hi", "th", "id", "vi", "uk",
110
+ ) # fmt: skip
111
+
112
+ _LANGUAGE_NAMES = {
113
+ "ENGLISH": "en", "TURKISH": "tr", "ARABIC": "ar", "FRENCH": "fr", "GERMAN": "de",
114
+ "SPANISH": "es", "ITALIAN": "it", "PORTUGUESE": "pt", "RUSSIAN": "ru", "CHINESE": "zh",
115
+ "JAPANESE": "ja", "KOREAN": "ko", "DUTCH": "nl", "POLISH": "pl", "SWEDISH": "sv",
116
+ "NORWEGIAN": "no", "DANISH": "da", "FINNISH": "fi", "CZECH": "cs", "GREEK": "el",
117
+ "HEBREW": "he", "HINDI": "hi", "THAI": "th", "INDONESIAN": "id", "VIETNAMESE": "vi",
118
+ "UKRAINIAN": "uk",
119
+ } # fmt: skip
120
+
121
+
122
+ def normalize_language(lang: Any) -> str | None:
123
+ """Two-letter code from "fr", "FR", "french" or "FRENCH", or None when not supported."""
124
+ if not isinstance(lang, str) or not lang:
125
+ return None
126
+ text = lang.strip()
127
+ if text.lower() in SUPPORTED_LANGUAGES:
128
+ return text.lower()
129
+ return _LANGUAGE_NAMES.get(text.upper())
130
+
131
+
132
+ def is_supported_language(lang: Any) -> bool:
133
+ return normalize_language(lang) is not None
134
+
135
+
136
+ SUPPORTED_STORE_TYPES: tuple[str, ...] = (
137
+ "3d", "3d_pay", "3d_half", "3d_full", "3d_hosting", "3d_pay_hosting", "pay_hosting", "pay", "opt_pay_hosting",
138
+ ) # fmt: skip
139
+
140
+ SUPPORTED_TRAN_TYPES: tuple[str, ...] = ("preauth", "auth", "postauth", "void", "credit")
141
+
142
+ ConfirmationMode = Literal["auto", "manual"]
143
+ SUPPORTED_CONFIRMATION_MODES: tuple[ConfirmationMode, ...] = ("auto", "manual")
144
+
145
+ AccountType = Literal["inshore", "offshore"]
146
+ SUPPORTED_ACCOUNT_TYPES: tuple[AccountType, ...] = ("inshore", "offshore")
cmi/errors.py ADDED
@@ -0,0 +1,52 @@
1
+ """Exceptions raised by the SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal
6
+
7
+ __all__ = ["CMIApiError", "CMIApiErrorCode", "CMIError", "CMIValidationError"]
8
+
9
+
10
+ class CMIError(Exception):
11
+ """Base class of every exception raised by the SDK."""
12
+
13
+
14
+ class CMIValidationError(CMIError, ValueError):
15
+ """A setting or a payment request field is missing or invalid.
16
+
17
+ Raised before anything is sent to CMI, so it is always safe to fix and retry.
18
+ Messages never contain a secret (store key, API password).
19
+ """
20
+
21
+
22
+ CMIApiErrorCode = Literal["TIMEOUT", "NETWORK", "HTTP_STATUS", "INVALID_RESPONSE"]
23
+
24
+
25
+ class CMIApiError(CMIError):
26
+ """No usable answer came back from CMI's XML API.
27
+
28
+ ``code`` is ``TIMEOUT``, ``NETWORK``, ``HTTP_STATUS`` or ``INVALID_RESPONSE``. A declined
29
+ or refused operation is NOT an error: it is a result with ``approved=False``.
30
+
31
+ The request may still have reached CMI. After any CMIApiError on an operation that
32
+ moves money (capture, refund, void), the outcome is unknown: query the order status
33
+ before sending it again, or the money may move twice.
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ code: CMIApiErrorCode,
39
+ operation: str,
40
+ message: str,
41
+ *,
42
+ status: int | None = None,
43
+ ) -> None:
44
+ super().__init__(message)
45
+ self.code: CMIApiErrorCode = code
46
+ #: The operation that failed, e.g. ``"refund"``.
47
+ self.operation = operation
48
+ #: HTTP status, for ``HTTP_STATUS`` errors.
49
+ self.status = status
50
+
51
+ def __repr__(self) -> str:
52
+ return f"CMIApiError(code={self.code!r}, operation={self.operation!r}, message={str(self)!r})"
cmi/py.typed ADDED
File without changes
@@ -0,0 +1,20 @@
1
+ """Standard kit: CMI's hosted payment page.
2
+
3
+ The customer is sent to CMI's payment page with a signed form; CMI calls the shop back
4
+ (``callback_url``) and returns the customer to ``okUrl`` / ``failUrl``.
5
+ Framework adapters: :mod:`cmi.adapters.django`, :mod:`cmi.adapters.flask`,
6
+ :mod:`cmi.adapters.fastapi` (Starlette).
7
+ """
8
+
9
+ from .callback import CallbackAnswer, CallbackHandler, CallbackResult, CallbackStatus, OrderData, parse_form_body
10
+ from .gateway import CMIPaymentGateway
11
+
12
+ __all__ = [
13
+ "CMIPaymentGateway",
14
+ "CallbackAnswer",
15
+ "CallbackHandler",
16
+ "CallbackResult",
17
+ "CallbackStatus",
18
+ "OrderData",
19
+ "parse_form_body",
20
+ ]
@@ -0,0 +1,191 @@
1
+ """Builds the signed parameters posted to CMI's payment page."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import secrets
6
+ import string
7
+ import time
8
+ from collections.abc import Mapping
9
+ from typing import Any
10
+
11
+ from .._amount import format_amount
12
+ from .._compat import js_string, js_to_number, js_trim, php_trim
13
+ from .._log import logger
14
+ from .._security import SecretString
15
+ from ..constants import AccountType, normalize_currency, normalize_currency_code, normalize_language
16
+ from ..errors import CMIValidationError
17
+ from . import _hash
18
+ from ._sanitize import remove_accents, sanitize_email, sanitize_string
19
+ from ._validators import check_duplicate_fields, normalize_request, validate_request
20
+
21
+ #: Optional payment request fields (billing + tel), with their maximum lengths.
22
+ OPTIONAL_PAYMENT_FIELDS = {
23
+ "BillToCompany": 255,
24
+ "BillToStreet1": 255,
25
+ "BillToStreet2": 255,
26
+ "BillToStreet3": 255,
27
+ "BillToCity": 64,
28
+ "BillToCountry": 3,
29
+ "BillToStateProv": 32,
30
+ "BillToPostalCode": 32,
31
+ "BillToTelVoice": 255,
32
+ "description": 125,
33
+ "tel": 32,
34
+ }
35
+
36
+ #: Every field handled explicitly by the builder (never passed through as a custom field).
37
+ STANDARD_PAYMENT_FIELDS = (
38
+ "amount", "oid", "okUrl", "failUrl", "shopUrl", "email", "BillToName", "rnd", "encoding",
39
+ "currency", "lang", "hashAlgorithm", "AutoRedirect", "amountCur", "symbolCur",
40
+ "sessiontimeout", "redirectGet", "CallbackResponse", *OPTIONAL_PAYMENT_FIELDS,
41
+ ) # fmt: skip
42
+ _STANDARD_FIELDS_LOWER = frozenset(f.lower() for f in STANDARD_PAYMENT_FIELDS)
43
+
44
+ #: Billing fields CMI's reference 2.SendData.php cleans with str_without_accents().
45
+ PHP_CLEANED_BILLING_FIELDS = (
46
+ "BillToName",
47
+ "BillToCompany",
48
+ "BillToStreet1",
49
+ "BillToCity",
50
+ "BillToStateProv",
51
+ "BillToPostalCode",
52
+ "BillToCountry",
53
+ )
54
+
55
+ MAX_CUSTOM_FIELD_LENGTH = 255
56
+ _RND_ALPHABET = string.ascii_letters
57
+
58
+
59
+ def generate_order_id() -> str:
60
+ return f"ORD-{int(time.time() * 1000)}-{secrets.token_hex(4).upper()}"
61
+
62
+
63
+ def generate_random() -> str:
64
+ """20 letters (a-zA-Z), as CMI's ``rnd`` field expects."""
65
+ return "".join(secrets.choice(_RND_ALPHABET) for _ in range(20))
66
+
67
+
68
+ def _clean_billing_fields(request: dict[str, Any]) -> dict[str, Any]:
69
+ """Apply str_without_accents() to the billing fields PHP cleans. A required field left
70
+ empty by the cleaning (a name written only in Arabic letters) is an error; an optional
71
+ one is not sent."""
72
+ cleaned = dict(request)
73
+ for field in PHP_CLEANED_BILLING_FIELDS:
74
+ raw = cleaned.get(field)
75
+ if raw is None or isinstance(raw, bool) or not isinstance(raw, (str, int, float)):
76
+ continue # left to the validator
77
+ raw_text = js_string(raw)
78
+ value = remove_accents(raw_text)
79
+ if value == "" and js_trim(raw_text) != "":
80
+ if field == "BillToName":
81
+ # The raw value is not echoed: error messages often end up in logs.
82
+ raise CMIValidationError(
83
+ "BillToName has no character CMI accepts. Use Latin letters, digits, spaces, "
84
+ '"-" or "_" (accents are removed automatically).'
85
+ )
86
+ del cleaned[field]
87
+ continue
88
+ cleaned[field] = value
89
+ return cleaned
90
+
91
+
92
+ class PaymentBuilder:
93
+ """Turns a payment request into the exact parameters posted to CMI, hash included."""
94
+
95
+ __slots__ = ("__store_key", "_account_type", "_callback_url", "_client_id", "_storetype", "_trantype")
96
+
97
+ def __init__(
98
+ self,
99
+ *,
100
+ client_id: str,
101
+ store_key: SecretString,
102
+ storetype: str,
103
+ trantype: str,
104
+ account_type: AccountType,
105
+ callback_url: str | None,
106
+ ) -> None:
107
+ self._client_id = client_id
108
+ self.__store_key = store_key
109
+ self._storetype = storetype
110
+ self._trantype = trantype
111
+ self._account_type = account_type
112
+ self._callback_url = callback_url
113
+
114
+ def build(self, raw_request: Mapping[str, Any]) -> dict[str, str]:
115
+ # None means "not given", as for keyword arguments.
116
+ request = {k: v for k, v in normalize_request(raw_request).items() if v is not None}
117
+ request = _clean_billing_fields(request)
118
+ validate_request(request, self._account_type)
119
+
120
+ params: dict[str, Any] = {
121
+ "oid": request.get("oid") or generate_order_id(),
122
+ "rnd": request.get("rnd") or generate_random(),
123
+ "clientId": self._client_id,
124
+ "trantype": self._trantype,
125
+ "amount": format_amount(request["amount"]),
126
+ "currency": normalize_currency(request["currency"]) or "",
127
+ "storetype": self._storetype.lower(),
128
+ "email": sanitize_email(request["email"]),
129
+ "BillToName": sanitize_string(request["BillToName"], 255),
130
+ "lang": normalize_language(request.get("lang") or "fr"),
131
+ "okUrl": request["okUrl"],
132
+ "failUrl": request["failUrl"],
133
+ "shopUrl": request["shopUrl"],
134
+ "hashAlgorithm": request.get("hashAlgorithm", "ver3"),
135
+ "encoding": request.get("encoding", "UTF-8"),
136
+ }
137
+
138
+ # CallbackResponse=False turns the server-to-server callback off for this payment:
139
+ # the callbackUrl is then not sent.
140
+ if request.get("CallbackResponse") is not False and self._callback_url:
141
+ params["callbackUrl"] = self._callback_url
142
+
143
+ for field, limit in OPTIONAL_PAYMENT_FIELDS.items():
144
+ value = request.get(field)
145
+ if value is not None:
146
+ params[field] = sanitize_string(js_string(value), limit)
147
+
148
+ params["AutoRedirect"] = "true" if request.get("AutoRedirect", False) else "false"
149
+ for field in ("redirectGet", "CallbackResponse", "sessiontimeout"):
150
+ if field in request:
151
+ params[field] = request[field]
152
+
153
+ # Offshore accounts don't use amountCur/symbolCur.
154
+ if self._account_type != "offshore":
155
+ amount_cur = request.get("amountCur")
156
+ if amount_cur is not None and js_to_number(amount_cur) > 0:
157
+ params["amountCur"] = format_amount(amount_cur)
158
+ if "symbolCur" in request:
159
+ params["symbolCur"] = normalize_currency_code(request["symbolCur"]) or ""
160
+
161
+ self._add_custom_fields(params, request)
162
+
163
+ # Post exactly the values that are hashed: PHP-trim every text value, as
164
+ # 2.SendData.php does for both the form and the hash.
165
+ final: dict[str, str] = {}
166
+ for key, value in params.items():
167
+ if value is not None:
168
+ final[key] = php_trim(js_string(value))
169
+
170
+ check_duplicate_fields(final)
171
+ final["hash"] = _hash.generate(final, self.__store_key)
172
+ return final
173
+
174
+ @staticmethod
175
+ def _add_custom_fields(params: dict[str, Any], request: Mapping[str, Any]) -> None:
176
+ existing = {key.lower() for key in params}
177
+ for key, value in request.items():
178
+ lower = key.lower()
179
+ # The hash is always computed by the SDK: a caller-supplied "hash" is dropped.
180
+ if lower == "hash":
181
+ logger.warning("CMI: custom field %r was ignored; the hash is computed by the SDK.", key)
182
+ continue
183
+ if lower in _STANDARD_FIELDS_LOWER or lower in existing or value is None:
184
+ continue
185
+ text = js_string(value)
186
+ if len(text) > MAX_CUSTOM_FIELD_LENGTH:
187
+ logger.warning(
188
+ "CMI: custom field %r exceeded %d characters and was truncated.", key, MAX_CUSTOM_FIELD_LENGTH
189
+ )
190
+ text = text[:MAX_CUSTOM_FIELD_LENGTH]
191
+ params[key] = text