shadpay 1.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.
shadpay/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ """ShadPay merchant API SDK for Python."""
2
+
3
+ from .client import (
4
+ ApiError,
5
+ Balance,
6
+ Client,
7
+ CreateResult,
8
+ Page,
9
+ Payment,
10
+ Refund,
11
+ Settlement,
12
+ )
13
+
14
+ __all__ = [
15
+ "ApiError",
16
+ "Balance",
17
+ "Client",
18
+ "CreateResult",
19
+ "Page",
20
+ "Payment",
21
+ "Refund",
22
+ "Settlement",
23
+ ]
24
+
25
+ __version__ = "1.2.0"
shadpay/client.py ADDED
@@ -0,0 +1,384 @@
1
+ """ShadPay merchant API client (the /v1 surface).
2
+
3
+ Thin, dependency-free wrapper over the standard response envelope and error codes. All amounts
4
+ are integer Rial — never floats, sent and returned as is.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import random
11
+ import time
12
+ import urllib.error
13
+ import urllib.parse
14
+ import urllib.request
15
+ from dataclasses import dataclass, field
16
+ from typing import Any, Generic, Optional, TypeVar
17
+
18
+ DEFAULT_TIMEOUT = 30.0
19
+
20
+ #: Sent as the User-Agent. Without it every SDK request is indistinguishable from curl
21
+ #: server-side, so nobody can tell which clients merchants run or warn a version with a bug.
22
+ VERSION = "1.2.0"
23
+
24
+ #: Extra attempts a transient failure gets. Zero disables retrying.
25
+ DEFAULT_RETRIES = 2
26
+ _USER_AGENT = f"shadpay-python/{VERSION}"
27
+
28
+ # Stable error codes returned by the API (see docs/api-design.md).
29
+ CODE_VALIDATION = "VALIDATION_ERROR"
30
+ CODE_UNAUTHENTICATED = "UNAUTHENTICATED"
31
+ CODE_IP_NOT_ALLOWED = "IP_NOT_ALLOWED"
32
+ CODE_FORBIDDEN = "FORBIDDEN"
33
+ CODE_NOT_FOUND = "NOT_FOUND"
34
+ CODE_INVALID_STATE = "INVALID_STATE"
35
+ CODE_DUPLICATE_REF = "DUPLICATE_REF"
36
+ CODE_PAYMENT_NOT_PAYABLE = "PAYMENT_NOT_PAYABLE"
37
+ # Nothing on this payment can be refunded through ShadPay: it is not verified, or no Shad wallet
38
+ # paid any of it. A card's share is refunded at the PSP.
39
+ CODE_PAYMENT_NOT_REFUNDABLE = "PAYMENT_NOT_REFUNDABLE"
40
+ # The refund asks for more than the payer's wallets paid and have not already been given back.
41
+ CODE_REFUND_EXCEEDS_REFUNDABLE = "REFUND_EXCEEDS_REFUNDABLE"
42
+ # The payment's PSP has no reverse before verify. ShadPay hides which PSP carried a payment, so
43
+ # a merchant cannot predict this — which is why it has to be reachable from here.
44
+ CODE_REVERSE_NOT_SUPPORTED = "REVERSE_NOT_SUPPORTED"
45
+ # The payment's PSP has no reverse before verify. ShadPay hides which PSP carried a payment,
46
+ # so a merchant cannot predict this — which is why it has to be reachable from here.
47
+ REVERSE_NOT_SUPPORTED = "REVERSE_NOT_SUPPORTED"
48
+ CODE_RATE_LIMITED = "RATE_LIMITED"
49
+ CODE_PSP_ERROR = "PSP_ERROR"
50
+ CODE_INTERNAL = "INTERNAL_ERROR"
51
+
52
+ T = TypeVar("T")
53
+
54
+
55
+ class ApiError(Exception):
56
+ """A non-2xx response mapped to the standard error envelope."""
57
+
58
+ def __init__(
59
+ self,
60
+ code: str,
61
+ message: str,
62
+ status: int,
63
+ details: Optional[list[dict]] = None,
64
+ retry_after: float = 0.0,
65
+ ):
66
+ super().__init__(f"shadpay: {message} ({code}, http {status})")
67
+ self.code = code
68
+ self.message = message
69
+ self.status = status
70
+ self.details = details or []
71
+ #: What the server asked for on a 429, in seconds. Zero when it sent nothing.
72
+ self.retry_after = retry_after
73
+
74
+
75
+ @dataclass
76
+ class Payment:
77
+ id: str
78
+ merchant_ref: str
79
+ amount_rial: int
80
+ state: str
81
+ created_at: str
82
+ settled_amount_rial: Optional[int] = None
83
+
84
+ @classmethod
85
+ def from_dict(cls, d: dict) -> "Payment":
86
+ return cls(
87
+ id=d["id"],
88
+ merchant_ref=d.get("merchant_ref", ""),
89
+ amount_rial=d.get("amount_rial", 0),
90
+ state=d.get("state", ""),
91
+ created_at=d.get("created_at", ""),
92
+ settled_amount_rial=d.get("settled_amount_rial"),
93
+ )
94
+
95
+
96
+ @dataclass
97
+ class CreateResult(Payment):
98
+ redirect_url: str = ""
99
+
100
+ @classmethod
101
+ def from_dict(cls, d: dict) -> "CreateResult":
102
+ p = Payment.from_dict(d)
103
+ return cls(**p.__dict__, redirect_url=d.get("redirect_url", ""))
104
+
105
+
106
+ @dataclass
107
+ class Refund:
108
+ """Money returned to the Shad wallets that paid for a payment.
109
+
110
+ ``status`` is PENDING while it is on its way back and SUCCEEDED once every wallet has it. A
111
+ pending refund completes on its own, so read it again rather than refunding again.
112
+ """
113
+
114
+ id: str
115
+ payment_id: str
116
+ merchant_refund_ref: str
117
+ amount_rial: int
118
+ status: str
119
+ created_at: str
120
+ reason: str = ""
121
+ completed_at: Optional[str] = None
122
+
123
+ @classmethod
124
+ def from_dict(cls, d: dict) -> "Refund":
125
+ return cls(
126
+ id=d["id"],
127
+ payment_id=d.get("payment_id", ""),
128
+ merchant_refund_ref=d.get("merchant_refund_ref", ""),
129
+ amount_rial=d.get("amount_rial", 0),
130
+ status=d.get("status", ""),
131
+ created_at=d.get("created_at", ""),
132
+ reason=d.get("reason", ""),
133
+ completed_at=d.get("completed_at"),
134
+ )
135
+
136
+
137
+ @dataclass
138
+ class Balance:
139
+ settleable_rial: int
140
+ settled_rial: int
141
+ updated_at: str = ""
142
+
143
+ @classmethod
144
+ def from_dict(cls, d: dict) -> "Balance":
145
+ return cls(d.get("settleable_rial", 0), d.get("settled_rial", 0), d.get("updated_at", ""))
146
+
147
+
148
+ @dataclass
149
+ class Settlement:
150
+ id: str
151
+ period_start: str
152
+ period_end: str
153
+ gross_rial: int
154
+ fee_rial: int
155
+ net_rial: int
156
+ status: str
157
+ created_at: str
158
+ reference: str = ""
159
+ settled_at: Optional[str] = None
160
+
161
+ @classmethod
162
+ def from_dict(cls, d: dict) -> "Settlement":
163
+ return cls(
164
+ id=d["id"],
165
+ period_start=d.get("period_start", ""),
166
+ period_end=d.get("period_end", ""),
167
+ gross_rial=d.get("gross_rial", 0),
168
+ fee_rial=d.get("fee_rial", 0),
169
+ net_rial=d.get("net_rial", 0),
170
+ status=d.get("status", ""),
171
+ created_at=d.get("created_at", ""),
172
+ reference=d.get("reference", ""),
173
+ settled_at=d.get("settled_at"),
174
+ )
175
+
176
+
177
+ @dataclass
178
+ class LedgerEntry:
179
+ """One signed line in the merchant's ledger.
180
+
181
+ Amounts are integer Rial: a capture is positive, a fee and a reversal are negative.
182
+ """
183
+
184
+ id: str
185
+ entry_type: str
186
+ amount_rial: int
187
+ created_at: str
188
+ payment_id: str = ""
189
+ settlement_id: str = ""
190
+
191
+ @classmethod
192
+ def from_dict(cls, d: dict) -> "LedgerEntry":
193
+ return cls(
194
+ id=d["id"],
195
+ entry_type=d.get("entry_type", ""),
196
+ amount_rial=d.get("amount_rial", 0),
197
+ created_at=d.get("created_at", ""),
198
+ payment_id=d.get("payment_id", ""),
199
+ settlement_id=d.get("settlement_id", ""),
200
+ )
201
+
202
+
203
+ @dataclass
204
+ class Page(Generic[T]):
205
+ items: list[T] = field(default_factory=list)
206
+ next_cursor: Optional[str] = None
207
+ has_more: bool = False
208
+
209
+
210
+ class Client:
211
+ """Client for one ShadPay environment authenticated with one merchant token."""
212
+
213
+ def __init__(
214
+ self,
215
+ base_url: str,
216
+ token: str,
217
+ timeout: float = DEFAULT_TIMEOUT,
218
+ retries: int = DEFAULT_RETRIES,
219
+ ):
220
+ self._base = base_url.rstrip("/")
221
+ self._token = token
222
+ self._timeout = timeout
223
+ self._retries = max(0, retries)
224
+
225
+ def create_payment(self, merchant_ref: str, amount_rial: int, callback_url: str,
226
+ shad_identifier: Optional[str] = None) -> CreateResult:
227
+ """Create a payment (idempotent on merchant_ref) and return the payer redirect URL.
228
+
229
+ shad_identifier is the paying user's Shad identifier, when you know it. It puts the
230
+ payment into the user's wallet history however they pay, and gives a card payment their
231
+ wallet to fall back on.
232
+ """
233
+ body = {
234
+ "merchant_ref": merchant_ref,
235
+ "amount_rial": amount_rial,
236
+ "callback_url": callback_url,
237
+ }
238
+ if shad_identifier:
239
+ body["shad_identifier"] = shad_identifier
240
+ data = self._request("POST", "/v1/payments", body)["data"]
241
+ return CreateResult.from_dict(data)
242
+
243
+ def get_payment(self, payment_id: str) -> Payment:
244
+ data = self._request("GET", f"/v1/payments/{urllib.parse.quote(payment_id)}")["data"]
245
+ return Payment.from_dict(data)
246
+
247
+ def verify(self, payment_id: str) -> Payment:
248
+ """Confirm a paid payment against the PSP and capture it. Idempotent."""
249
+ data = self._request("POST", f"/v1/payments/{urllib.parse.quote(payment_id)}/verify")["data"]
250
+ return Payment.from_dict(data)
251
+
252
+ def reverse(self, payment_id: str) -> Payment:
253
+ """Return the money to the payer before settlement. Idempotent."""
254
+ data = self._request("POST", f"/v1/payments/{urllib.parse.quote(payment_id)}/reverse")["data"]
255
+ return Payment.from_dict(data)
256
+
257
+ def refund(self, payment_id: str, merchant_refund_ref: str, amount_rial: int, reason: str = "") -> Refund:
258
+ """Return part or all of what the payer's Shad wallets paid for a verified payment.
259
+
260
+ Each wallet gets back its own share. A card's share is not refunded here; it is returned
261
+ at the PSP. Idempotent on merchant_refund_ref.
262
+ """
263
+ body = {"merchant_refund_ref": merchant_refund_ref, "amount_rial": amount_rial}
264
+ if reason:
265
+ body["reason"] = reason
266
+ data = self._request("POST", f"/v1/payments/{urllib.parse.quote(payment_id)}/refunds", body)["data"]
267
+ return Refund.from_dict(data)
268
+
269
+ def list_refunds(self, payment_id: str) -> list[Refund]:
270
+ """A payment's refunds, oldest first."""
271
+ return self._list(f"/v1/payments/{urllib.parse.quote(payment_id)}/refunds", Refund.from_dict, None, 0).items
272
+
273
+ def list_payments(self, cursor: Optional[str] = None, limit: int = 0) -> Page[Payment]:
274
+ return self._list("/v1/payments", Payment.from_dict, cursor, limit)
275
+
276
+ def list_ledger(self, cursor: Optional[str] = None, limit: int = 0) -> "Page[LedgerEntry]":
277
+ """A page of the merchant's ledger entries, newest first.
278
+
279
+ This is the statement behind the balance: what each figure is made of.
280
+ """
281
+ return self._list("/v1/ledger", LedgerEntry.from_dict, cursor, limit)
282
+
283
+ def list_settlements(self, cursor: Optional[str] = None, limit: int = 0) -> Page[Settlement]:
284
+ return self._list("/v1/settlements", Settlement.from_dict, cursor, limit)
285
+
286
+ def balance(self) -> Balance:
287
+ return Balance.from_dict(self._request("GET", "/v1/balance")["data"])
288
+
289
+ def _list(self, path: str, parse, cursor: Optional[str], limit: int) -> Page:
290
+ params = {}
291
+ if cursor:
292
+ params["cursor"] = cursor
293
+ if limit and limit > 0:
294
+ params["limit"] = str(limit)
295
+ if params:
296
+ path = f"{path}?{urllib.parse.urlencode(params)}"
297
+ env = self._request("GET", path)
298
+ page: Page = Page(items=[parse(x) for x in (env.get("data") or [])])
299
+ pg = (env.get("meta") or {}).get("pagination") or {}
300
+ page.next_cursor = pg.get("next_cursor")
301
+ page.has_more = bool(pg.get("has_more"))
302
+ return page
303
+
304
+ def _request(self, method: str, path: str, body: Optional[dict] = None) -> dict:
305
+ """Send the request, retrying a transient failure.
306
+
307
+ Retrying is safe on every operation this client exposes, and that is a property of the
308
+ API rather than a hope: create is idempotent on merchant_ref, verify and reverse are
309
+ idempotent by state machine and row lock, and reads are reads. Without this every
310
+ integrator writes the loop themselves against a contract they have to infer.
311
+ """
312
+ attempt = 0
313
+ while True:
314
+ try:
315
+ return self._attempt(method, path, body)
316
+ except ApiError as exc:
317
+ if attempt >= self._retries or not _retryable_status(exc.status):
318
+ raise
319
+ delay = exc.retry_after or _backoff(attempt)
320
+ except urllib.error.URLError:
321
+ # The request may not have arrived at all; every operation here is idempotent.
322
+ if attempt >= self._retries:
323
+ raise
324
+ delay = _backoff(attempt)
325
+ time.sleep(delay)
326
+ attempt += 1
327
+
328
+ def _attempt(self, method: str, path: str, body: Optional[dict] = None) -> dict:
329
+ headers = {"X-Token": self._token, "Accept": "application/json", "User-Agent": _USER_AGENT}
330
+ payload = None
331
+ if body is not None:
332
+ payload = json.dumps(body).encode("utf-8")
333
+ headers["Content-Type"] = "application/json"
334
+ req = urllib.request.Request(self._base + path, data=payload, headers=headers, method=method)
335
+ try:
336
+ with urllib.request.urlopen(req, timeout=self._timeout) as resp:
337
+ raw = resp.read()
338
+ except urllib.error.HTTPError as exc:
339
+ raw = exc.read()
340
+ env = _parse(raw)
341
+ err = (env or {}).get("error") or {"code": CODE_INTERNAL, "message": "request failed"}
342
+ retry_after = 0.0
343
+ try:
344
+ secs = int((exc.headers or {}).get("Retry-After", "0"))
345
+ retry_after = float(secs) if secs > 0 else 0.0
346
+ except (TypeError, ValueError):
347
+ retry_after = 0.0
348
+ raise ApiError(
349
+ err.get("code", CODE_INTERNAL), err.get("message", ""), exc.code,
350
+ err.get("details"), retry_after,
351
+ ) from None
352
+ env = _parse(raw) or {}
353
+ if env.get("error"):
354
+ err = env["error"]
355
+ raise ApiError(err.get("code", CODE_INTERNAL), err.get("message", ""), 200, err.get("details"))
356
+ return env
357
+
358
+
359
+ def _retryable_status(status: int) -> bool:
360
+ """Only 429, 502, 503 and 504.
361
+
362
+ Every other 4xx means the same thing however many times it is sent, and retrying it wastes
363
+ the caller's time and ours.
364
+ """
365
+ return status in (429, 502, 503, 504)
366
+
367
+
368
+ def _backoff(attempt: int) -> float:
369
+ """250ms, 500ms, 1s… capped, with jitter.
370
+
371
+ A fixed-delay loop from every integrator at once is how a struggling service is kept
372
+ struggling.
373
+ """
374
+ base = min(0.25 * (2 ** attempt), 4.0)
375
+ return base + random.uniform(0, base / 2)
376
+
377
+
378
+ def _parse(raw: bytes) -> Optional[dict[str, Any]]:
379
+ if not raw:
380
+ return None
381
+ try:
382
+ return json.loads(raw.decode("utf-8"))
383
+ except (ValueError, UnicodeDecodeError):
384
+ return None
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: shadpay
3
+ Version: 1.2.0
4
+ Summary: Official Python client library for the ShadPay merchant API (/v1). All amounts are integer Rial.
5
+ Author: ShadPay
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/shadpay/sdk/tree/main/python
8
+ Project-URL: Repository, https://github.com/shadpay/sdk
9
+ Project-URL: Issues, https://github.com/shadpay/sdk/issues
10
+ Keywords: shadpay,payment,gateway,iran,psp,sdk
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.9
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Dynamic: license-file
25
+
26
+ # ShadPay Python SDK
27
+
28
+ Thin, dependency-free client for the ShadPay merchant API (`/v1`). Python 3.9+. All amounts are
29
+ **integer Rial**.
30
+
31
+ ```bash
32
+ pip install shadpay
33
+ ```
34
+
35
+ ## Usage
36
+
37
+ ```python
38
+ from shadpay import Client, ApiError
39
+
40
+ client = Client("https://pay.shad.ir/backend", "YOUR_MERCHANT_TOKEN")
41
+
42
+ # Create a payment (idempotent on merchant_ref) and redirect the payer.
43
+ res = client.create_payment(
44
+ merchant_ref="order-1001",
45
+ amount_rial=500_000, # 500,000 Rial
46
+ callback_url="https://shop.example/pay/return",
47
+ )
48
+ # redirect the browser to res.redirect_url
49
+
50
+ # After the payer returns, verify server-to-server for the real outcome.
51
+ try:
52
+ p = client.verify(res.id)
53
+ print(p.state) # "VERIFIED" | "FAILED" | ...
54
+ except ApiError as e:
55
+ print(e.code, e.message)
56
+ ```
57
+
58
+ ## Methods
59
+ `create_payment` · `get_payment` · `verify` · `reverse` · `refund` · `list_refunds` · `list_payments` · `list_ledger` · `list_settlements`
60
+ · `balance`.
61
+
62
+ ## Notes
63
+ - **Auth:** token sent as `X-Token`; your server must be on the merchant IP allowlist.
64
+ - **Idempotency:** reuse `merchant_ref` to safely retry create.
65
+ - **Refunds:** `refund(payment_id, merchant_refund_ref, amount_rial, reason="")` returns only what
66
+ the payer's Shad wallets paid; a card's share is refunded at the PSP. Reuse `merchant_refund_ref`
67
+ to retry safely. A `PENDING` refund completes on its own — read it with `list_refunds`.
68
+ - **Errors:** non-2xx responses raise `ApiError` with a stable `.code` (e.g.
69
+ `PAYMENT_NOT_PAYABLE`).
70
+ - **The redirect result is non-authoritative** — always `verify` to learn the outcome.
71
+
72
+ ## Develop
73
+ ```bash
74
+ python -m unittest discover -s tests
75
+ ```
76
+
77
+ ## Naming the payer
78
+
79
+ If you know the paying user's Shad identifier, pass it when you create the payment. It is
80
+ optional. It puts the payment into the user's ShadPay wallet history whether they pay from a wallet
81
+ or by card, and gives a card payment their wallet to fall back on if the bank cannot return money
82
+ to the card. If the user signs in at the checkout, their own sign-in takes its place.
83
+
84
+ ```python
85
+ client.create_payment("order-1001", 500_000, "https://shop.example/pay/return",
86
+ shad_identifier=user.shad_identifier)
87
+ ```
@@ -0,0 +1,7 @@
1
+ shadpay/__init__.py,sha256=_jLCfscvuX1QwrAmsMyitzpkIA35uvwb3L_wPaDznZM,338
2
+ shadpay/client.py,sha256=xQgLPNibaVYFFLY9kelPWAK0I0R-2uh7wsNmILs82NE,13865
3
+ shadpay-1.2.0.dist-info/licenses/LICENSE,sha256=lC0AftXUUtE2oiF3vSNRFIp6dmnAr2yC60yUoWZyxmU,1064
4
+ shadpay-1.2.0.dist-info/METADATA,sha256=6znoDT34eK9ehVZH_Otx26nOKtYkb66vUnbzLL0dYg8,3221
5
+ shadpay-1.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ shadpay-1.2.0.dist-info/top_level.txt,sha256=adaYpDZMJV-BOSu7asp_jEv3HB2ZdTjRjOPRsX7MOeU,8
7
+ shadpay-1.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ShadPay
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ shadpay