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,389 @@
1
+ """Validation of the gateway configuration and of payment requests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import re
7
+ from collections.abc import Mapping
8
+ from decimal import Decimal
9
+ from typing import Any
10
+
11
+ from .._compat import js_parse_float_prefix, js_to_number, js_trim
12
+ from .._validation import (
13
+ has_http_protocol,
14
+ is_digits,
15
+ is_phone_number,
16
+ is_secure_or_local_url,
17
+ is_valid_email,
18
+ is_valid_redirect_url,
19
+ is_valid_url,
20
+ )
21
+ from ..constants import (
22
+ SUPPORTED_ACCOUNT_TYPES,
23
+ SUPPORTED_CONFIRMATION_MODES,
24
+ SUPPORTED_STORE_TYPES,
25
+ SUPPORTED_TRAN_TYPES,
26
+ AccountType,
27
+ ConfirmationMode,
28
+ is_moroccan_dirham,
29
+ is_supported_currency,
30
+ is_supported_language,
31
+ )
32
+ from ..errors import CMIValidationError
33
+
34
+ # ----------------------------------------------------------------------------- configuration
35
+
36
+ #: Configuration keys accepted by ``CMIPaymentGateway.from_dict()``, compared case-insensitively
37
+ #: and without underscores, so ``storeKey``, ``store_key`` and ``STOREKEY`` are the same field.
38
+ CONFIG_FIELDS = {
39
+ "storekey": "store_key",
40
+ "clientid": "client_id",
41
+ "gatewayurl": "gateway_url",
42
+ "storetype": "storetype",
43
+ "trantype": "trantype",
44
+ "accounttype": "account_type",
45
+ "callbackurl": "callback_url",
46
+ "confirmationmode": "confirmation_mode",
47
+ }
48
+
49
+
50
+ def normalize_config(raw: Mapping[str, Any]) -> dict[str, Any]:
51
+ """Map raw configuration keys to keyword names, rejecting unknown and duplicate fields."""
52
+ if not isinstance(raw, Mapping):
53
+ raise CMIValidationError("The CMI configuration must be a mapping (dict).")
54
+ normalized: dict[str, Any] = {}
55
+ for key, value in raw.items():
56
+ name = CONFIG_FIELDS.get(str(key).replace("_", "").lower())
57
+ if name is None:
58
+ raise CMIValidationError(
59
+ f'Unknown configuration field detected: "{key}". '
60
+ "The configuration must only contain valid schema fields."
61
+ )
62
+ if name in normalized:
63
+ raise CMIValidationError(
64
+ f'Duplicate configuration field detected: "{key}" maps to the same field as a '
65
+ f'previously provided key ("{name}"). Ensure each field is provided only once.'
66
+ )
67
+ normalized[name] = value
68
+ return normalized
69
+
70
+
71
+ def _require_text(value: Any, name: str) -> str:
72
+ if isinstance(value, bool) or value is None or value == "":
73
+ raise CMIValidationError(f"Missing required config field: {name}")
74
+ if name == "client_id" and isinstance(value, int):
75
+ value = str(value)
76
+ if not isinstance(value, str):
77
+ raise CMIValidationError(f"{name} must be a string")
78
+ return value
79
+
80
+
81
+ def validate_config(
82
+ *,
83
+ store_key: Any,
84
+ client_id: Any,
85
+ gateway_url: Any,
86
+ storetype: Any,
87
+ trantype: Any,
88
+ callback_url: Any,
89
+ ) -> tuple[str, str, str, str, str, str | None]:
90
+ """Validate the gateway settings and return them as (store_key, client_id, gateway_url,
91
+ storetype, trantype, callback_url)."""
92
+ store_key = _require_text(store_key, "store_key")
93
+ client_id = _require_text(client_id, "client_id")
94
+ gateway_url = _require_text(gateway_url, "gateway_url")
95
+ storetype = _require_text(storetype, "storetype")
96
+ trantype = _require_text(trantype, "trantype")
97
+
98
+ if not is_digits(client_id):
99
+ raise CMIValidationError(f"client_id must be numeric: {client_id}")
100
+ client_id = js_trim(client_id)
101
+
102
+ if not is_valid_url(gateway_url) or not has_http_protocol(gateway_url):
103
+ raise CMIValidationError(f"Invalid gateway_url: {gateway_url} or missing http/https protocol")
104
+ if not is_secure_or_local_url(gateway_url):
105
+ raise CMIValidationError(
106
+ f"gateway_url must use https:// (got {gateway_url}). Plain http is only allowed for localhost."
107
+ )
108
+
109
+ if callback_url is not None and callback_url != "":
110
+ if not isinstance(callback_url, str) or not is_valid_url(callback_url) or not has_http_protocol(callback_url):
111
+ raise CMIValidationError(f"Invalid callback_url: {callback_url} or missing http/https protocol")
112
+ if not is_secure_or_local_url(callback_url):
113
+ raise CMIValidationError(
114
+ f"callback_url must use https:// (got {callback_url}). Plain http is only allowed for localhost."
115
+ )
116
+ else:
117
+ callback_url = None
118
+
119
+ if storetype.lower() not in SUPPORTED_STORE_TYPES:
120
+ raise CMIValidationError(
121
+ f'Unsupported store type: "{storetype}". '
122
+ f"Supported types (case-insensitive): {', '.join(SUPPORTED_STORE_TYPES)}"
123
+ )
124
+ if trantype.lower() not in SUPPORTED_TRAN_TYPES:
125
+ raise CMIValidationError(
126
+ f'Unsupported transaction type: "{trantype}". '
127
+ f"Supported types (case-insensitive): {', '.join(SUPPORTED_TRAN_TYPES)}"
128
+ )
129
+ return store_key, client_id, gateway_url, storetype, trantype, callback_url
130
+
131
+
132
+ def validate_account_type(value: Any) -> AccountType:
133
+ if value is None or value == "":
134
+ return "inshore"
135
+ normalized = value.lower() if isinstance(value, str) else None
136
+ for account_type in SUPPORTED_ACCOUNT_TYPES:
137
+ if normalized == account_type:
138
+ return account_type
139
+ raise CMIValidationError(
140
+ f'Unsupported account type: "{value}". Supported types: {", ".join(SUPPORTED_ACCOUNT_TYPES)}'
141
+ )
142
+
143
+
144
+ def validate_confirmation_mode(value: Any) -> ConfirmationMode:
145
+ if value is None or value == "":
146
+ return "manual"
147
+ normalized = value.lower() if isinstance(value, str) else None
148
+ for mode in SUPPORTED_CONFIRMATION_MODES:
149
+ if normalized == mode:
150
+ return mode
151
+ raise CMIValidationError(
152
+ f'Unsupported confirmation mode: "{value}". '
153
+ f"Supported modes (case-insensitive): {', '.join(SUPPORTED_CONFIRMATION_MODES)}"
154
+ )
155
+
156
+
157
+ # ----------------------------------------------------------------------------- payment requests
158
+
159
+ #: Lower-cased field name -> canonical CMI name. Other (custom) fields are kept as they are.
160
+ PAYMENT_REQUEST_FIELDS = {
161
+ "amount": "amount",
162
+ "oid": "oid",
163
+ "okurl": "okUrl",
164
+ "failurl": "failUrl",
165
+ "shopurl": "shopUrl",
166
+ "email": "email",
167
+ "billtoname": "BillToName",
168
+ "currency": "currency",
169
+ "lang": "lang",
170
+ "hashalgorithm": "hashAlgorithm",
171
+ "tel": "tel",
172
+ "rnd": "rnd",
173
+ "encoding": "encoding",
174
+ "autoredirect": "AutoRedirect",
175
+ "billtocity": "BillToCity",
176
+ "billtocountry": "BillToCountry",
177
+ "billtostreet1": "BillToStreet1",
178
+ "billtostateprov": "BillToStateProv",
179
+ "billtopostalcode": "BillToPostalCode",
180
+ "billtotelvoice": "BillToTelVoice",
181
+ "billtocompany": "BillToCompany",
182
+ "billtostreet2": "BillToStreet2",
183
+ "billtostreet3": "BillToStreet3",
184
+ "amountcur": "amountCur",
185
+ "symbolcur": "symbolCur",
186
+ "description": "description",
187
+ "sessiontimeout": "sessiontimeout",
188
+ "redirectget": "redirectGet",
189
+ "callbackresponse": "CallbackResponse",
190
+ }
191
+
192
+ _BILLING_LIMITS = (
193
+ ("BillToCompany", 255),
194
+ ("BillToStreet1", 255),
195
+ ("BillToStreet2", 255),
196
+ ("BillToStreet3", 255),
197
+ ("BillToCity", 64),
198
+ ("BillToStateProv", 32),
199
+ ("BillToPostalCode", 32),
200
+ ("BillToCountry", 3),
201
+ )
202
+
203
+ _AMOUNT_TEXT = re.compile(r"-?[0-9]*\.?[0-9]+", re.ASCII)
204
+
205
+
206
+ def normalize_request(raw: Mapping[str, Any]) -> dict[str, Any]:
207
+ """Known fields (``shopurl``, ``OKURL``...) get their canonical name (``shopUrl``, ``okUrl``);
208
+ custom fields are kept as they are. Two keys for the same field are an error."""
209
+ if not isinstance(raw, Mapping):
210
+ raise CMIValidationError("The payment request must be a mapping (dict).")
211
+ normalized: dict[str, Any] = {}
212
+ for key, value in raw.items():
213
+ if not isinstance(key, str):
214
+ raise CMIValidationError(f"Payment request field names must be strings (got {key!r}).")
215
+ canonical = PAYMENT_REQUEST_FIELDS.get(key.lower(), key)
216
+ if canonical in normalized:
217
+ raise CMIValidationError(
218
+ f'Duplicate field detected: "{key}" maps to the same field as a previously provided key '
219
+ f'("{canonical}"). Ensure each field is provided only once.'
220
+ )
221
+ normalized[canonical] = value
222
+ return normalized
223
+
224
+
225
+ def check_duplicate_fields(fields: Mapping[str, Any]) -> None:
226
+ """Field names must be unique case-insensitively ("BillToName" and "billtoname" clash)."""
227
+ seen: set[str] = set()
228
+ duplicates: list[str] = []
229
+ for key in fields:
230
+ lower = key.lower()
231
+ if lower in seen:
232
+ duplicates.append(key)
233
+ else:
234
+ seen.add(lower)
235
+ if duplicates:
236
+ raise CMIValidationError(
237
+ f"Duplicate fields detected (case-insensitive): {', '.join(duplicates)}. "
238
+ "Ensure each field is provided only once."
239
+ )
240
+
241
+
242
+ def _is_blank(value: Any) -> bool:
243
+ return not isinstance(value, str) or js_trim(value) == ""
244
+
245
+
246
+ def validate_request(request: Mapping[str, Any], account_type: AccountType = "inshore") -> None:
247
+ """Validate a normalized payment request (see :func:`normalize_request`)."""
248
+ check_duplicate_fields(request)
249
+
250
+ amount = request.get("amount")
251
+ if amount is None:
252
+ raise CMIValidationError("Amount is required")
253
+ if isinstance(amount, str):
254
+ if not _AMOUNT_TEXT.fullmatch(js_trim(amount)):
255
+ raise CMIValidationError(f'Invalid amount format: "{amount}". Amount must contain only numeric characters.')
256
+ prefix = js_parse_float_prefix(amount)
257
+ numeric = float(prefix) if prefix is not None else math.nan
258
+ elif isinstance(amount, (int, float, Decimal)) and not isinstance(amount, bool):
259
+ numeric = float(amount)
260
+ else:
261
+ raise CMIValidationError(f'Invalid amount: "{amount}". Must be a valid number.')
262
+ if math.isnan(numeric) or math.isinf(numeric):
263
+ raise CMIValidationError(f'Invalid amount: "{amount}". Must be a valid number.')
264
+ if numeric < 1:
265
+ raise CMIValidationError("Amount must be greater than or equal to 1")
266
+
267
+ redirect_help = "Must be a valid http/https URL or a mobile deeplink (e.g., myapp://success)"
268
+ for name in ("shopUrl", "okUrl", "failUrl"):
269
+ value = request.get(name)
270
+ if not value or not is_valid_redirect_url(value):
271
+ raise CMIValidationError(f"Valid {name} is required. {redirect_help}")
272
+
273
+ email = request.get("email")
274
+ if not email or not is_valid_email(email):
275
+ raise CMIValidationError("Valid email is required")
276
+ if len(email) > 64:
277
+ raise CMIValidationError("email cannot exceed 64 characters")
278
+
279
+ bill_to_name = request.get("BillToName")
280
+ if not isinstance(bill_to_name, str) or js_trim(bill_to_name) == "":
281
+ raise CMIValidationError("BillToName is required")
282
+ if len(bill_to_name) > 255:
283
+ raise CMIValidationError("BillToName cannot exceed 255 characters")
284
+
285
+ currency = request.get("currency")
286
+ if not currency or not is_supported_currency(currency):
287
+ raise CMIValidationError(
288
+ f'Unsupported currency: {currency}. Must be a valid currency code (e.g., "MAD") or numeric '
289
+ 'code (e.g., "504"). Check the supported currencies list.'
290
+ )
291
+
292
+ amount_cur = request.get("amountCur")
293
+ symbol_cur = request.get("symbolCur")
294
+ is_mad = is_moroccan_dirham(currency)
295
+ if account_type == "inshore":
296
+ if not is_mad:
297
+ raise CMIValidationError(
298
+ "Inshore accounts only accept MAD as the processing currency.\n"
299
+ 'Use currency: "504" or "MAD".\n'
300
+ "For multi-currency display, use amountCur and symbolCur fields."
301
+ )
302
+ elif is_mad:
303
+ raise CMIValidationError("Offshore accounts cannot use MAD as processing currency.")
304
+ elif amount_cur is not None or symbol_cur is not None:
305
+ raise CMIValidationError(
306
+ "Offshore accounts cannot use amountCur or symbolCur fields because they "
307
+ "already use a custom processing currency."
308
+ )
309
+
310
+ has_amount_cur = amount_cur is not None and js_to_number(amount_cur) > 0
311
+ has_symbol_cur = isinstance(symbol_cur, str) and js_trim(symbol_cur) != ""
312
+ if has_amount_cur != has_symbol_cur:
313
+ raise CMIValidationError(
314
+ "amountCur and symbolCur must be provided together.\n"
315
+ "Either provide both (for foreign currency display) or neither (MAD only)."
316
+ )
317
+ if has_symbol_cur:
318
+ if not is_supported_currency(symbol_cur):
319
+ raise CMIValidationError(f"Invalid symbolCur: {symbol_cur}. Must be a valid currency code.")
320
+ if is_moroccan_dirham(symbol_cur):
321
+ raise CMIValidationError(
322
+ "symbolCur should not be MAD since the main currency is already MAD.\n"
323
+ "For MAD-only payments, omit amountCur and symbolCur fields."
324
+ )
325
+
326
+ lang = request.get("lang")
327
+ if lang and not is_supported_language(lang):
328
+ raise CMIValidationError(f"Unsupported language: {lang}. Check the supported languages list.")
329
+
330
+ if request.get("phone"):
331
+ raise CMIValidationError("The 'phone' field is not supported by CMI. Use 'tel' instead.")
332
+
333
+ tel = request.get("tel")
334
+ if tel:
335
+ if not isinstance(tel, str) or not is_phone_number(tel) or js_trim(tel) == "":
336
+ raise CMIValidationError("Invalid phone number format")
337
+ if len(tel) > 32:
338
+ raise CMIValidationError("tel cannot exceed 32 characters")
339
+
340
+ oid = request.get("oid")
341
+ if oid is not None:
342
+ if _is_blank(oid):
343
+ raise CMIValidationError("oid must be a non-empty string when provided")
344
+ if len(oid) > 64:
345
+ raise CMIValidationError("oid cannot exceed 64 characters")
346
+
347
+ rnd = request.get("rnd")
348
+ if rnd is not None:
349
+ if _is_blank(rnd):
350
+ raise CMIValidationError("rnd must be a non-empty string when provided")
351
+ if len(rnd) > 20:
352
+ raise CMIValidationError("rnd cannot exceed 20 characters")
353
+
354
+ hash_algorithm = request.get("hashAlgorithm")
355
+ if hash_algorithm is not None:
356
+ if _is_blank(hash_algorithm):
357
+ raise CMIValidationError(
358
+ "hashAlgorithm cannot be empty when provided. Use 'ver3' or omit the field for default."
359
+ )
360
+ if hash_algorithm != "ver3":
361
+ raise CMIValidationError("hashAlgorithm must be 'ver3'")
362
+
363
+ encoding = request.get("encoding")
364
+ if encoding is not None:
365
+ if _is_blank(encoding):
366
+ raise CMIValidationError(
367
+ "encoding cannot be empty when provided. Use 'UTF-8' or omit the field for default."
368
+ )
369
+ if encoding != "UTF-8":
370
+ raise CMIValidationError("encoding must be 'UTF-8'")
371
+
372
+ auto_redirect = request.get("AutoRedirect")
373
+ if auto_redirect is not None and not isinstance(auto_redirect, bool):
374
+ raise CMIValidationError("AutoRedirect must be a boolean (True or False)")
375
+
376
+ timeout = request.get("sessiontimeout")
377
+ if timeout is not None:
378
+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not math.isfinite(timeout):
379
+ raise CMIValidationError("sessiontimeout must be a number (seconds). Min: 30, Max: 2700, Default: 1800.")
380
+ if timeout < 30 or timeout > 2700:
381
+ raise CMIValidationError(f"sessiontimeout must be between 30 and 2700 seconds (got {timeout}).")
382
+
383
+ for field, max_length in _BILLING_LIMITS:
384
+ value = request.get(field)
385
+ if value is not None:
386
+ if _is_blank(value):
387
+ raise CMIValidationError(f"{field} must be a non-empty string")
388
+ if len(value) > max_length:
389
+ raise CMIValidationError(f"{field} cannot exceed {max_length} characters")