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/_compat.py ADDED
@@ -0,0 +1,125 @@
1
+ """JavaScript and PHP semantics the SDK needs to reproduce byte for byte.
2
+
3
+ CMI's reference scripts are PHP, and cmi-node is JavaScript. A payment hash only
4
+ matches when every value is turned into text, trimmed and encoded exactly the way
5
+ they do it, so the small differences between Python and those languages
6
+ (``str(True)``, ``str.strip()``, ``float()``...) are handled here, in one place.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ import re
13
+ from decimal import Decimal
14
+ from typing import Any
15
+
16
+ # ECMAScript WhiteSpace + LineTerminator: what String.prototype.trim() removes.
17
+ _JS_WHITESPACE = "\t\n\v\f\r              

   "
18
+ # PHP trim(): only " \t\n\r\0\x0B".
19
+ _PHP_TRIM = " \t\n\r\0\x0b"
20
+
21
+
22
+ def js_trim(value: str) -> str:
23
+ """``String.prototype.trim()``."""
24
+ return value.strip(_JS_WHITESPACE)
25
+
26
+
27
+ def php_trim(value: str) -> str:
28
+ """PHP's ``trim()``: unlike ``str.strip()``, it keeps non-breaking and Unicode spaces."""
29
+ return value.strip(_PHP_TRIM)
30
+
31
+
32
+ def js_number_to_string(number: float) -> str:
33
+ """``String(number)`` in JavaScript (Number::toString, shortest round-trip digits)."""
34
+ if math.isnan(number):
35
+ return "NaN"
36
+ if math.isinf(number):
37
+ return "Infinity" if number > 0 else "-Infinity"
38
+ if number == 0:
39
+ return "0" # also -0
40
+ if number.is_integer() and abs(number) < 1e21:
41
+ return str(int(number))
42
+
43
+ # repr() gives the shortest digits that round-trip, like JavaScript.
44
+ sign, digit_tuple, exponent = Decimal(repr(number)).normalize().as_tuple()
45
+ if not isinstance(exponent, int): # pragma: no cover - NaN and infinities are handled above
46
+ raise ValueError(number)
47
+ digits = "".join(map(str, digit_tuple))
48
+ k = len(digits)
49
+ n = exponent + k # value = 0.digits x 10^n
50
+ if k <= n <= 21:
51
+ text = digits + "0" * (n - k)
52
+ elif 0 < n <= 21:
53
+ text = f"{digits[:n]}.{digits[n:]}"
54
+ elif -6 < n <= 0:
55
+ text = "0." + "0" * (-n) + digits
56
+ else:
57
+ mantissa = digits[0] + (f".{digits[1:]}" if k > 1 else "")
58
+ e = n - 1
59
+ text = f"{mantissa}e{'+' if e >= 0 else '-'}{abs(e)}"
60
+ return ("-" if sign else "") + text
61
+
62
+
63
+ def js_string(value: Any) -> str:
64
+ """``String(value)`` in JavaScript, for the value types a payment request can hold."""
65
+ if value is None:
66
+ return ""
67
+ if isinstance(value, str):
68
+ return value
69
+ if isinstance(value, bool):
70
+ return "true" if value else "false"
71
+ if isinstance(value, int):
72
+ return str(value)
73
+ if isinstance(value, float):
74
+ return js_number_to_string(value)
75
+ if isinstance(value, Decimal):
76
+ return format(value, "f") if value.is_finite() else str(value)
77
+ if isinstance(value, (list, tuple)):
78
+ return ",".join(js_string(item) for item in value)
79
+ return str(value)
80
+
81
+
82
+ def to_field_string(value: Any) -> str:
83
+ """A posted form value as text. A repeated field keeps its last value, like PHP's ``$_POST``."""
84
+ if isinstance(value, (list, tuple)):
85
+ value = value[-1] if value else None
86
+ return js_string(value)
87
+
88
+
89
+ _JS_FLOAT_PREFIX = re.compile(r"[+-]?(?:Infinity|(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?)", re.ASCII)
90
+ _JS_NUMBER = re.compile(r"[+-]?(?:(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?|Infinity)", re.ASCII)
91
+
92
+
93
+ def js_parse_float_prefix(value: Any) -> str | None:
94
+ """The numeric prefix ``parseFloat()`` would read from ``value`` ("10.25abc" -> "10.25")."""
95
+ match = _JS_FLOAT_PREFIX.match(js_trim(to_field_string(value)))
96
+ return match.group(0) if match else None
97
+
98
+
99
+ def js_to_number(value: Any) -> float:
100
+ """JavaScript's ``Number(value)`` / implicit conversion in ``value > 0``."""
101
+ if value is None:
102
+ return math.nan
103
+ if isinstance(value, bool):
104
+ return 1.0 if value else 0.0
105
+ if isinstance(value, (int, float, Decimal)):
106
+ return float(value)
107
+ if isinstance(value, str):
108
+ text = js_trim(value)
109
+ if text == "":
110
+ return 0.0
111
+ if _JS_NUMBER.fullmatch(text):
112
+ return float(text.replace("Infinity", "inf"))
113
+ if re.fullmatch(r"0[xX][0-9a-fA-F]+", text):
114
+ return float(int(text, 16))
115
+ return math.nan
116
+ return math.nan
117
+
118
+
119
+ def utf8(text: str) -> bytes:
120
+ """UTF-8 bytes of a string, with lone surrogates replaced by U+FFFD as Node.js does."""
121
+ try:
122
+ return text.encode("utf-8")
123
+ except UnicodeEncodeError:
124
+ repaired = text.encode("utf-16", "surrogatepass").decode("utf-16", "replace")
125
+ return repaired.encode("utf-8")
cmi/_log.py ADDED
@@ -0,0 +1,16 @@
1
+ """The SDK's logger.
2
+
3
+ The SDK logs through the standard :mod:`logging` module, under the ``"cmi"`` logger.
4
+ It never logs a secret, the hash input or customer data. Like every library, it adds
5
+ a :class:`logging.NullHandler` and leaves the configuration to the application::
6
+
7
+ import logging
8
+ logging.getLogger("cmi").setLevel(logging.DEBUG)
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+
15
+ logger = logging.getLogger("cmi")
16
+ logger.addHandler(logging.NullHandler())
cmi/_php.py ADDED
@@ -0,0 +1,169 @@
1
+ """PHP-compatible helpers used to reproduce, byte for byte, the hash calculation of
2
+ CMI's reference PHP scripts (2.SendData.php and callback.php)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import re
7
+ from html.entities import name2codepoint
8
+
9
+ # name2codepoint is the HTML 4.01 entity table, exactly the one PHP's
10
+ # html_entity_decode(..., ENT_QUOTES, 'UTF-8') uses by default (252 names, no &apos;).
11
+ _ENTITY = re.compile(r"&(?:#([0-9]+)|#[xX]([0-9a-fA-F]+)|([A-Za-z][A-Za-z0-9]*));")
12
+
13
+
14
+ def _is_decodable_code_point(cp: int) -> bool:
15
+ """Code points PHP decodes from numeric entities with the HTML 4.01 doctype."""
16
+ if cp in (0x09, 0x0A, 0x0D):
17
+ return True
18
+ if 0x20 <= cp <= 0x7E:
19
+ return True
20
+ return 0xA0 <= cp <= 0x10FFFF and not 0xD800 <= cp <= 0xDFFF
21
+
22
+
23
+ def _decode_entity(match: re.Match[str]) -> str:
24
+ dec, hexa, name = match.group(1), match.group(2), match.group(3)
25
+ if name is not None:
26
+ cp = name2codepoint.get(name)
27
+ return match.group(0) if cp is None else chr(cp)
28
+ cp = int(dec, 10) if dec is not None else int(hexa, 16)
29
+ return chr(cp) if _is_decodable_code_point(cp) else match.group(0)
30
+
31
+
32
+ def php_html_entity_decode(value: str) -> str:
33
+ """PHP's ``html_entity_decode($value, ENT_QUOTES, 'UTF-8')`` with the default HTML 4.01 table."""
34
+ if "&" not in value:
35
+ return value
36
+ return _ENTITY.sub(_decode_entity, value)
37
+
38
+
39
+ _TRAILING_NEWLINE = re.compile(r"\n(?=\n?\Z)")
40
+
41
+
42
+ def php_strip_trailing_newline(value: str) -> str:
43
+ """callback.php's ``preg_replace("/\\n$/", "", $value)``: PCRE ``$`` also matches before a final newline."""
44
+ return _TRAILING_NEWLINE.sub("", value)
45
+
46
+
47
+ def _is_digit(c: int) -> bool:
48
+ return 0x30 <= c <= 0x39
49
+
50
+
51
+ def _is_space(c: int) -> bool:
52
+ # C isspace(): space, \t, \n, \v, \f, \r
53
+ return c == 0x20 or 0x09 <= c <= 0x0D
54
+
55
+
56
+ def _to_upper(c: int) -> int:
57
+ return c - 0x20 if 0x61 <= c <= 0x7A else c
58
+
59
+
60
+ def php_strnatcasecmp(left: str, right: str) -> int:
61
+ """PHP's ``strnatcasecmp()`` (ext/standard/strnatcmp.c), on the UTF-8 bytes of both strings.
62
+
63
+ ``natcasesort()`` orders the field names with it: "item2" comes before "item10", and the
64
+ comparison is done on upper-cased characters (so "_" sorts after letters).
65
+ """
66
+ a = left.encode("utf-8", "surrogatepass")
67
+ b = right.encode("utf-8", "surrogatepass")
68
+ la, lb = len(a), len(b)
69
+ if la == 0 or lb == 0:
70
+ return 0 if la == lb else (1 if la > lb else -1)
71
+
72
+ ai = 0
73
+ bi = 0
74
+
75
+ def at(buf: bytes, i: int) -> int:
76
+ # Out-of-range reads behave like C's terminating NUL byte.
77
+ return buf[i] if i < len(buf) else 0
78
+
79
+ def compare_right() -> int:
80
+ # The longest run of digits wins; with equal length, the first difference decides.
81
+ nonlocal ai, bi
82
+ bias = 0
83
+ while True:
84
+ a_end = ai == la or not _is_digit(a[ai])
85
+ b_end = bi == lb or not _is_digit(b[bi])
86
+ if a_end and b_end:
87
+ return bias
88
+ if a_end:
89
+ return -1
90
+ if b_end:
91
+ return 1
92
+ if a[ai] < b[bi] and not bias:
93
+ bias = -1
94
+ elif a[ai] > b[bi] and not bias:
95
+ bias = 1
96
+ ai += 1
97
+ bi += 1
98
+
99
+ def compare_left() -> int:
100
+ # Left-aligned (fractional) numbers: the first different digit wins.
101
+ nonlocal ai, bi
102
+ while True:
103
+ a_end = ai == la or not _is_digit(a[ai])
104
+ b_end = bi == lb or not _is_digit(b[bi])
105
+ if a_end and b_end:
106
+ return 0
107
+ if a_end:
108
+ return -1
109
+ if b_end:
110
+ return 1
111
+ if a[ai] < b[bi]:
112
+ return -1
113
+ if a[ai] > b[bi]:
114
+ return 1
115
+ ai += 1
116
+ bi += 1
117
+
118
+ leading = True
119
+ while True:
120
+ ca = at(a, ai)
121
+ cb = at(b, bi)
122
+
123
+ # Skip over leading zeros (only at the start of the strings).
124
+ while leading and ca == 0x30 and ai + 1 < la and _is_digit(a[ai + 1]):
125
+ ai += 1
126
+ ca = at(a, ai)
127
+ while leading and cb == 0x30 and bi + 1 < lb and _is_digit(b[bi + 1]):
128
+ bi += 1
129
+ cb = at(b, bi)
130
+ leading = False
131
+
132
+ # Skip consecutive whitespace.
133
+ while _is_space(ca):
134
+ ai += 1
135
+ ca = at(a, ai)
136
+ while _is_space(cb):
137
+ bi += 1
138
+ cb = at(b, bi)
139
+
140
+ # Process a run of digits.
141
+ if _is_digit(ca) and _is_digit(cb):
142
+ fractional = ca == 0x30 or cb == 0x30
143
+ result = compare_left() if fractional else compare_right()
144
+ if result != 0:
145
+ return result
146
+ if ai == la and bi == lb:
147
+ return 0
148
+ if ai == la:
149
+ return -1
150
+ if bi == lb:
151
+ return 1
152
+ ca = at(a, ai)
153
+ cb = at(b, bi)
154
+
155
+ ca = _to_upper(ca)
156
+ cb = _to_upper(cb)
157
+ if ca < cb:
158
+ return -1
159
+ if ca > cb:
160
+ return 1
161
+
162
+ ai += 1
163
+ bi += 1
164
+ if ai >= la and bi >= lb:
165
+ return 0
166
+ if ai >= la:
167
+ return -1
168
+ if bi >= lb:
169
+ return 1
cmi/_security.py ADDED
@@ -0,0 +1,88 @@
1
+ """Secret handling, timing-safe comparison and the server-only guard."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import hmac
7
+ import sys
8
+ from typing import Any, NoReturn
9
+
10
+ from ._compat import utf8
11
+ from .errors import CMIValidationError
12
+
13
+ _MASK = "********"
14
+
15
+ SERVER_ONLY_MESSAGE = (
16
+ "cmi-python is server-only: it holds your CMI store key and must never run in a browser "
17
+ "(Pyodide, PyScript). Use it in your server code (a view, a route handler, a worker)."
18
+ )
19
+
20
+
21
+ def assert_server_runtime() -> None:
22
+ """Refuses to run inside a browser (Pyodide / PyScript run on Emscripten)."""
23
+ if sys.platform == "emscripten":
24
+ raise RuntimeError(SERVER_ONLY_MESSAGE)
25
+
26
+
27
+ class SecretString:
28
+ """A secret value that never shows up in ``repr()``, ``str()``, f-strings, logs or pickles.
29
+
30
+ Python has no truly private attributes: this protects against *accidental* exposure
31
+ (a ``print``, a log line, an error report, a cache), not against code that digs into
32
+ the object on purpose.
33
+ """
34
+
35
+ __slots__ = ("__value",)
36
+
37
+ def __init__(self, value: str) -> None:
38
+ if not isinstance(value, str) or value == "":
39
+ raise CMIValidationError("SecretString requires a non-empty string value")
40
+ self.__value = value
41
+
42
+ def get_value(self) -> str:
43
+ """The secret itself. Only for the cryptographic operations of the SDK."""
44
+ return self.__value
45
+
46
+ def equals(self, other: str | SecretString) -> bool:
47
+ """Constant-time comparison (neither the content nor the length leaks through timing)."""
48
+ other_value = other.get_value() if isinstance(other, SecretString) else other
49
+ if not isinstance(other_value, str):
50
+ return False
51
+ return timing_safe_compare(self.__value, other_value)
52
+
53
+ def __len__(self) -> int:
54
+ return len(self.__value)
55
+
56
+ def __repr__(self) -> str:
57
+ return f"SecretString({_MASK})"
58
+
59
+ def __str__(self) -> str:
60
+ return _MASK
61
+
62
+ def __format__(self, format_spec: str) -> str:
63
+ return _MASK
64
+
65
+ def __reduce__(self) -> NoReturn:
66
+ raise TypeError("SecretString cannot be pickled: secrets must not end up in caches or files")
67
+
68
+ def __copy__(self) -> SecretString:
69
+ return self
70
+
71
+ def __deepcopy__(self, memo: dict[int, Any]) -> SecretString:
72
+ return self
73
+
74
+ __hash__ = object.__hash__
75
+
76
+
77
+ def timing_safe_compare(a: str, b: str) -> bool:
78
+ """Constant-time comparison of two strings.
79
+
80
+ Both sides are hashed to fixed-length digests first, so neither the value nor the
81
+ length of either string can be inferred from the comparison time.
82
+ """
83
+ try:
84
+ digest_a = hashlib.sha256(utf8(a)).digest()
85
+ digest_b = hashlib.sha256(utf8(b)).digest()
86
+ except (TypeError, AttributeError):
87
+ return False
88
+ return hmac.compare_digest(digest_a, digest_b)
cmi/_validation.py ADDED
@@ -0,0 +1,89 @@
1
+ """URL, e-mail and phone checks shared by every kit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any
7
+ from urllib.parse import SplitResult, urlsplit
8
+
9
+ from ._compat import js_trim
10
+
11
+ _SCHEME = re.compile(r"[A-Za-z][A-Za-z0-9+.\-]*", re.ASCII)
12
+ _HOST_SCHEMES = {"http", "https", "ws", "wss", "ftp"}
13
+ _BLOCKED_REDIRECT_SCHEMES = {"javascript", "data", "vbscript", "file"}
14
+ _EMAIL = re.compile(r"[a-zA-Z0-9]+(?:[._+-][a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:[.-][a-zA-Z0-9]+)*\.[a-zA-Z]{2,}", re.ASCII)
15
+ _PHONE_FORMAT = re.compile(r"[+0-9][0-9\s\-()]*")
16
+ _PHONE_DIGITS = re.compile(r"\+?[0-9]{6,20}")
17
+
18
+
19
+ def parse_url(url: Any) -> SplitResult | None:
20
+ """The URL's parts, or None when it is not an absolute URL (like ``new URL()`` failing)."""
21
+ if not isinstance(url, str) or url == "":
22
+ return None
23
+ # No whitespace or control character anywhere (WHATWG would silently strip some).
24
+ if any(ord(c) <= 0x20 or ord(c) == 0x7F for c in url):
25
+ return None
26
+ try:
27
+ parts = urlsplit(url)
28
+ if not parts.scheme or not _SCHEME.fullmatch(parts.scheme):
29
+ return None
30
+ if not url[len(parts.scheme) :].startswith(":"):
31
+ return None
32
+ if parts.scheme.lower() in _HOST_SCHEMES:
33
+ if not parts.hostname:
34
+ return None
35
+ _ = parts.port # raises ValueError for an invalid port
36
+ except ValueError:
37
+ return None
38
+ return parts
39
+
40
+
41
+ def is_valid_url(url: Any) -> bool:
42
+ return parse_url(url) is not None
43
+
44
+
45
+ def has_http_protocol(url: Any) -> bool:
46
+ parts = parse_url(url)
47
+ return parts is not None and parts.scheme.lower() in ("http", "https")
48
+
49
+
50
+ def is_secure_or_local_url(url: Any) -> bool:
51
+ """HTTPS, or plain HTTP on a local development host (localhost, *.localhost, 127.0.0.1, [::1]),
52
+ so the gateway, callback and API URLs are never used in clear text over the internet."""
53
+ parts = parse_url(url)
54
+ if parts is None:
55
+ return False
56
+ scheme = parts.scheme.lower()
57
+ if scheme == "https":
58
+ return True
59
+ if scheme != "http":
60
+ return False
61
+ host = (parts.hostname or "").lower()
62
+ return host == "localhost" or host.endswith(".localhost") or host in ("127.0.0.1", "::1")
63
+
64
+
65
+ def is_valid_redirect_url(url: Any) -> bool:
66
+ """http, https, or a safe custom scheme (mobile deeplink such as ``myapp://success``)."""
67
+ parts = parse_url(url)
68
+ return parts is not None and parts.scheme.lower() not in _BLOCKED_REDIRECT_SCHEMES
69
+
70
+
71
+ def is_valid_email(email: Any) -> bool:
72
+ return isinstance(email, str) and _EMAIL.fullmatch(email) is not None
73
+
74
+
75
+ def is_phone_number(phone: str) -> bool:
76
+ """Digits, spaces, dashes and parentheses, with an optional leading "+": 6 to 20 digits.
77
+
78
+ Leading zeros are allowed (Moroccan numbers such as 0612345678 or 00212612345678).
79
+ """
80
+ trimmed = js_trim(phone)
81
+ if not _PHONE_FORMAT.fullmatch(trimmed):
82
+ return False
83
+ cleaned = re.sub(r"[\s\-()]", "", trimmed)
84
+ return _PHONE_DIGITS.fullmatch(cleaned) is not None
85
+
86
+
87
+ def is_digits(value: str) -> bool:
88
+ """Only the digits 0-9 (no sign, no decimal point)."""
89
+ return re.fullmatch(r"[0-9]+", js_trim(value)) is not None
@@ -0,0 +1,27 @@
1
+ """Framework adapters for CMI's callback. Import only the one you use:
2
+
3
+ - :mod:`cmi.adapters.django`: ``create_django_view(gateway, ...)``
4
+ - :mod:`cmi.adapters.flask`: ``create_flask_view(gateway, ...)``, ``register_flask_callback(app, gateway, ...)``
5
+ - :mod:`cmi.adapters.fastapi` / :mod:`cmi.adapters.starlette`:
6
+ ``create_starlette_endpoint(gateway, ...)``, ``register_fastapi_callback(app, gateway, ...)``
7
+
8
+ Every adapter takes the :class:`~cmi.CallbackHandler` options (``validate_order``,
9
+ ``on_success``, ``on_failure``, ``success_response``, ``failure_response``,
10
+ ``declined_response``, ``support_get_method``), answers CMI first, then runs
11
+ ``on_success`` / ``on_failure`` once the answer has been sent.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections.abc import Iterable
17
+ from typing import Any
18
+
19
+ __all__: list[str] = []
20
+
21
+
22
+ def lists_to_fields(items: Iterable[tuple[str, Any]]) -> dict[str, list[Any]]:
23
+ """(key, value) pairs -> {key: [values]}; the verifier keeps the last value of a repeated field."""
24
+ fields: dict[str, list[Any]] = {}
25
+ for key, value in items:
26
+ fields.setdefault(key, []).append(value)
27
+ return fields
cmi/adapters/django.py ADDED
@@ -0,0 +1,97 @@
1
+ """Django adapter for CMI's callback.
2
+
3
+ ::
4
+
5
+ # urls.py
6
+ from cmi.adapters.django import create_django_view
7
+
8
+ urlpatterns = [
9
+ path("cmi/callback", create_django_view(gateway, validate_order=validate_order,
10
+ on_success=mark_paid)),
11
+ ]
12
+
13
+ The view is CSRF-exempt and exempt from ``LoginRequiredMiddleware`` (CMI's server can neither
14
+ send your CSRF token nor log in): its protection is the HASH. It is a plain Django view, so
15
+ DRF's default authentication, permission and parser settings do not apply to it.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from collections.abc import Callable
21
+ from typing import Any
22
+
23
+ try:
24
+ from django.http import HttpRequest, HttpResponse, HttpResponseNotAllowed
25
+ from django.views.decorators.csrf import csrf_exempt
26
+ except ImportError as error: # pragma: no cover
27
+ raise ImportError("cmi.adapters.django needs Django: pip install 'cmi-python[django]'") from error
28
+
29
+ try: # Django 5.1+: exempts the view from LoginRequiredMiddleware
30
+ from django.contrib.auth.decorators import login_not_required
31
+ except ImportError: # pragma: no cover - older Django has no LoginRequiredMiddleware
32
+
33
+ def login_not_required(view_func: Any) -> Any:
34
+ view_func.login_required = False
35
+ return view_func
36
+
37
+
38
+ from .._log import logger
39
+ from ..standard import CallbackHandler, CallbackResult, CMIPaymentGateway
40
+
41
+ __all__ = ["create_django_view"]
42
+
43
+
44
+ class _AnswerThenNotify(HttpResponse):
45
+ """Runs ``after`` once Django has sent the answer (when the server closes the response),
46
+ before Django's own clean-up (database connections are still usable)."""
47
+
48
+ def __init__(self, *args: Any, after: Callable[[], None] | None = None, **kwargs: Any) -> None:
49
+ super().__init__(*args, **kwargs)
50
+ self._cmi_after = after
51
+
52
+ def close(self) -> None:
53
+ after, self._cmi_after = self._cmi_after, None
54
+ try:
55
+ if after is not None:
56
+ after()
57
+ finally:
58
+ super().close()
59
+
60
+
61
+ def create_django_view(gateway: CMIPaymentGateway, **options: Any) -> Callable[[HttpRequest], HttpResponse]:
62
+ """A Django view for CMI's callback.
63
+
64
+ It verifies the HASH, runs ``validate_order``, answers CMI (``ACTION=POSTAUTH``,
65
+ ``APPROVED`` or ``FAILURE``) and runs ``on_success`` / ``on_failure`` after the answer
66
+ has been sent. Only POST is accepted (and GET with ``support_get_method``). The handler
67
+ is available as ``view.cmi_handler``.
68
+ """
69
+ handler: CallbackHandler = gateway.create_callback_handler(**options)
70
+ allowed = ["POST", "GET"] if handler.supports_get_method else ["POST"]
71
+
72
+ # CMI's server cannot log in nor send a CSRF token: the HASH is the protection. Without
73
+ # these, CsrfViewMiddleware answers 403 and LoginRequiredMiddleware redirects CMI to the
74
+ # login page, so payments are never confirmed.
75
+ @login_not_required
76
+ @csrf_exempt
77
+ def cmi_callback(request: HttpRequest) -> HttpResponse:
78
+ if request.method not in allowed:
79
+ return HttpResponseNotAllowed(allowed)
80
+ result: CallbackResult | None = None
81
+ try:
82
+ query = request.GET if request.method == "GET" else request.POST
83
+ result, answer = handler.evaluate(dict(query.lists()))
84
+ except Exception as error: # noqa: BLE001 - CMI must always get an answer
85
+ logger.error("CMI: callback handler error: %s", type(error).__name__)
86
+ answer = handler.error_response()
87
+
88
+ finished = result
89
+ return _AnswerThenNotify(
90
+ answer.body,
91
+ status=answer.status,
92
+ content_type="text/plain; charset=utf-8",
93
+ after=(lambda: handler.notify(finished)) if finished is not None else None,
94
+ )
95
+
96
+ cmi_callback.cmi_handler = handler # type: ignore[attr-defined]
97
+ return cmi_callback
@@ -0,0 +1,15 @@
1
+ """FastAPI adapter for CMI's callback (the Starlette adapter, under FastAPI's name).
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
+
11
+ from .starlette import DEFAULT_MAX_BODY_SIZE, create_starlette_endpoint, register_fastapi_callback
12
+
13
+ create_fastapi_endpoint = create_starlette_endpoint
14
+
15
+ __all__ = ["DEFAULT_MAX_BODY_SIZE", "create_fastapi_endpoint", "create_starlette_endpoint", "register_fastapi_callback"]