slip2sure 2.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.
slip2sure/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ '''
2
+ Copyright 2025 Slip2Sure
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
9
+ '''
10
+
11
+ from ._version import VERSION
12
+
13
+ AUTHOR = "Slip2Sure"
14
+
15
+ from .client import *
16
+ from .exception import *
17
+ from .model import *
slip2sure/_version.py ADDED
@@ -0,0 +1,7 @@
1
+ """Single source of truth for the package version.
2
+
3
+ setup.py reads this file, so the version can no longer drift between the
4
+ package and its metadata.
5
+ """
6
+
7
+ VERSION = "2.0.0"
slip2sure/client.py ADDED
@@ -0,0 +1,654 @@
1
+ """Async client for the Slip2Sure slip verification API."""
2
+
3
+ import asyncio
4
+ import base64
5
+ import json
6
+ import random
7
+ import re
8
+ import time
9
+ import uuid
10
+ from datetime import datetime
11
+ from enum import Enum
12
+ from types import TracebackType
13
+ from typing import Any, Callable
14
+
15
+ import aiohttp
16
+ from aiohttp import FormData
17
+
18
+ from ._version import VERSION
19
+ from .exception import (
20
+ ErrorCode,
21
+ Slip2SureError,
22
+ Slip2SureTransportError,
23
+ Slip2SureValidationError,
24
+ )
25
+ from .model import (
26
+ Slip2SureAPIKey,
27
+ Slip2SureApplication,
28
+ Slip2SureApplicationInput,
29
+ Slip2SureBankSlip,
30
+ Slip2SureTransactionList,
31
+ Slip2SureTruemoney,
32
+ Slip2SureUserCredit,
33
+ SlipType,
34
+ TransactionStatus,
35
+ )
36
+
37
+ __all__ = [
38
+ "Slip2SureAPI",
39
+ "DEFAULT_BASE_URL",
40
+ "DEFAULT_TIMEOUT",
41
+ "DEFAULT_MAX_RETRIES",
42
+ ]
43
+
44
+ DEFAULT_BASE_URL = "https://api.slip2sure.com/api/v0"
45
+ DEFAULT_TIMEOUT = 30.0
46
+ DEFAULT_MAX_RETRIES = 2
47
+ DEFAULT_RETRY_BACKOFF = 0.5
48
+
49
+ # Exponential growth is capped so a long retry chain cannot stall a call well
50
+ # past what the caller expected.
51
+ _MAX_RETRY_BACKOFF = 10.0
52
+
53
+ # Statuses worth retrying. Verification costs credits, so 500 is deliberately
54
+ # excluded: the request may have been processed and billed before failing, and
55
+ # retrying it could bill the caller twice. The statuses below all mean the
56
+ # request did not reach or complete processing.
57
+ _RETRYABLE_STATUS = frozenset({408, 429, 502, 503, 504})
58
+
59
+ # Which credential a request authenticates with.
60
+ _AUTH_API_KEY = "api-key"
61
+ _AUTH_USER_TOKEN = "user-token"
62
+
63
+ _MANAGEMENT_PATH = "/management/application"
64
+
65
+ # Magic bytes of the formats the API accepts, longest prefix first.
66
+ _IMAGE_SIGNATURES: tuple[tuple[bytes, str, str], ...] = (
67
+ (b"\x89PNG\r\n\x1a\n", "png", "image/png"),
68
+ (b"\xff\xd8\xff", "jpg", "image/jpeg"),
69
+ )
70
+
71
+ # The "data:image/png;base64," preamble browsers prepend, which the API does
72
+ # not accept.
73
+ _DATA_URL_PREFIX = re.compile(r"^data:[^;,]*(;[^;,]*)*,")
74
+
75
+
76
+ def _detect_image(raw: bytes) -> tuple[str, str]:
77
+ """Return the ``(extension, mime type)`` of ``raw``.
78
+
79
+ Raises:
80
+ Slip2SureValidationError: if ``raw`` is empty or is not a PNG or JPEG.
81
+ """
82
+ if not raw:
83
+ raise Slip2SureValidationError(
84
+ ErrorCode.FILE_REQUIRED.value, "image is empty"
85
+ )
86
+
87
+ for signature, extension, mime in _IMAGE_SIGNATURES:
88
+ if raw.startswith(signature):
89
+ return extension, mime
90
+
91
+ raise Slip2SureValidationError(
92
+ ErrorCode.FILE_NOT_SUPPORTED.value, "file not supported (PNG/JPEG only)"
93
+ )
94
+
95
+
96
+ class Slip2SureAPI:
97
+ """Client for the Slip2Sure API.
98
+
99
+ Args:
100
+ api_key: The Application API Key, sent as the ``x-api-key`` header.
101
+ Required by the slip verification and transaction endpoints.
102
+ user_api_token: The User API Token, sent as an ``Authorization``
103
+ bearer token. Required by the credit and application management
104
+ endpoints, which the Application API Key cannot authenticate.
105
+ base_url: Override the API root, for staging or for a local mock.
106
+ timeout: Seconds bounding one whole call including retries. ``None``
107
+ disables the timeout.
108
+ max_retries: How many times a retryable request is retried.
109
+ retry_backoff: Base delay in seconds for exponential backoff.
110
+ session: An ``aiohttp.ClientSession`` to use. When given, the caller
111
+ keeps ownership and is responsible for closing it; otherwise the
112
+ client creates one lazily and closes it in :meth:`close`.
113
+
114
+ The client reuses a single session across calls, so prefer keeping one
115
+ instance alive over building one per request::
116
+
117
+ async with Slip2SureAPI("YOUR_API_KEY") as client:
118
+ result = await client.scanBankSlipByPayload("YOUR_QR_CODE")
119
+
120
+ Every method is available in camelCase, matching earlier releases, and in
121
+ snake_case for callers who prefer PEP 8 naming.
122
+ """
123
+
124
+ def __init__(
125
+ self,
126
+ api_key: str = "",
127
+ *,
128
+ user_api_token: str = "",
129
+ base_url: str = DEFAULT_BASE_URL,
130
+ timeout: float | None = DEFAULT_TIMEOUT,
131
+ max_retries: int = DEFAULT_MAX_RETRIES,
132
+ retry_backoff: float = DEFAULT_RETRY_BACKOFF,
133
+ session: aiohttp.ClientSession | None = None,
134
+ ):
135
+ self._api_key = api_key
136
+ self._user_api_token = user_api_token
137
+ self._base_url = base_url.rstrip("/")
138
+ self._timeout = timeout
139
+ self._max_retries = max(0, max_retries)
140
+ self._retry_backoff = (
141
+ retry_backoff if retry_backoff > 0 else DEFAULT_RETRY_BACKOFF
142
+ )
143
+ self._session = session
144
+ self._owns_session = session is None
145
+
146
+ # --- Slip verification -------------------------------------------------
147
+
148
+ async def scanTruemoneySlip(self, file: bytes) -> Slip2SureTruemoney:
149
+ """Verify a TrueMoney Wallet slip image against the v2 endpoint.
150
+
151
+ v2 also returns the slip's payload and both parties' names.
152
+
153
+ Args:
154
+ file: The slip image as bytes. Must be PNG or JPEG; the format is
155
+ detected from the contents, not from a filename.
156
+
157
+ Raises:
158
+ Slip2SureError: if the API rejects the request or is unreachable.
159
+ """
160
+ payload = await self._scan_image("/truemoney/v2/verify", file)
161
+ return Slip2SureTruemoney(**payload)
162
+
163
+ async def scanTruemoneySlipV1(self, file: bytes) -> Slip2SureTruemoney:
164
+ """Verify a TrueMoney Wallet slip image against the v1 endpoint.
165
+
166
+ Deprecated: use :meth:`scanTruemoneySlip`, which calls v2. v1 omits
167
+ ``payload``, ``account_from_name`` and ``account_to_name``.
168
+ """
169
+ payload = await self._scan_image("/truemoney/v1/verify", file)
170
+ return Slip2SureTruemoney(**payload)
171
+
172
+ async def scanBankSlipByPayload(self, payload: str) -> Slip2SureBankSlip:
173
+ """Verify a bank slip from the payload encoded in its QR code."""
174
+ if not payload:
175
+ raise Slip2SureValidationError(
176
+ ErrorCode.VALIDATE_ERROR.value, "payload is empty"
177
+ )
178
+
179
+ body = await self._request(
180
+ "POST",
181
+ "/bank/v0/verifyByPayload",
182
+ json_body={"payload": payload},
183
+ retryable=True,
184
+ )
185
+ return Slip2SureBankSlip(**body)
186
+
187
+ async def scanBankSlipByFile(self, file: bytes) -> Slip2SureBankSlip:
188
+ """Verify a bank slip from its image.
189
+
190
+ Use this when the QR code has not been decoded yet.
191
+
192
+ Args:
193
+ file: The slip image as bytes. Must be PNG or JPEG.
194
+ """
195
+ payload = await self._scan_image("/bank/v0/verifyByFile", file)
196
+ return Slip2SureBankSlip(**payload)
197
+
198
+ async def scanBankSlipByBase64(self, encoded: str) -> Slip2SureBankSlip:
199
+ """Verify a bank slip from a base64 encoded image.
200
+
201
+ A ``data:image/png;base64,`` prefix is stripped if present, since the
202
+ API expects the bare encoding.
203
+ """
204
+ encoded = _DATA_URL_PREFIX.sub("", encoded.strip()).strip()
205
+ if not encoded:
206
+ raise Slip2SureValidationError(
207
+ ErrorCode.VALIDATE_ERROR.value, "base64 image is empty"
208
+ )
209
+
210
+ body = await self._request(
211
+ "POST",
212
+ "/bank/v0/verifyByBase64",
213
+ json_body={"payload": encoded},
214
+ retryable=True,
215
+ )
216
+ return Slip2SureBankSlip(**body)
217
+
218
+ async def scanBankSlipByImage(self, file: bytes) -> Slip2SureBankSlip:
219
+ """Verify a bank slip by base64 encoding ``file`` for the caller.
220
+
221
+ Prefer :meth:`scanBankSlipByFile`, which uploads the bytes directly
222
+ and avoids the roughly one third size increase of base64. This exists
223
+ for callers whose infrastructure cannot send multipart bodies.
224
+ """
225
+ _detect_image(file)
226
+ return await self.scanBankSlipByBase64(base64.b64encode(file).decode("ascii"))
227
+
228
+ # --- Transactions ------------------------------------------------------
229
+
230
+ async def getAllTransactions(
231
+ self,
232
+ *,
233
+ page: int | None = None,
234
+ size: int | None = None,
235
+ from_: datetime | str | None = None,
236
+ to: datetime | str | None = None,
237
+ paid_at: datetime | str | None = None,
238
+ slip_type: SlipType | str | None = None,
239
+ status: TransactionStatus | str | None = None,
240
+ ) -> Slip2SureTransactionList:
241
+ """List the application's verification history.
242
+
243
+ Args:
244
+ page: Zero based page number. The API defaults to 0.
245
+ size: Items per page. The API defaults to 20.
246
+ from_: Only slips scanned at or after this time. Named with a
247
+ trailing underscore because ``from`` is a Python keyword.
248
+ to: Only slips scanned at or before this time.
249
+ paid_at: Only transfers made at this time.
250
+ slip_type: Restrict to one :class:`SlipType`.
251
+ status: Restrict to one :class:`TransactionStatus`.
252
+ """
253
+ params: dict[str, str] = {}
254
+ # Compared against None rather than truthiness so page 0, a real
255
+ # page, is still sent.
256
+ if page is not None:
257
+ params["page"] = str(page)
258
+ if size is not None:
259
+ params["size"] = str(size)
260
+ if from_ is not None:
261
+ params["from"] = _format_time(from_)
262
+ if to is not None:
263
+ params["to"] = _format_time(to)
264
+ if paid_at is not None:
265
+ params["paid_at"] = _format_time(paid_at)
266
+ if slip_type is not None:
267
+ params["slip_type"] = _enum_value(slip_type)
268
+ if status is not None:
269
+ params["status"] = _enum_value(status)
270
+
271
+ body = await self._request(
272
+ "GET",
273
+ "/transaction/getAllTransactions",
274
+ params=params,
275
+ retryable=True,
276
+ )
277
+ return Slip2SureTransactionList(**body)
278
+
279
+ # --- User --------------------------------------------------------------
280
+
281
+ async def getUserCredit(self) -> Slip2SureUserCredit:
282
+ """Return the account's remaining credit.
283
+
284
+ Authenticates with the User API Token, so the client needs
285
+ ``user_api_token``. The Application API Key was accepted here until
286
+ 3 October 2026 and no longer is.
287
+ """
288
+ body = await self._request(
289
+ "GET", "/user/credit", auth=_AUTH_USER_TOKEN, retryable=True
290
+ )
291
+ return Slip2SureUserCredit(**body)
292
+
293
+ # --- Application management --------------------------------------------
294
+ #
295
+ # Every endpoint below authenticates with the User API Token; the
296
+ # Application API Key cannot authenticate them.
297
+
298
+ async def getApplications(self) -> list[Slip2SureApplication]:
299
+ """List the user's active applications."""
300
+ body = await self._request(
301
+ "GET", _MANAGEMENT_PATH, auth=_AUTH_USER_TOKEN, retryable=True, expect=list
302
+ )
303
+ return [Slip2SureApplication(**item) for item in body]
304
+
305
+ async def getApplication(self, app_id: str) -> Slip2SureApplication:
306
+ """Return one application by ID."""
307
+ body = await self._request(
308
+ "GET",
309
+ _application_path(app_id),
310
+ auth=_AUTH_USER_TOKEN,
311
+ retryable=True,
312
+ )
313
+ return Slip2SureApplication(**body)
314
+
315
+ async def createApplication(
316
+ self,
317
+ name: str,
318
+ description: str = "",
319
+ whitelist_ips: list[str] | None = None,
320
+ ) -> Slip2SureApplication:
321
+ """Create an application and return it with its API key.
322
+
323
+ The API key is returned in full only here, so store it before
324
+ discarding the result. This call is never retried automatically,
325
+ because a retried gateway error could create a second application.
326
+
327
+ Args:
328
+ whitelist_ips: IPs allowed to use the key. Pass ``["*"]`` to allow
329
+ every IP.
330
+ """
331
+ payload = Slip2SureApplicationInput(
332
+ name=name, description=description, whitelist_ips=whitelist_ips or []
333
+ )
334
+ body = await self._request(
335
+ "POST",
336
+ _MANAGEMENT_PATH,
337
+ json_body=payload.model_dump(),
338
+ auth=_AUTH_USER_TOKEN,
339
+ )
340
+ return Slip2SureApplication(**body)
341
+
342
+ async def updateApplication(
343
+ self,
344
+ app_id: str,
345
+ name: str,
346
+ description: str = "",
347
+ whitelist_ips: list[str] | None = None,
348
+ ) -> Slip2SureApplication:
349
+ """Replace an application's name, description and IP whitelist."""
350
+ payload = Slip2SureApplicationInput(
351
+ name=name, description=description, whitelist_ips=whitelist_ips or []
352
+ )
353
+ body = await self._request(
354
+ "PUT",
355
+ _application_path(app_id),
356
+ json_body=payload.model_dump(),
357
+ auth=_AUTH_USER_TOKEN,
358
+ )
359
+ return Slip2SureApplication(**body)
360
+
361
+ async def deleteApplication(self, app_id: str) -> None:
362
+ """Delete an application. It cannot be undone through the API."""
363
+ # The API answers 204 with no body on success.
364
+ await self._request(
365
+ "DELETE",
366
+ _application_path(app_id),
367
+ auth=_AUTH_USER_TOKEN,
368
+ allow_empty=True,
369
+ )
370
+
371
+ async def getApplicationApiKey(self, app_id: str) -> Slip2SureAPIKey:
372
+ """Return an application's current API key."""
373
+ body = await self._request(
374
+ "GET",
375
+ _application_path(app_id, "/api_key"),
376
+ auth=_AUTH_USER_TOKEN,
377
+ retryable=True,
378
+ )
379
+ return Slip2SureAPIKey(**body)
380
+
381
+ async def rotateApplicationApiKey(self, app_id: str) -> Slip2SureAPIKey:
382
+ """Issue a new API key and invalidate the old one immediately.
383
+
384
+ The new key is returned in full only here. This call is never retried
385
+ automatically: a retried gateway error could rotate the key twice and
386
+ discard the key the first attempt returned.
387
+ """
388
+ body = await self._request(
389
+ "POST",
390
+ _application_path(app_id, "/api_key/rotate"),
391
+ auth=_AUTH_USER_TOKEN,
392
+ )
393
+ return Slip2SureAPIKey(**body)
394
+
395
+ # --- Lifecycle ---------------------------------------------------------
396
+
397
+ async def close(self) -> None:
398
+ """Close the underlying session, if this client created it."""
399
+ if self._session is not None and self._owns_session:
400
+ await self._session.close()
401
+ self._session = None
402
+
403
+ async def __aenter__(self) -> "Slip2SureAPI":
404
+ return self
405
+
406
+ async def __aexit__(
407
+ self,
408
+ exc_type: type[BaseException] | None,
409
+ exc: BaseException | None,
410
+ tb: TracebackType | None,
411
+ ) -> None:
412
+ await self.close()
413
+
414
+ # --- HTTP --------------------------------------------------------------
415
+
416
+ def _get_session(self) -> aiohttp.ClientSession:
417
+ if self._session is None or self._session.closed:
418
+ self._session = aiohttp.ClientSession()
419
+ self._owns_session = True
420
+ return self._session
421
+
422
+ async def _scan_image(self, path: str, file: bytes) -> dict[str, Any]:
423
+ """Upload an image to a verification endpoint."""
424
+ extension, mime = _detect_image(file)
425
+
426
+ def build_form() -> FormData:
427
+ # Rebuilt per attempt because an aiohttp FormData is consumed by
428
+ # the request that sends it and cannot be replayed on a retry.
429
+ form = FormData()
430
+ form.add_field(
431
+ "image",
432
+ file,
433
+ filename=f"{uuid.uuid4()}.{extension}",
434
+ content_type=mime,
435
+ )
436
+ return form
437
+
438
+ return await self._request(
439
+ "POST", path, form_factory=build_form, retryable=True
440
+ )
441
+
442
+ def _check_auth(self, auth: str) -> None:
443
+ """Fail locally when the credential a call needs is not configured."""
444
+ if auth == _AUTH_USER_TOKEN:
445
+ if not self._user_api_token:
446
+ raise Slip2SureError(
447
+ ErrorCode.UNAUTHORIZED.value,
448
+ "no User API Token configured; pass user_api_token",
449
+ )
450
+ elif not self._api_key:
451
+ raise Slip2SureError(
452
+ ErrorCode.UNAUTHORIZED.value, "no Application API Key configured"
453
+ )
454
+
455
+ async def _request(
456
+ self,
457
+ method: str,
458
+ path: str,
459
+ *,
460
+ json_body: dict[str, Any] | None = None,
461
+ form_factory: Callable[[], FormData] | None = None,
462
+ params: dict[str, str] | None = None,
463
+ auth: str = _AUTH_API_KEY,
464
+ retryable: bool = False,
465
+ allow_empty: bool = False,
466
+ expect: type = dict,
467
+ ) -> Any:
468
+ """Send a request, retrying transient failures, and return its JSON.
469
+
470
+ ``retryable`` is False by default so a call with a side effect that
471
+ must not happen twice, such as creating an application or rotating a
472
+ key, is never retried behind the caller's back.
473
+ """
474
+ self._check_auth(auth)
475
+
476
+ url = f"{self._base_url}{path}"
477
+ session = self._get_session()
478
+ deadline = None if self._timeout is None else time.monotonic() + self._timeout
479
+ attempts = self._max_retries if retryable else 0
480
+
481
+ last_error: Slip2SureError | None = None
482
+ retry_after = 0.0
483
+
484
+ for attempt in range(attempts + 1):
485
+ if attempt:
486
+ delay = self._backoff_for(attempt, retry_after)
487
+ if deadline is not None and time.monotonic() + delay > deadline:
488
+ break
489
+ await asyncio.sleep(delay)
490
+ retry_after = 0.0
491
+
492
+ remaining = None if deadline is None else deadline - time.monotonic()
493
+ if remaining is not None and remaining <= 0:
494
+ break
495
+
496
+ is_last = attempt == attempts
497
+
498
+ try:
499
+ async with session.request(
500
+ method,
501
+ url,
502
+ headers=self._headers(auth),
503
+ params=params or None,
504
+ json=json_body,
505
+ data=form_factory() if form_factory else None,
506
+ timeout=aiohttp.ClientTimeout(total=remaining),
507
+ ) as response:
508
+ raw = await response.read()
509
+
510
+ if response.status >= 400:
511
+ error = self._parse_error(raw, response.status)
512
+ if is_last or response.status not in _RETRYABLE_STATUS:
513
+ raise error
514
+ last_error = error
515
+ retry_after = _parse_retry_after(
516
+ response.headers.get("Retry-After")
517
+ )
518
+ continue
519
+
520
+ return self._parse_success(
521
+ raw, response.status, allow_empty=allow_empty, expect=expect
522
+ )
523
+
524
+ except (aiohttp.ClientError, asyncio.TimeoutError) as exc:
525
+ error = Slip2SureTransportError(f"request failed: {exc}")
526
+ if is_last:
527
+ raise error from exc
528
+ last_error = error
529
+ continue
530
+
531
+ raise last_error or Slip2SureTransportError("request failed: timed out")
532
+
533
+ def _headers(self, auth: str) -> dict[str, str]:
534
+ headers = {
535
+ "Accept": "application/json",
536
+ "User-Agent": f"slip2sure-py/{VERSION}",
537
+ }
538
+ if auth == _AUTH_USER_TOKEN:
539
+ headers["Authorization"] = f"Bearer {self._user_api_token}"
540
+ else:
541
+ headers["x-api-key"] = self._api_key
542
+ return headers
543
+
544
+ def _backoff_for(self, attempt: int, retry_after: float) -> float:
545
+ """Delay before ``attempt``, honouring a server Retry-After hint."""
546
+ if retry_after > 0:
547
+ return min(retry_after, _MAX_RETRY_BACKOFF)
548
+
549
+ backoff = min(self._retry_backoff * (2 ** (attempt - 1)), _MAX_RETRY_BACKOFF)
550
+ # Full jitter, so concurrent clients retrying after the same outage do
551
+ # not line up into a second thundering herd.
552
+ return backoff / 2 + random.uniform(0, backoff / 2)
553
+
554
+ @staticmethod
555
+ def _parse_error(raw: bytes, status: int) -> Slip2SureError:
556
+ """Turn an error body into an error.
557
+
558
+ Degrades gracefully when the body is not the expected JSON, which a
559
+ proxy serving an HTML error page would previously have crashed on.
560
+ """
561
+ try:
562
+ body = json.loads(raw)
563
+ result = body["result"]
564
+ except (ValueError, TypeError, KeyError):
565
+ return Slip2SureError(
566
+ ErrorCode.UNKNOWN_ERROR.value,
567
+ _body_excerpt(raw, status),
568
+ status,
569
+ )
570
+
571
+ return Slip2SureError.from_response(result, body.get("message", ""), status)
572
+
573
+ @staticmethod
574
+ def _parse_success(
575
+ raw: bytes, status: int, *, allow_empty: bool, expect: type
576
+ ) -> Any:
577
+ if allow_empty and not raw.strip():
578
+ return None
579
+ try:
580
+ body = json.loads(raw)
581
+ except ValueError:
582
+ raise Slip2SureError(
583
+ ErrorCode.UNKNOWN_ERROR.value, _body_excerpt(raw, status), status
584
+ ) from None
585
+ if not isinstance(body, expect):
586
+ raise Slip2SureError(
587
+ ErrorCode.UNKNOWN_ERROR.value, _body_excerpt(raw, status), status
588
+ )
589
+ return body
590
+
591
+ # --- snake_case aliases ------------------------------------------------
592
+ #
593
+ # The camelCase names above are what earlier releases shipped; these let
594
+ # callers use PEP 8 naming instead. Both refer to the same function.
595
+
596
+ scan_truemoney_slip = scanTruemoneySlip
597
+ scan_truemoney_slip_v1 = scanTruemoneySlipV1
598
+ scan_bank_slip_by_payload = scanBankSlipByPayload
599
+ scan_bank_slip_by_file = scanBankSlipByFile
600
+ scan_bank_slip_by_base64 = scanBankSlipByBase64
601
+ scan_bank_slip_by_image = scanBankSlipByImage
602
+ get_all_transactions = getAllTransactions
603
+ get_user_credit = getUserCredit
604
+ get_applications = getApplications
605
+ get_application = getApplication
606
+ create_application = createApplication
607
+ update_application = updateApplication
608
+ delete_application = deleteApplication
609
+ get_application_api_key = getApplicationApiKey
610
+ rotate_application_api_key = rotateApplicationApiKey
611
+
612
+
613
+ def _application_path(app_id: str, suffix: str = "") -> str:
614
+ """Build a management path, rejecting an empty or path-bearing ID."""
615
+ if not app_id:
616
+ raise Slip2SureValidationError(
617
+ ErrorCode.VALIDATE_ERROR.value, "application ID is empty"
618
+ )
619
+ if "/" in app_id:
620
+ raise Slip2SureValidationError(
621
+ ErrorCode.VALIDATE_ERROR.value, "application ID must not contain '/'"
622
+ )
623
+ return f"{_MANAGEMENT_PATH}/{app_id}{suffix}"
624
+
625
+
626
+ def _format_time(value: datetime | str) -> str:
627
+ """Render a filter timestamp as ISO 8601."""
628
+ return value.isoformat() if isinstance(value, datetime) else value
629
+
630
+
631
+ def _enum_value(value: Any) -> str:
632
+ """Accept either an enum member or its raw string."""
633
+ return value.value if isinstance(value, Enum) else str(value)
634
+
635
+
636
+ def _body_excerpt(raw: bytes, status: int) -> str:
637
+ """Describe a body that is not a Slip2Sure envelope, keeping an excerpt."""
638
+ excerpt = raw.decode("utf-8", errors="replace").strip()
639
+ if not excerpt:
640
+ return f"HTTP {status} with empty body"
641
+ if len(excerpt) > 200:
642
+ excerpt = excerpt[:200] + "..."
643
+ return f"HTTP {status}: {excerpt}"
644
+
645
+
646
+ def _parse_retry_after(value: str | None) -> float:
647
+ """Read a Retry-After header given as a delay in seconds."""
648
+ if not value:
649
+ return 0.0
650
+ try:
651
+ seconds = float(value.strip())
652
+ except ValueError:
653
+ return 0.0
654
+ return seconds if seconds > 0 else 0.0