mbongo 0.1.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.
mbongo/__init__.py ADDED
@@ -0,0 +1,81 @@
1
+ """MTN MoMo and Airtel Money Congo clients that run the same code against the Mbongo mock, the operators'
2
+ sandboxes and production."""
3
+
4
+ from ._airtel import (
5
+ AIRTEL_LIVE_URL,
6
+ AIRTEL_SANDBOX_URL,
7
+ AirtelBalance,
8
+ AirtelCallback,
9
+ AirtelStatus,
10
+ AirtelUser,
11
+ airtel_number,
12
+ parse_airtel_callback,
13
+ )
14
+ from ._core import Mode
15
+ from ._mtn import (
16
+ MTN_LIVE_URL,
17
+ MTN_SANDBOX_URL,
18
+ MtnAccountType,
19
+ MtnApiUser,
20
+ MtnBalance,
21
+ MtnKeys,
22
+ MtnParty,
23
+ MtnStatus,
24
+ MtnStatusValue,
25
+ PayoutKind,
26
+ )
27
+ from .airtel import Airtel, AsyncAirtel
28
+ from .errors import (
29
+ AirtelDuplicateError,
30
+ AirtelError,
31
+ AirtelNoAnswerError,
32
+ MtnDuplicateError,
33
+ MtnError,
34
+ MtnNoAnswerError,
35
+ )
36
+ from .mtn import (
37
+ AsyncMtn,
38
+ AsyncMtnCollection,
39
+ AsyncMtnDisbursement,
40
+ Mtn,
41
+ MtnCollection,
42
+ MtnDisbursement,
43
+ parse_mtn_callback,
44
+ )
45
+
46
+ __all__ = [
47
+ "AIRTEL_LIVE_URL",
48
+ "AIRTEL_SANDBOX_URL",
49
+ "MTN_LIVE_URL",
50
+ "MTN_SANDBOX_URL",
51
+ "Airtel",
52
+ "AirtelBalance",
53
+ "AirtelCallback",
54
+ "AirtelDuplicateError",
55
+ "AirtelError",
56
+ "AirtelNoAnswerError",
57
+ "AirtelStatus",
58
+ "AirtelUser",
59
+ "AsyncAirtel",
60
+ "AsyncMtn",
61
+ "AsyncMtnCollection",
62
+ "AsyncMtnDisbursement",
63
+ "Mode",
64
+ "Mtn",
65
+ "MtnAccountType",
66
+ "MtnApiUser",
67
+ "MtnBalance",
68
+ "MtnCollection",
69
+ "MtnDisbursement",
70
+ "MtnDuplicateError",
71
+ "MtnError",
72
+ "MtnKeys",
73
+ "MtnNoAnswerError",
74
+ "MtnParty",
75
+ "MtnStatus",
76
+ "MtnStatusValue",
77
+ "PayoutKind",
78
+ "airtel_number",
79
+ "parse_airtel_callback",
80
+ "parse_mtn_callback",
81
+ ]
mbongo/_airtel.py ADDED
@@ -0,0 +1,617 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import binascii
5
+ import calendar
6
+ import hashlib
7
+ import hmac
8
+ import json
9
+ import math
10
+ import re
11
+ import time
12
+ import uuid
13
+ from collections.abc import Callable
14
+ from dataclasses import dataclass, field, replace
15
+ from decimal import Decimal, InvalidOperation
16
+ from typing import Any, Literal
17
+
18
+ import httpx
19
+
20
+ from ._core import MODES, Answer, Mode, Request, Step, call, get, sleep, text_of
21
+ from ._mtn import enc
22
+ from .errors import AirtelDuplicateError, AirtelError, AirtelNoAnswerError
23
+
24
+ AIRTEL_SANDBOX_URL = "https://openapiuat.airtel.cg"
25
+ AIRTEL_LIVE_URL = "https://openapi.airtel.cg"
26
+
27
+ Amount = int | float | str | Decimal
28
+
29
+ FINAL = ("TS", "TF", "TE")
30
+
31
+ SUCCESS_CODES = frozenset(
32
+ ["DP00800001001", "DP00800001006", "DP00900001001", "DP00900001006", "DP01000001001", "DP01000001006"]
33
+ )
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class AirtelStatus:
38
+ """A payment's status. ``status`` is TIP in progress, TS paid, TF failed, TE expired, TA ambiguous (ask again
39
+ later), or another value Airtel sends."""
40
+
41
+ id: str
42
+ """Your transaction id."""
43
+ status: str
44
+ airtel_money_id: str | None = None
45
+ """Airtel's id, only once paid (TS). Needed to refund."""
46
+ message: str | None = None
47
+ code: str | None = None
48
+ """Airtel's response code, such as DP00800001001."""
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class AirtelBalance:
53
+ balance: str
54
+ """As Airtel writes it: "37,600.00"."""
55
+ amount: Decimal
56
+ currency: str
57
+ account_status: str | None = None
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class AirtelUser:
62
+ msisdn: str
63
+ first_name: str | None = None
64
+ last_name: str | None = None
65
+ grade: str | None = None
66
+ """Such as SUBS."""
67
+ is_barred: bool | None = None
68
+ is_pin_set: bool | None = None
69
+ registration_status: str | None = None
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class AirtelCallback:
74
+ id: str
75
+ status: Literal["TS", "TF"]
76
+ airtel_money_id: str | None = None
77
+ message: str | None = None
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class Config:
82
+ mode: Mode
83
+ base_url: str
84
+ client_id: str
85
+ client_secret: str = field(repr=False)
86
+ pin: str | None = field(repr=False)
87
+ public_key: str | None
88
+ country: str
89
+ currency: str
90
+
91
+
92
+ def config(
93
+ mode: Mode,
94
+ base_url: str | None,
95
+ client_id: str,
96
+ client_secret: str,
97
+ pin: str | None,
98
+ public_key: str | None,
99
+ country: str,
100
+ currency: str,
101
+ ) -> Config:
102
+ if mode not in MODES:
103
+ raise ValueError(f"unknown mode {mode!r}")
104
+ if mode == "mock" and not base_url:
105
+ raise ValueError("mock mode needs base_url: your Mbongo URL")
106
+ url = (base_url or (AIRTEL_SANDBOX_URL if mode == "sandbox" else AIRTEL_LIVE_URL)).rstrip("/")
107
+ return Config(mode, url, client_id, client_secret, pin, public_key, country, currency)
108
+
109
+
110
+ def airtel_number(phone: str) -> str:
111
+ """Takes off spaces, signs and the 242 or 00242 country code: Airtel Congo wants the national number. Raises
112
+ ``ValueError`` when there are no digits."""
113
+ digits = re.sub(r"\D", "", phone)
114
+ if not digits:
115
+ raise ValueError(f"phone has no digits: {phone!r}")
116
+ if len(digits) == 14 and digits.startswith("00242"):
117
+ return digits[5:]
118
+ return digits[3:] if len(digits) == 12 and digits.startswith("242") else digits
119
+
120
+
121
+ def amount_of(v: Amount) -> int | float:
122
+ """The amount as a JSON number, as JavaScript writes it: whole amounts without a decimal point."""
123
+ if isinstance(v, int) and not isinstance(v, bool):
124
+ return v
125
+ try:
126
+ d = Decimal(v.strip()) if isinstance(v, str) else Decimal(v)
127
+ except (InvalidOperation, TypeError, ValueError):
128
+ d = Decimal("NaN")
129
+ if isinstance(v, bool) or not d.is_finite():
130
+ raise ValueError(f"amount is not a number: {v!r}")
131
+ return int(d) if d == d.to_integral_value() else float(d)
132
+
133
+
134
+ def _data(a: Answer) -> dict[str, Any]:
135
+ d = get(a.body, "data")
136
+ return d if isinstance(d, dict) else {}
137
+
138
+
139
+ def _string(v: Any) -> str:
140
+ if v is None:
141
+ return ""
142
+ if isinstance(v, bool):
143
+ return "true" if v else "false"
144
+ return str(v)
145
+
146
+
147
+ def _succeeded(a: Answer) -> bool:
148
+ if a.status != 200:
149
+ return False
150
+ st = get(a.body, "status")
151
+ return get(st, "success") is True or _string(get(st, "response_code")) in SUCCESS_CODES
152
+
153
+
154
+ def _paid_status(raw: str, code: str | None) -> str:
155
+ # Refunds and the cash pages answer SUCCESS, and disbursements may: with a ...001 code it means paid, as TS
156
+ # does elsewhere.
157
+ return "TS" if raw == "SUCCESS" and code is not None and code.endswith("001") else raw
158
+
159
+
160
+ def _id_of(v: Any) -> str | None:
161
+ # Airtel's docs show ids as strings, but a JSON number must not read as a missing id.
162
+ return str(v) if isinstance(v, int) and not isinstance(v, bool) else text_of(v)
163
+
164
+
165
+ def _first(*values: Any) -> Any:
166
+ return next((v for v in values if v is not None), None)
167
+
168
+
169
+ def to_status(id: str, a: Answer) -> AirtelStatus:
170
+ tx = get(_data(a), "transaction")
171
+ st = get(a.body, "status")
172
+ return AirtelStatus(
173
+ id=_id_of(get(tx, "id")) or id,
174
+ status=_string(_first(get(tx, "status"), get(tx, "status_code"))),
175
+ airtel_money_id=_id_of(get(tx, "airtel_money_id")),
176
+ message=text_of(get(tx, "message")) or text_of(get(st, "message")),
177
+ code=text_of(get(st, "response_code")),
178
+ )
179
+
180
+
181
+ def _cash_status(id: str, a: Answer) -> AirtelStatus:
182
+ # Cash-out answers data.{id, status}, cash-in data.{status, message, transaction}: SUCCESS once paid.
183
+ d = _data(a)
184
+ tx = get(d, "transaction")
185
+ st = get(a.body, "status")
186
+ code = text_of(get(st, "response_code"))
187
+ return AirtelStatus(
188
+ id=_id_of(get(tx, "id")) or _id_of(get(d, "id")) or id,
189
+ status=_paid_status(_string(_first(get(d, "status"), get(tx, "status"))), code),
190
+ airtel_money_id=_id_of(get(tx, "airtel_money_id")),
191
+ message=text_of(get(d, "message")) or text_of(get(st, "message")),
192
+ code=code,
193
+ )
194
+
195
+
196
+ def _cash_body(id: str, amount: Amount, phone: str, reference: str, pin: str | None = None) -> dict[str, Any]:
197
+ # The cash pages write the amount as a string, unlike collections and disbursements; without the exponent
198
+ # str() gives small floats ("1e-05").
199
+ body: dict[str, Any] = {"subscriber": {"msisdn": airtel_number(phone)}, "reference": reference}
200
+ if pin is not None:
201
+ body["pin"] = pin
202
+ body["transaction"] = {"amount": format(Decimal(repr(amount_of(amount))), "f"), "id": id}
203
+ return body
204
+
205
+
206
+ def valid_upto(s: str | None) -> float:
207
+ """ "dd-MM-yyyy HH:mm:ss" as the docs write valid_upto, without a zone: read as Congo time (UTC+1), the earlier
208
+ of the two readings if it is in fact UTC. Now when it can't be read."""
209
+ m = re.fullmatch(r"(\d{2})-(\d{2})-(\d{4}) (\d{2}):(\d{2}):(\d{2})", s or "")
210
+ if not m:
211
+ return time.time()
212
+ d, mo, y, h, mi, se = (int(g) for g in m.groups())
213
+ try:
214
+ return calendar.timegm((y, mo, d, h, mi, se, 0, 0, 0)) - 3600.0
215
+ except (OverflowError, ValueError):
216
+ return time.time()
217
+
218
+
219
+ def _pin_encrypter() -> Callable[[str, str], str]:
220
+ try:
221
+ from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15
222
+ from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
223
+ from cryptography.hazmat.primitives.serialization import load_der_public_key
224
+ except ImportError as e:
225
+ raise ImportError("encrypting the PIN needs the cryptography package: pip install 'mbongo[airtel]'") from e
226
+
227
+ def encrypt(key: str, pin: str) -> str:
228
+ public = load_der_public_key(base64.b64decode(key))
229
+ if not isinstance(public, RSAPublicKey):
230
+ raise ValueError("Airtel's public key is not an RSA key")
231
+ return base64.b64encode(public.encrypt(pin.encode(), PKCS1v15())).decode()
232
+
233
+ return encrypt
234
+
235
+
236
+ class AirtelCore:
237
+ """The token, the key and every call, shared by the sync and async clients through the generator drivers."""
238
+
239
+ def __init__(self, cfg: Config) -> None:
240
+ self.cfg = cfg
241
+ self._token: tuple[str, float] | None = None
242
+ self._key: tuple[str, float] | None = None
243
+
244
+ def _raw(self, method: str, path: str, headers: dict[str, str], body: Any = None) -> Step[Answer]:
245
+ return call(Request(method, self.cfg.base_url + path, headers, body))
246
+
247
+ def _fresh_token(self) -> Step[str]:
248
+ if self._token and time.monotonic() < self._token[1]:
249
+ return self._token[0]
250
+ a = yield from self._raw(
251
+ "POST",
252
+ "/auth/oauth2/token",
253
+ {},
254
+ {
255
+ "client_id": self.cfg.client_id,
256
+ "client_secret": self.cfg.client_secret,
257
+ "grant_type": "client_credentials",
258
+ },
259
+ )
260
+ value = get(a.body, "access_token")
261
+ if a.status != 200 or not isinstance(value, str):
262
+ raise AirtelError(a, "token", never_sent=True)
263
+ # expires_in comes as a string, "180" in the docs: renew a third of the life early, at most a minute.
264
+ try:
265
+ life = float(get(a.body, "expires_in"))
266
+ except (TypeError, ValueError):
267
+ life = 180.0
268
+ if not (math.isfinite(life) and life > 0):
269
+ life = 180.0
270
+ self._token = (value, time.monotonic() + life - min(60.0, life / 3))
271
+ return value
272
+
273
+ def call(
274
+ self, method: str, path: str, body: Any = None, id: str | None = None, advice: str | None = None
275
+ ) -> Step[Answer]:
276
+ """Calls with a token, and asks a new one once if Airtel says the token is no longer good. With ``id``, a
277
+ call that got no answer raises ``AirtelNoAnswerError``; a token call never does: nothing was sent."""
278
+ attempt = 0
279
+ while True:
280
+ token = yield from self._fresh_token()
281
+ headers = {
282
+ "Authorization": f"Bearer {token}",
283
+ "X-Country": self.cfg.country,
284
+ "X-Currency": self.cfg.currency,
285
+ }
286
+ try:
287
+ a = yield from self._raw(method, path, headers, body)
288
+ except httpx.RequestError as e:
289
+ if id is None:
290
+ raise
291
+ raise AirtelNoAnswerError(id, advice) from e
292
+ if a.status != 401 or attempt > 0:
293
+ return a
294
+ self._token = None
295
+ attempt += 1
296
+
297
+ def _create(self, what: str, path: str, id: str, body: Any, advice: str | None = None) -> Step[Answer]:
298
+ a = yield from self.call("POST", path, body, id, advice)
299
+ if _succeeded(a):
300
+ return a
301
+ if AirtelDuplicateError.matches(a):
302
+ raise AirtelDuplicateError(a, what)
303
+ raise AirtelError(a, what)
304
+
305
+ def status(self, path: str, id: str, what: str) -> Step[AirtelStatus]:
306
+ a = yield from self.call("GET", f"{path}/{enc(id)}")
307
+ s = to_status(id, a)
308
+ # The docs' enquiry examples say success false beside a valid status: the status decides.
309
+ if a.status != 200 or s.status == "":
310
+ raise AirtelError(a, what)
311
+ return s
312
+
313
+ def payment(self, id: str) -> Step[AirtelStatus]:
314
+ return self.status("/standard/v1/payments", id, "payment status")
315
+
316
+ def disbursement(self, id: str) -> Step[AirtelStatus]:
317
+ return self.status("/standard/v1/disbursements", id, "disbursement status")
318
+
319
+ def wait_for(self, ask: Callable[[], Step[AirtelStatus]], timeout: float, interval: float) -> Step[AirtelStatus]:
320
+ deadline = time.monotonic() + timeout
321
+ last: AirtelStatus | None = None
322
+ failure: Exception | None = None
323
+ while True:
324
+ try:
325
+ last = yield from ask()
326
+ if last.status in FINAL:
327
+ return last
328
+ except (httpx.RequestError, AirtelError) as e:
329
+ # A lost or 5xx answer says nothing about the payment: ask again rather than call it failed.
330
+ if isinstance(e, AirtelError) and not (e.outcome_unknown or e.status >= 500 or e.status in (408, 429)):
331
+ raise
332
+ failure = e
333
+ if time.monotonic() + interval > deadline:
334
+ if last is not None:
335
+ return last
336
+ assert failure is not None
337
+ raise failure
338
+ yield from sleep(interval)
339
+
340
+ def collect(self, amount: Amount, phone: str, reference: str, id: str | None) -> Step[str]:
341
+ tx_id = id or str(uuid.uuid4())
342
+ c, cur = self.cfg.country, self.cfg.currency
343
+ yield from self._create(
344
+ "collection",
345
+ "/merchant/v1/payments/",
346
+ tx_id,
347
+ {
348
+ "reference": reference,
349
+ "subscriber": {"country": c, "currency": cur, "msisdn": airtel_number(phone)},
350
+ "transaction": {"amount": amount_of(amount), "country": c, "currency": cur, "id": tx_id},
351
+ },
352
+ )
353
+ return tx_id
354
+
355
+ def refund(self, airtel_money_id: str) -> Step[AirtelStatus]:
356
+ a = yield from self._create(
357
+ "refund",
358
+ "/standard/v1/payments/refund",
359
+ airtel_money_id,
360
+ {"transaction": {"airtel_money_id": airtel_money_id}},
361
+ "there is no refund status call: check your balance before sending it again",
362
+ )
363
+ s = to_status(airtel_money_id, a)
364
+ return replace(s, id=s.airtel_money_id or airtel_money_id, status=_paid_status(s.status, s.code))
365
+
366
+ def disburse(self, amount: Amount, phone: str, reference: str, id: str | None) -> Step[AirtelStatus]:
367
+ tx_id = id or str(uuid.uuid4())
368
+ n, msisdn = amount_of(amount), airtel_number(phone)
369
+
370
+ def send(pin: str) -> Step[Answer]:
371
+ return self._create(
372
+ "disbursement",
373
+ "/standard/v1/disbursements/",
374
+ tx_id,
375
+ {
376
+ "payee": {"msisdn": msisdn},
377
+ "reference": reference,
378
+ "pin": pin,
379
+ "transaction": {"amount": n, "id": tx_id},
380
+ },
381
+ )
382
+
383
+ a = yield from self._with_pin(send)
384
+ s = to_status(tx_id, a)
385
+ return replace(s, status=_paid_status(s.status, s.code))
386
+
387
+ def cash_in(self, amount: Amount, phone: str, reference: str, id: str | None) -> Step[AirtelStatus]:
388
+ tx_id = id or str(uuid.uuid4())
389
+ amount_of(amount)
390
+
391
+ def send(pin: str) -> Step[Answer]:
392
+ return self._create(
393
+ "cash-in", "/standard/v1/cashin/", tx_id, _cash_body(tx_id, amount, phone, reference, pin)
394
+ )
395
+
396
+ a = yield from self._with_pin(send)
397
+ return _cash_status(tx_id, a)
398
+
399
+ def cash_out(self, amount: Amount, phone: str, reference: str, id: str | None) -> Step[AirtelStatus]:
400
+ tx_id = id or str(uuid.uuid4())
401
+ a = yield from self._create(
402
+ "cash-out", "/standard/v1/cashout/", tx_id, _cash_body(tx_id, amount, phone, reference)
403
+ )
404
+ return _cash_status(tx_id, a)
405
+
406
+ def user(self, phone: str) -> Step[AirtelUser]:
407
+ msisdn = airtel_number(phone)
408
+ a = yield from self.call("GET", f"/standard/v1/users/{enc(msisdn)}")
409
+ d = _data(a)
410
+ # As for the status enquiries, the docs' examples may say success false beside valid data: the data decides.
411
+ found = get(get(a.body, "status"), "success") is True or text_of(get(d, "msisdn")) is not None
412
+ if a.status != 200 or not found:
413
+ raise AirtelError(a, "user", never_sent=True)
414
+
415
+ def flag(v: Any) -> bool | None:
416
+ return v if isinstance(v, bool) else None
417
+
418
+ return AirtelUser(
419
+ msisdn=text_of(get(d, "msisdn")) or msisdn,
420
+ first_name=text_of(get(d, "first_name")),
421
+ last_name=text_of(get(d, "last_name")),
422
+ grade=text_of(get(d, "grade")),
423
+ is_barred=flag(get(d, "is_barred")),
424
+ is_pin_set=flag(get(d, "is_pin_set")),
425
+ registration_status=text_of(get(get(d, "registration"), "status")),
426
+ )
427
+
428
+ def balance(self) -> Step[AirtelBalance]:
429
+ a = yield from self.call("GET", "/standard/v1/users/balance")
430
+ d = _data(a)
431
+ balance = text_of(get(d, "balance"))
432
+ try:
433
+ amount = Decimal(balance.replace(",", "")) if balance is not None else None
434
+ except InvalidOperation:
435
+ amount = None
436
+ # As for the enquiries, the data decides, not the success flag.
437
+ if a.status != 200 or balance is None or amount is None or not amount.is_finite():
438
+ raise AirtelError(a, "balance", never_sent=True)
439
+ return AirtelBalance(
440
+ balance=balance,
441
+ amount=amount,
442
+ currency=text_of(get(d, "currency")) or self.cfg.currency,
443
+ account_status=text_of(get(d, "account_status")),
444
+ )
445
+
446
+ def _public_key(self) -> Step[str]:
447
+ if self.cfg.public_key:
448
+ return self.cfg.public_key
449
+ if self._key and time.time() < self._key[1]:
450
+ return self._key[0]
451
+ a = yield from self.call("GET", "/v1/rsa/encryption-keys")
452
+ d = _data(a)
453
+ value = text_of(get(d, "key"))
454
+ # As for the enquiries, the data decides, not the success flag.
455
+ if a.status != 200 or value is None:
456
+ raise AirtelError(a, "encryption key", never_sent=True)
457
+ self._key = (value, min(valid_upto(text_of(get(d, "valid_upto"))), time.time() + 24 * 3600.0))
458
+ return value
459
+
460
+ def _encrypted_pin(self) -> Step[str]:
461
+ if not self.cfg.pin:
462
+ raise ValueError("this call needs the app's pin")
463
+ encrypt = _pin_encrypter()
464
+ key = yield from self._public_key()
465
+ return encrypt(key, self.cfg.pin)
466
+
467
+ def _with_pin(self, send: Callable[[str], Step[Answer]]) -> Step[Answer]:
468
+ """Sends with the encrypted PIN. If Airtel says the PIN was encrypted with another key (ROUTER116) and the
469
+ key came from Airtel, it may have changed early: fetch it again and send once more. The PIN is checked
470
+ before the payment is made, so the same id is safe to send again."""
471
+ pin = yield from self._encrypted_pin()
472
+ try:
473
+ return (yield from send(pin))
474
+ except AirtelError as e:
475
+ if self.cfg.public_key or e.code != "ROUTER116":
476
+ raise
477
+ self._key = None
478
+ pin = yield from self._encrypted_pin()
479
+ return (yield from send(pin))
480
+
481
+
482
+ def raw_transaction(text: str) -> str | None:
483
+ """The ``transaction`` value of a JSON object as it was written, so the hash covers the bytes Airtel sent.
484
+ Raises on a second ``transaction`` key: json.loads keeps the last, so a hash on the first would vouch for data
485
+ it never covered."""
486
+ depth = 0
487
+ found: str | None = None
488
+ i = 0
489
+ while i < len(text):
490
+ c = text[i]
491
+ if c == '"':
492
+ end = _string_end(text, i)
493
+ j = _skip_space(text, end + 1)
494
+ # Keys are compared decoded, as json.loads reads them: "\u0074ransaction" is a transaction key too.
495
+ if depth == 1 and text[j : j + 1] == ":" and _key_name(text[i : end + 1]) == "transaction":
496
+ if found is not None:
497
+ raise ValueError("the callback has two transaction fields")
498
+ j = _skip_space(text, j + 1)
499
+ v_end = _value_end(text, j)
500
+ found = text[j : v_end + 1]
501
+ i = v_end + 1
502
+ continue
503
+ i = end
504
+ elif c in "{[":
505
+ depth += 1
506
+ elif c in "}]":
507
+ depth -= 1
508
+ i += 1
509
+ return found
510
+
511
+
512
+ def _skip_space(text: str, i: int) -> int:
513
+ while i < len(text) and text[i].isspace():
514
+ i += 1
515
+ return i
516
+
517
+
518
+ def _key_name(quoted: str) -> str | None:
519
+ try:
520
+ name = json.loads(quoted)
521
+ except ValueError:
522
+ return None
523
+ return name if isinstance(name, str) else None
524
+
525
+
526
+ def _string_end(text: str, start: int) -> int:
527
+ i = start + 1
528
+ while i < len(text) and text[i] != '"':
529
+ i += 2 if text[i] == "\\" else 1
530
+ return i
531
+
532
+
533
+ def _value_end(text: str, start: int) -> int:
534
+ if text[start : start + 1] == '"':
535
+ return _string_end(text, start)
536
+ if text[start : start + 1] not in ("{", "["):
537
+ i = start
538
+ while i + 1 < len(text) and not (text[i + 1] in ",}]" or text[i + 1].isspace()):
539
+ i += 1
540
+ return i
541
+ depth = 0
542
+ i = start
543
+ while i < len(text):
544
+ c = text[i]
545
+ if c == '"':
546
+ i = _string_end(text, i)
547
+ elif c in "{[":
548
+ depth += 1
549
+ elif c in "}]":
550
+ depth -= 1
551
+ if depth == 0:
552
+ return i
553
+ i += 1
554
+ return len(text) - 1
555
+
556
+
557
+ def _js_number(v: float) -> str:
558
+ if not math.isfinite(v):
559
+ return "null"
560
+ r = repr(v)
561
+ if v.is_integer() and abs(v) < 1e21:
562
+ # The shortest digits, then zeros: 2**60 is 1152921504606847000 in JavaScript.
563
+ return str(int(Decimal(r)))
564
+ if "e" not in r:
565
+ return r
566
+ mantissa, exp = r.split("e")
567
+ # JavaScript writes plain digits from 1e-6 up, where Python already writes 1e-05.
568
+ e = int(exp)
569
+ return format(Decimal(r), "f") if -6 <= e < 21 else f"{mantissa}e{'+' if e > 0 else ''}{e}"
570
+
571
+
572
+ def _js_json(v: Any) -> str:
573
+ """As JSON.stringify writes it: compact, numbers as JavaScript writes them."""
574
+ if isinstance(v, float):
575
+ return _js_number(v)
576
+ if isinstance(v, dict):
577
+ return "{" + ",".join(f"{_js_json(str(k))}:{_js_json(x)}" for k, x in v.items()) + "}"
578
+ if isinstance(v, list):
579
+ return "[" + ",".join(_js_json(x) for x in v) + "]"
580
+ return json.dumps(v, ensure_ascii=False)
581
+
582
+
583
+ def _hashes(key: str, tx: Any, sent: str | None) -> list[bytes]:
584
+ # As JSON.stringify writes it, as Node and Go senders do.
585
+ plain = _js_json(tx)
586
+ # Go-built senders escape <, > and & in JSON; hash both spellings when the bytes sent are not at hand.
587
+ escaped = re.sub(r"[<>&]", lambda m: f"\\u{ord(m.group()):04x}", plain)
588
+ tries = [plain, escaped] if sent is None else [sent, plain, escaped]
589
+ return [hmac.new(key.encode(), s.encode(), hashlib.sha256).digest() for s in dict.fromkeys(tries)]
590
+
591
+
592
+ def parse_airtel_callback(body: str | bytes | dict[str, Any], callback_key: str | None = None) -> AirtelCallback:
593
+ """Reads an Airtel callback. With ``callback_key`` (set in the app's settings), the body's ``hash`` must match:
594
+ HMAC-SHA256 of the transaction object, in Base64 (the docs don't say which bytes; this follows Mbongo). Give
595
+ the body as the text or bytes received, so the hash is checked on the bytes Airtel sent. A body with a ``hash``
596
+ needs the key: an empty or missing key raises rather than skip the check. Without a key and a hash, anyone can
597
+ send a callback: confirm with ``get_payment`` before you deliver anything. Raises ``ValueError``."""
598
+ text = body.decode() if isinstance(body, bytes) else body if isinstance(body, str) else None
599
+ data: Any = json.loads(text) if text is not None else body
600
+ tx = get(data, "transaction")
601
+ status = get(tx, "status_code")
602
+ id = _id_of(get(tx, "id"))
603
+ if status not in ("TS", "TF") or id is None:
604
+ raise ValueError("not an Airtel callback")
605
+ if callback_key == "":
606
+ raise ValueError("the callback key is empty")
607
+ if callback_key is None and get(data, "hash") is not None:
608
+ raise ValueError("the callback has a hash: give the callback key to check it")
609
+ if callback_key is not None:
610
+ try:
611
+ got = base64.b64decode(_string(get(data, "hash")))
612
+ except (binascii.Error, ValueError):
613
+ got = b""
614
+ sent = raw_transaction(text) if text is not None else None
615
+ if not any(hmac.compare_digest(h, got) for h in _hashes(callback_key, tx, sent)):
616
+ raise ValueError("Airtel callback hash does not match")
617
+ return AirtelCallback(id, status, _id_of(get(tx, "airtel_money_id")), text_of(get(tx, "message")))