shadpay 1.2.0__tar.gz

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-1.2.0/LICENSE ADDED
@@ -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.
shadpay-1.2.0/PKG-INFO ADDED
@@ -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,62 @@
1
+ # ShadPay Python SDK
2
+
3
+ Thin, dependency-free client for the ShadPay merchant API (`/v1`). Python 3.9+. All amounts are
4
+ **integer Rial**.
5
+
6
+ ```bash
7
+ pip install shadpay
8
+ ```
9
+
10
+ ## Usage
11
+
12
+ ```python
13
+ from shadpay import Client, ApiError
14
+
15
+ client = Client("https://pay.shad.ir/backend", "YOUR_MERCHANT_TOKEN")
16
+
17
+ # Create a payment (idempotent on merchant_ref) and redirect the payer.
18
+ res = client.create_payment(
19
+ merchant_ref="order-1001",
20
+ amount_rial=500_000, # 500,000 Rial
21
+ callback_url="https://shop.example/pay/return",
22
+ )
23
+ # redirect the browser to res.redirect_url
24
+
25
+ # After the payer returns, verify server-to-server for the real outcome.
26
+ try:
27
+ p = client.verify(res.id)
28
+ print(p.state) # "VERIFIED" | "FAILED" | ...
29
+ except ApiError as e:
30
+ print(e.code, e.message)
31
+ ```
32
+
33
+ ## Methods
34
+ `create_payment` · `get_payment` · `verify` · `reverse` · `refund` · `list_refunds` · `list_payments` · `list_ledger` · `list_settlements`
35
+ · `balance`.
36
+
37
+ ## Notes
38
+ - **Auth:** token sent as `X-Token`; your server must be on the merchant IP allowlist.
39
+ - **Idempotency:** reuse `merchant_ref` to safely retry create.
40
+ - **Refunds:** `refund(payment_id, merchant_refund_ref, amount_rial, reason="")` returns only what
41
+ the payer's Shad wallets paid; a card's share is refunded at the PSP. Reuse `merchant_refund_ref`
42
+ to retry safely. A `PENDING` refund completes on its own — read it with `list_refunds`.
43
+ - **Errors:** non-2xx responses raise `ApiError` with a stable `.code` (e.g.
44
+ `PAYMENT_NOT_PAYABLE`).
45
+ - **The redirect result is non-authoritative** — always `verify` to learn the outcome.
46
+
47
+ ## Develop
48
+ ```bash
49
+ python -m unittest discover -s tests
50
+ ```
51
+
52
+ ## Naming the payer
53
+
54
+ If you know the paying user's Shad identifier, pass it when you create the payment. It is
55
+ optional. It puts the payment into the user's ShadPay wallet history whether they pay from a wallet
56
+ or by card, and gives a card payment their wallet to fall back on if the bank cannot return money
57
+ to the card. If the user signs in at the checkout, their own sign-in takes its place.
58
+
59
+ ```python
60
+ client.create_payment("order-1001", 500_000, "https://shop.example/pay/return",
61
+ shad_identifier=user.shad_identifier)
62
+ ```
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "shadpay"
7
+ version = "1.2.0"
8
+ description = "Official Python client library for the ShadPay merchant API (/v1). All amounts are integer Rial."
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ authors = [{ name = "ShadPay" }]
12
+ keywords = ["shadpay", "payment", "gateway", "iran", "psp", "sdk"]
13
+ classifiers = [
14
+ "Development Status :: 5 - Production/Stable",
15
+ "Intended Audience :: Developers",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.9",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Typing :: Typed",
24
+ ]
25
+ requires-python = ">=3.9"
26
+ dependencies = []
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/shadpay/sdk/tree/main/python"
30
+ Repository = "https://github.com/shadpay/sdk"
31
+ Issues = "https://github.com/shadpay/sdk/issues"
32
+
33
+ [tool.setuptools]
34
+ packages = ["shadpay"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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"
@@ -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,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ shadpay/__init__.py
5
+ shadpay/client.py
6
+ shadpay.egg-info/PKG-INFO
7
+ shadpay.egg-info/SOURCES.txt
8
+ shadpay.egg-info/dependency_links.txt
9
+ shadpay.egg-info/top_level.txt
10
+ tests/test_client.py
11
+ tests/test_contract.py
@@ -0,0 +1 @@
1
+ shadpay
@@ -0,0 +1,152 @@
1
+ """Tests against a local stub HTTP server (dependency-free)."""
2
+
3
+ import io
4
+ import json
5
+ import threading
6
+ import unittest
7
+ import urllib.error
8
+ from unittest import mock
9
+ from http.server import BaseHTTPRequestHandler, HTTPServer
10
+
11
+ from shadpay import ApiError, Client
12
+
13
+ # Set per-test: (status, body dict). The handler echoes captured request state back to the test.
14
+ _STATE = {"status": 200, "body": {}, "last": {}}
15
+
16
+
17
+ class _Handler(BaseHTTPRequestHandler):
18
+ def log_message(self, *args): # silence
19
+ pass
20
+
21
+ def _serve(self):
22
+ length = int(self.headers.get("Content-Length", 0))
23
+ raw = self.rfile.read(length) if length else b""
24
+ _STATE["last"] = {
25
+ "method": self.command,
26
+ "path": self.path,
27
+ "token": self.headers.get("X-Token"),
28
+ "body": json.loads(raw) if raw else None,
29
+ }
30
+ self.send_response(_STATE["status"])
31
+ self.send_header("Content-Type", "application/json")
32
+ self.end_headers()
33
+ self.wfile.write(json.dumps(_STATE["body"]).encode())
34
+
35
+ do_GET = _serve
36
+ do_POST = _serve
37
+
38
+
39
+ class ClientTest(unittest.TestCase):
40
+ @classmethod
41
+ def setUpClass(cls):
42
+ cls.server = HTTPServer(("127.0.0.1", 0), _Handler)
43
+ cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True)
44
+ cls.thread.start()
45
+ host, port = cls.server.server_address
46
+ cls.client = Client(f"http://{host}:{port}", "tok-123")
47
+
48
+ @classmethod
49
+ def tearDownClass(cls):
50
+ cls.server.shutdown()
51
+
52
+ def test_create_payment(self):
53
+ _STATE["status"] = 201
54
+ _STATE["body"] = {"data": {
55
+ "id": "p1", "merchant_ref": "ref-1", "amount_rial": 50000,
56
+ "state": "CREATED", "created_at": "2026-01-01T00:00:00Z",
57
+ "redirect_url": "https://psp/pay/abc",
58
+ }}
59
+ res = self.client.create_payment("ref-1", 50000, "https://m/cb")
60
+ self.assertEqual(res.id, "p1")
61
+ self.assertEqual(res.redirect_url, "https://psp/pay/abc")
62
+ self.assertEqual(_STATE["last"]["token"], "tok-123")
63
+ self.assertEqual(_STATE["last"]["body"]["amount_rial"], 50000)
64
+
65
+ def test_verify(self):
66
+ _STATE["status"] = 200
67
+ _STATE["body"] = {"data": {
68
+ "id": "p1", "merchant_ref": "r", "amount_rial": 50000, "state": "VERIFIED",
69
+ "settled_amount_rial": 50000, "created_at": "x",
70
+ }}
71
+ p = self.client.verify("p1")
72
+ self.assertEqual(p.state, "VERIFIED")
73
+ self.assertEqual(p.settled_amount_rial, 50000)
74
+
75
+ def test_refund(self):
76
+ _STATE["status"] = 201
77
+ _STATE["body"] = {"data": {
78
+ "id": "r1", "payment_id": "p1", "merchant_refund_ref": "RFD-1", "amount_rial": 500000,
79
+ "status": "SUCCEEDED", "created_at": "2026-01-01T00:00:00Z",
80
+ }}
81
+ r = self.client.refund("p1", "RFD-1", 500000)
82
+ self.assertEqual(r.status, "SUCCEEDED")
83
+ self.assertEqual(_STATE["last"]["method"], "POST")
84
+ self.assertEqual(_STATE["last"]["path"], "/v1/payments/p1/refunds")
85
+ self.assertEqual(_STATE["last"]["body"], {"merchant_refund_ref": "RFD-1", "amount_rial": 500000})
86
+
87
+ def test_refund_too_large(self):
88
+ _STATE["status"] = 409
89
+ _STATE["body"] = {"error": {"code": "REFUND_EXCEEDS_REFUNDABLE", "message": "too much"}}
90
+ with self.assertRaises(ApiError) as ctx:
91
+ self.client.refund("p1", "R", 1)
92
+ self.assertEqual(ctx.exception.code, "REFUND_EXCEEDS_REFUNDABLE")
93
+
94
+ def test_list_pagination(self):
95
+ _STATE["status"] = 200
96
+ _STATE["body"] = {
97
+ "data": [{"id": "p1", "merchant_ref": "", "amount_rial": 0, "state": "", "created_at": ""},
98
+ {"id": "p2", "merchant_ref": "", "amount_rial": 0, "state": "", "created_at": ""}],
99
+ "meta": {"pagination": {"next_cursor": "cur2", "has_more": True, "limit": 2}},
100
+ }
101
+ page = self.client.list_payments(limit=2)
102
+ self.assertEqual(len(page.items), 2)
103
+ self.assertEqual(page.next_cursor, "cur2")
104
+ self.assertTrue(page.has_more)
105
+ self.assertIn("limit=2", _STATE["last"]["path"])
106
+
107
+ def test_error_maps_to_apierror(self):
108
+ _STATE["status"] = 422
109
+ _STATE["body"] = {"error": {"code": "PAYMENT_NOT_PAYABLE", "message": "payment is not payable"}}
110
+ with self.assertRaises(ApiError) as ctx:
111
+ self.client.verify("p1")
112
+ self.assertEqual(ctx.exception.code, "PAYMENT_NOT_PAYABLE")
113
+ self.assertEqual(ctx.exception.status, 422)
114
+
115
+
116
+ if __name__ == "__main__":
117
+ unittest.main()
118
+
119
+
120
+ class RetryTest(unittest.TestCase):
121
+ """Retrying is safe on every operation this client exposes, so the client does it."""
122
+
123
+ def test_transient_failure_is_retried(self):
124
+ calls = {"n": 0}
125
+
126
+ def handler(req):
127
+ calls["n"] += 1
128
+ if calls["n"] < 3:
129
+ raise urllib.error.HTTPError(req.full_url, 503, "later", {}, io.BytesIO(
130
+ b'{"error":{"code":"INTERNAL_ERROR","message":"later"}}'))
131
+ return io.BytesIO(b'{"data":{"id":"p1","state":"VERIFIED"}}')
132
+
133
+ with mock.patch("urllib.request.urlopen", side_effect=lambda req, timeout=None: handler(req)):
134
+ with mock.patch("time.sleep"):
135
+ payment = Client("https://x", "t", retries=3).verify("p1")
136
+
137
+ self.assertEqual(payment.state, "VERIFIED")
138
+ self.assertEqual(calls["n"], 3)
139
+
140
+ def test_a_conflict_is_not_retried(self):
141
+ calls = {"n": 0}
142
+
143
+ def handler(req):
144
+ calls["n"] += 1
145
+ raise urllib.error.HTTPError(req.full_url, 409, "no", {}, io.BytesIO(
146
+ b'{"error":{"code":"INVALID_STATE","message":"already reversed"}}'))
147
+
148
+ with mock.patch("urllib.request.urlopen", side_effect=lambda req, timeout=None: handler(req)):
149
+ with self.assertRaises(ApiError):
150
+ Client("https://x", "t", retries=3).verify("p1")
151
+
152
+ self.assertEqual(calls["n"], 1, "a 409 means the same thing however many times it is sent")
@@ -0,0 +1,123 @@
1
+ """Every route the merchant API exposes is called by this client, and no others.
2
+
3
+ The contract is generated in the backend repository from its swaggo spec and copied to
4
+ contract/merchant-v1.json here. Five clients can agree with each other and still be wrong; what
5
+ they have to agree with is the backend. A route the API gains that this client never calls fails
6
+ here, rather than surfacing as a merchant who cannot reach half the surface.
7
+ """
8
+
9
+ import json
10
+ import threading
11
+ import unittest
12
+ from http.server import BaseHTTPRequestHandler, HTTPServer
13
+ from pathlib import Path
14
+
15
+ from shadpay import Client, client as client_module
16
+
17
+ CONTRACT = json.loads(
18
+ (Path(__file__).resolve().parents[2] / "contract" / "merchant-v1.json").read_text("utf-8")
19
+ )
20
+
21
+ _SEEN: list[str] = []
22
+
23
+
24
+ class _Recorder(BaseHTTPRequestHandler):
25
+ def log_message(self, *args): # silence
26
+ pass
27
+
28
+ def _serve(self):
29
+ length = int(self.headers.get("Content-Length", 0))
30
+ if length:
31
+ self.rfile.read(length)
32
+ # The id is put back as the template so the two sides are comparable.
33
+ path = self.path.split("?")[0].replace("PID", "{id}")
34
+ _SEEN.append(f"{self.command} {path}")
35
+ self.send_response(200)
36
+ self.send_header("Content-Type", "application/json")
37
+ self.end_headers()
38
+ # A minimally valid payment: this client parses what it receives, so an empty object
39
+ # would fail on the shape rather than on the contract, which is not what is being tested.
40
+ payment = {
41
+ "id": "p1",
42
+ "merchant_ref": "ref",
43
+ "amount_rial": 1,
44
+ "state": "CREATED",
45
+ "created_at": "2026-01-01T00:00:00Z",
46
+ "payment_id": "p1",
47
+ "merchant_refund_ref": "R1",
48
+ "status": "SUCCEEDED",
49
+ "settleable_rial": 0,
50
+ "settled_rial": 0,
51
+ }
52
+ # A list route is answered with a list; this client parses what it receives, and a shape
53
+ # mismatch would fail on the parsing rather than on the contract.
54
+ listing = self.command == "GET" and path in (
55
+ "/v1/payments",
56
+ "/v1/settlements",
57
+ "/v1/ledger",
58
+ "/v1/payments/{id}/refunds",
59
+ )
60
+ data = [] if listing else payment
61
+ self.wfile.write(
62
+ json.dumps({"data": data, "meta": {"pagination": {"has_more": False}}}).encode()
63
+ )
64
+
65
+ do_GET = _serve
66
+ do_POST = _serve
67
+
68
+
69
+ class ContractTest(unittest.TestCase):
70
+ @classmethod
71
+ def setUpClass(cls):
72
+ cls.server = HTTPServer(("127.0.0.1", 0), _Recorder)
73
+ threading.Thread(target=cls.server.serve_forever, daemon=True).start()
74
+ host, port = cls.server.server_address
75
+ cls.base = f"http://{host}:{port}"
76
+
77
+ @classmethod
78
+ def tearDownClass(cls):
79
+ cls.server.shutdown()
80
+
81
+ def test_calls_every_contract_route_and_no_others(self):
82
+ self.assertTrue(CONTRACT["routes"], "the contract lists no routes; this would pass vacuously")
83
+ _SEEN.clear()
84
+ c = Client(self.base, "tok")
85
+
86
+ c.create_payment("ref", 1, "https://m/cb")
87
+ c.get_payment("PID")
88
+ c.verify("PID")
89
+ c.reverse("PID")
90
+ c.refund("PID", "R1", 1)
91
+ c.list_refunds("PID")
92
+ c.list_payments()
93
+ c.list_settlements()
94
+ c.list_ledger()
95
+ c.balance()
96
+
97
+ self.assertEqual(sorted(set(_SEEN)), sorted(CONTRACT["routes"]))
98
+
99
+ def test_has_a_name_for_every_error_code(self):
100
+ # By constant, not by literal: a code the contract gains that this module has not defined
101
+ # cannot be listed here without defining it.
102
+ known = {
103
+ client_module.CODE_VALIDATION,
104
+ client_module.CODE_UNAUTHENTICATED,
105
+ client_module.CODE_IP_NOT_ALLOWED,
106
+ client_module.CODE_FORBIDDEN,
107
+ client_module.CODE_NOT_FOUND,
108
+ client_module.CODE_INVALID_STATE,
109
+ client_module.CODE_DUPLICATE_REF,
110
+ client_module.CODE_PAYMENT_NOT_PAYABLE,
111
+ client_module.CODE_PAYMENT_NOT_REFUNDABLE,
112
+ client_module.CODE_REFUND_EXCEEDS_REFUNDABLE,
113
+ client_module.CODE_REVERSE_NOT_SUPPORTED,
114
+ client_module.CODE_RATE_LIMITED,
115
+ client_module.CODE_PSP_ERROR,
116
+ client_module.CODE_INTERNAL,
117
+ }
118
+ missing = sorted(set(CONTRACT["error_codes"]) - known)
119
+ self.assertEqual(missing, [], "codes the API can return that this client cannot name")
120
+
121
+
122
+ if __name__ == "__main__":
123
+ unittest.main()