varizet 0.2.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.
- varizet/__init__.py +93 -0
- varizet/_base.py +157 -0
- varizet/_client.py +679 -0
- varizet/_errors.py +123 -0
- varizet/_models.py +503 -0
- varizet/_specs.py +301 -0
- varizet/_version.py +1 -0
- varizet/contrib/__init__.py +2 -0
- varizet/contrib/django.py +98 -0
- varizet/contrib/fastapi.py +57 -0
- varizet/formatting.py +24 -0
- varizet/py.typed +0 -0
- varizet/webhooks.py +166 -0
- varizet-0.2.0.dist-info/METADATA +248 -0
- varizet-0.2.0.dist-info/RECORD +17 -0
- varizet-0.2.0.dist-info/WHEEL +4 -0
- varizet-0.2.0.dist-info/licenses/LICENSE +21 -0
varizet/__init__.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Varizet (واریزت) Python SDK: the public ``/v1`` API, webhook verification and sandbox helpers.
|
|
2
|
+
|
|
3
|
+
Money is ``int`` rial everywhere; timestamps are aware UTC ``datetime`` objects.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from ._base import API_VERSION, DEFAULT_BASE_URL
|
|
7
|
+
from ._client import AsyncVarizet, Varizet
|
|
8
|
+
from ._errors import (
|
|
9
|
+
APIConnectionError,
|
|
10
|
+
APIError,
|
|
11
|
+
APIServerError,
|
|
12
|
+
APITimeoutError,
|
|
13
|
+
AuthenticationError,
|
|
14
|
+
ConflictError,
|
|
15
|
+
InvalidRequestError,
|
|
16
|
+
NotFoundError,
|
|
17
|
+
PermissionDeniedError,
|
|
18
|
+
RateLimitError,
|
|
19
|
+
ValidationError,
|
|
20
|
+
VarizetError,
|
|
21
|
+
)
|
|
22
|
+
from ._models import (
|
|
23
|
+
ORDER_STATUSES,
|
|
24
|
+
WEBHOOK_EVENT_TYPES,
|
|
25
|
+
ApiKeyIdentity,
|
|
26
|
+
CreatedWebhookEndpoint,
|
|
27
|
+
Customer,
|
|
28
|
+
Deleted,
|
|
29
|
+
Deposit,
|
|
30
|
+
EventResent,
|
|
31
|
+
Order,
|
|
32
|
+
OrderDestination,
|
|
33
|
+
OrderMatch,
|
|
34
|
+
Page,
|
|
35
|
+
Refund,
|
|
36
|
+
RotatedSecret,
|
|
37
|
+
StoreRef,
|
|
38
|
+
WebhookEndpoint,
|
|
39
|
+
WebhookEvent,
|
|
40
|
+
WebhookPingResult,
|
|
41
|
+
)
|
|
42
|
+
from ._version import __version__
|
|
43
|
+
from .formatting import format_rial, to_persian_digits
|
|
44
|
+
from .webhooks import (
|
|
45
|
+
SIGNATURE_HEADER,
|
|
46
|
+
WebhookSignatureError,
|
|
47
|
+
construct_event,
|
|
48
|
+
verify_signature,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
__all__ = [
|
|
52
|
+
"API_VERSION",
|
|
53
|
+
"DEFAULT_BASE_URL",
|
|
54
|
+
"ORDER_STATUSES",
|
|
55
|
+
"SIGNATURE_HEADER",
|
|
56
|
+
"WEBHOOK_EVENT_TYPES",
|
|
57
|
+
"APIConnectionError",
|
|
58
|
+
"APIError",
|
|
59
|
+
"APIServerError",
|
|
60
|
+
"APITimeoutError",
|
|
61
|
+
"ApiKeyIdentity",
|
|
62
|
+
"AsyncVarizet",
|
|
63
|
+
"AuthenticationError",
|
|
64
|
+
"ConflictError",
|
|
65
|
+
"CreatedWebhookEndpoint",
|
|
66
|
+
"Customer",
|
|
67
|
+
"Deleted",
|
|
68
|
+
"Deposit",
|
|
69
|
+
"EventResent",
|
|
70
|
+
"InvalidRequestError",
|
|
71
|
+
"NotFoundError",
|
|
72
|
+
"Order",
|
|
73
|
+
"OrderDestination",
|
|
74
|
+
"OrderMatch",
|
|
75
|
+
"Page",
|
|
76
|
+
"PermissionDeniedError",
|
|
77
|
+
"RateLimitError",
|
|
78
|
+
"Refund",
|
|
79
|
+
"RotatedSecret",
|
|
80
|
+
"StoreRef",
|
|
81
|
+
"ValidationError",
|
|
82
|
+
"Varizet",
|
|
83
|
+
"VarizetError",
|
|
84
|
+
"WebhookEndpoint",
|
|
85
|
+
"WebhookEvent",
|
|
86
|
+
"WebhookPingResult",
|
|
87
|
+
"WebhookSignatureError",
|
|
88
|
+
"__version__",
|
|
89
|
+
"construct_event",
|
|
90
|
+
"format_rial",
|
|
91
|
+
"to_persian_digits",
|
|
92
|
+
"verify_signature",
|
|
93
|
+
]
|
varizet/_base.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Request building, retries and error mapping shared by the sync and async clients."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import random
|
|
8
|
+
import re
|
|
9
|
+
import uuid
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any
|
|
13
|
+
from urllib.parse import quote
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
from ._errors import APIConnectionError, APIError, RateLimitError, error_class
|
|
18
|
+
from ._version import __version__
|
|
19
|
+
|
|
20
|
+
API_VERSION = "2026-10-01"
|
|
21
|
+
DEFAULT_BASE_URL = "https://api.varizet.ir"
|
|
22
|
+
DEFAULT_TIMEOUT = 30.0
|
|
23
|
+
DEFAULT_MAX_RETRIES = 2
|
|
24
|
+
#: Answers worth one more try (the request is safe to repeat: GET, or a POST with its key).
|
|
25
|
+
RETRY_STATUSES = frozenset({500, 502, 503, 504})
|
|
26
|
+
_KEY = re.compile(r"vz_(live|test)_[0-9A-Za-z]+")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class PreparedRequest:
|
|
31
|
+
method: str
|
|
32
|
+
path: str
|
|
33
|
+
params: Mapping[str, str] | None
|
|
34
|
+
body: bytes | None
|
|
35
|
+
headers: Mapping[str, str]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def segment(value: str) -> str:
|
|
39
|
+
"""One path segment (ids, codes), percent-encoded."""
|
|
40
|
+
if not value:
|
|
41
|
+
raise ValueError("an id is required")
|
|
42
|
+
return quote(value, safe="")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class BaseClient:
|
|
46
|
+
def __init__(
|
|
47
|
+
self,
|
|
48
|
+
api_key: str | None,
|
|
49
|
+
*,
|
|
50
|
+
base_url: str | None,
|
|
51
|
+
timeout: float,
|
|
52
|
+
max_retries: int,
|
|
53
|
+
app_info: str | None,
|
|
54
|
+
) -> None:
|
|
55
|
+
key = api_key or os.environ.get("VARIZET_API_KEY")
|
|
56
|
+
if not key or not _KEY.fullmatch(key):
|
|
57
|
+
raise ValueError("api_key must be a vz_live_… or vz_test_… key (or set VARIZET_API_KEY)")
|
|
58
|
+
self._api_key = key
|
|
59
|
+
self.base_url = (base_url or os.environ.get("VARIZET_API_BASE") or DEFAULT_BASE_URL).rstrip("/")
|
|
60
|
+
self.timeout = timeout
|
|
61
|
+
self.max_retries = max(0, max_retries)
|
|
62
|
+
self._user_agent = f"varizet-python/{__version__}" + (f" {app_info}" if app_info else "")
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def livemode(self) -> bool:
|
|
66
|
+
return self._api_key.startswith("vz_live_")
|
|
67
|
+
|
|
68
|
+
def __repr__(self) -> str:
|
|
69
|
+
mode = "live" if self.livemode else "test"
|
|
70
|
+
return f"{type(self).__name__}(base_url={self.base_url!r}, mode={mode!r})"
|
|
71
|
+
|
|
72
|
+
def _prepare(
|
|
73
|
+
self,
|
|
74
|
+
method: str,
|
|
75
|
+
path: str,
|
|
76
|
+
*,
|
|
77
|
+
params: Mapping[str, str | None] | None = None,
|
|
78
|
+
body: Any = None,
|
|
79
|
+
idempotency_key: str | None = None,
|
|
80
|
+
) -> PreparedRequest:
|
|
81
|
+
headers = {
|
|
82
|
+
"Authorization": f"Bearer {self._api_key}",
|
|
83
|
+
"Accept": "application/json",
|
|
84
|
+
"Varizet-Version": API_VERSION,
|
|
85
|
+
"User-Agent": self._user_agent,
|
|
86
|
+
}
|
|
87
|
+
if method == "POST":
|
|
88
|
+
# every POST carries a key, so a retry after a lost answer can never act twice
|
|
89
|
+
headers["Idempotency-Key"] = idempotency_key or str(uuid.uuid4())
|
|
90
|
+
raw: bytes | None = None
|
|
91
|
+
if body is not None:
|
|
92
|
+
headers["Content-Type"] = "application/json"
|
|
93
|
+
raw = json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
|
94
|
+
clean = {k: v for k, v in (params or {}).items() if v is not None}
|
|
95
|
+
return PreparedRequest(method, path, clean or None, raw, headers)
|
|
96
|
+
|
|
97
|
+
def _url(self, path: str) -> str:
|
|
98
|
+
return f"{self.base_url}{path}"
|
|
99
|
+
|
|
100
|
+
def _retry_delay(self, attempt: int, response: httpx.Response | None) -> float:
|
|
101
|
+
retry_after = _retry_after(response)
|
|
102
|
+
if retry_after is not None:
|
|
103
|
+
return min(retry_after, 30.0)
|
|
104
|
+
return min(0.5 * 2.0**attempt, 8.0) * (0.75 + random.random() / 2) # noqa: S311 (jitter)
|
|
105
|
+
|
|
106
|
+
def _should_retry_status(self, attempt: int, response: httpx.Response) -> bool:
|
|
107
|
+
return attempt < self.max_retries and response.status_code in RETRY_STATUSES
|
|
108
|
+
|
|
109
|
+
def _parse(self, response: httpx.Response) -> Any:
|
|
110
|
+
try:
|
|
111
|
+
data = response.json() if response.content else None
|
|
112
|
+
except ValueError:
|
|
113
|
+
data = None
|
|
114
|
+
if response.is_success:
|
|
115
|
+
if data is None and response.content:
|
|
116
|
+
raise APIConnectionError(f"Varizet answered {response.status_code} with a non-JSON body")
|
|
117
|
+
return data
|
|
118
|
+
raise _api_error(response, data)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _retry_after(response: httpx.Response | None) -> float | None:
|
|
122
|
+
if response is None:
|
|
123
|
+
return None
|
|
124
|
+
value = response.headers.get("retry-after")
|
|
125
|
+
try:
|
|
126
|
+
return max(0.0, float(value)) if value is not None else None
|
|
127
|
+
except ValueError:
|
|
128
|
+
return None
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _api_error(response: httpx.Response, data: Any) -> APIError:
|
|
132
|
+
error = data.get("error") if isinstance(data, Mapping) else None
|
|
133
|
+
status = response.status_code
|
|
134
|
+
request_id = response.headers.get("x-request-id")
|
|
135
|
+
if isinstance(error, Mapping) and isinstance(error.get("code"), str):
|
|
136
|
+
kwargs: dict[str, Any] = {
|
|
137
|
+
"status": status,
|
|
138
|
+
"type": str(error.get("type") or ""),
|
|
139
|
+
"code": str(error["code"]),
|
|
140
|
+
"message": str(error.get("message") or ""),
|
|
141
|
+
"param": error.get("param") if isinstance(error.get("param"), str) else None,
|
|
142
|
+
"request_id": error.get("request_id") if isinstance(error.get("request_id"), str) else request_id,
|
|
143
|
+
"body": data,
|
|
144
|
+
}
|
|
145
|
+
else:
|
|
146
|
+
kwargs = {
|
|
147
|
+
"status": status,
|
|
148
|
+
"type": "api_error" if status >= 500 else "invalid_request",
|
|
149
|
+
"code": f"http_{status}",
|
|
150
|
+
"message": f"HTTP {status}",
|
|
151
|
+
"request_id": request_id,
|
|
152
|
+
"body": data,
|
|
153
|
+
}
|
|
154
|
+
cls = error_class(status, kwargs["type"])
|
|
155
|
+
if cls is RateLimitError:
|
|
156
|
+
return RateLimitError(retry_after=_retry_after(response), **kwargs)
|
|
157
|
+
return cls(**kwargs)
|