paytrade-sdk 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.
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
paytrade_sdk.py,sha256=oGFCzzrSTUu75i15a_-Bm32q-N0P1CMPPAQiFRL-A_A,5875
|
|
2
|
+
paytrade_sdk-0.2.0.dist-info/METADATA,sha256=wJWAGE_lsPTHj5EavMhfYcdJ_oiYvAvAeESNcvbNN8M,162
|
|
3
|
+
paytrade_sdk-0.2.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
4
|
+
paytrade_sdk-0.2.0.dist-info/top_level.txt,sha256=hibF1qMe7PLoFMsYDS4S-KOpH4ITEMfA5Fc4t93ZYTw,13
|
|
5
|
+
paytrade_sdk-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
paytrade_sdk
|
paytrade_sdk.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""PayTrade SDK: all amounts are integer Telegram Stars (XTR)."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import time
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from urllib.parse import quote, urlparse
|
|
6
|
+
|
|
7
|
+
import aiohttp
|
|
8
|
+
|
|
9
|
+
__version__ = '0.2.0'
|
|
10
|
+
__all__ = ['PayTrade', 'Payment', 'PayTradeError']
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class PayTradeError(Exception):
|
|
14
|
+
def __init__(self, code, message, status=0):
|
|
15
|
+
self.code, self.status = code, status
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class Payment:
|
|
21
|
+
id: str
|
|
22
|
+
order_id: str
|
|
23
|
+
buyer_id: int
|
|
24
|
+
amount: int
|
|
25
|
+
currency: str
|
|
26
|
+
title: str
|
|
27
|
+
description: str
|
|
28
|
+
status: str
|
|
29
|
+
created_at: int
|
|
30
|
+
expires_at: int
|
|
31
|
+
paid_at: int | None
|
|
32
|
+
payment_url: str
|
|
33
|
+
test_mode: bool = False
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def paid(self):
|
|
37
|
+
return self.status == 'paid'
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class PayTrade:
|
|
41
|
+
def __init__(self, api_key: str, base_url: str, *, timeout: float = 15,
|
|
42
|
+
session: aiohttp.ClientSession | None = None):
|
|
43
|
+
parsed = urlparse(base_url)
|
|
44
|
+
if parsed.scheme not in ('http', 'https') or not parsed.hostname or parsed.query or parsed.fragment or parsed.username or parsed.password:
|
|
45
|
+
raise ValueError('base_url must be an HTTP(S) origin or prefix without credentials/query/fragment')
|
|
46
|
+
if parsed.scheme == 'http' and parsed.hostname not in ('localhost', '127.0.0.1', '::1'):
|
|
47
|
+
raise ValueError('Use HTTPS for a remote API; HTTP is allowed only on localhost')
|
|
48
|
+
if not api_key or timeout <= 0:
|
|
49
|
+
raise ValueError('api_key and a positive timeout are required')
|
|
50
|
+
self._key = api_key
|
|
51
|
+
self.base_url = base_url.rstrip('/')
|
|
52
|
+
self.timeout = aiohttp.ClientTimeout(total=timeout)
|
|
53
|
+
self._session, self._owns_session = session, session is None
|
|
54
|
+
|
|
55
|
+
async def __aenter__(self):
|
|
56
|
+
return self
|
|
57
|
+
|
|
58
|
+
async def __aexit__(self, *exc):
|
|
59
|
+
await self.close()
|
|
60
|
+
|
|
61
|
+
async def close(self):
|
|
62
|
+
if self._owns_session and self._session is not None:
|
|
63
|
+
await self._session.close()
|
|
64
|
+
self._session = None
|
|
65
|
+
|
|
66
|
+
async def _request(self, method, path, data=None):
|
|
67
|
+
if self._session is None:
|
|
68
|
+
self._session = aiohttp.ClientSession()
|
|
69
|
+
try:
|
|
70
|
+
async with self._session.request(
|
|
71
|
+
method, self.base_url + path, json=data,
|
|
72
|
+
headers={'Authorization': 'Bearer ' + self._key},
|
|
73
|
+
timeout=self.timeout, allow_redirects=False,
|
|
74
|
+
) as response:
|
|
75
|
+
try:
|
|
76
|
+
body = await response.json()
|
|
77
|
+
except (ValueError, aiohttp.ContentTypeError):
|
|
78
|
+
raise PayTradeError('invalid_response', 'API returned a non-JSON response', response.status) from None
|
|
79
|
+
if not 200 <= response.status < 300:
|
|
80
|
+
error = body.get('error', {}) if isinstance(body, dict) else {}
|
|
81
|
+
raise PayTradeError(error.get('code', 'http_error'), error.get('message', 'API error'), response.status)
|
|
82
|
+
return body
|
|
83
|
+
except (aiohttp.ClientError, asyncio.TimeoutError):
|
|
84
|
+
raise PayTradeError('network_error', 'Cannot reach PayTrade API; retry creation with the SAME order_id') from None
|
|
85
|
+
|
|
86
|
+
async def me(self):
|
|
87
|
+
return await self._request('GET', '/v1/me')
|
|
88
|
+
|
|
89
|
+
async def create_payment(self, *, order_id: str, buyer_id: int, amount: int,
|
|
90
|
+
title: str, description: str = '', return_payload: str = '',
|
|
91
|
+
expires_in: int = 3600) -> Payment:
|
|
92
|
+
"""order_id is an idempotency key, unique inside this application."""
|
|
93
|
+
body = await self._request('POST', '/v1/payments', {
|
|
94
|
+
'order_id': order_id, 'buyer_id': buyer_id, 'amount': amount,
|
|
95
|
+
'title': title, 'description': description,
|
|
96
|
+
'return_payload': return_payload, 'expires_in': expires_in})
|
|
97
|
+
return Payment(**body)
|
|
98
|
+
|
|
99
|
+
async def payment(self, title: str, amount: int, *, buyer_id: int, order_id: str,
|
|
100
|
+
description: str = '', return_payload: str = '', expires_in: int = 3600) -> Payment:
|
|
101
|
+
"""One-line configuration: await api.payment('Title', price, buyer_id=uid, order_id=order).
|
|
102
|
+
|
|
103
|
+
amount may be a constant or a validated runtime value. Mode is configured
|
|
104
|
+
in the service bot, returned as Payment.test_mode and frozen per invoice.
|
|
105
|
+
"""
|
|
106
|
+
return await self.create_payment(order_id=order_id, buyer_id=buyer_id, amount=amount,
|
|
107
|
+
title=title, description=description, return_payload=return_payload, expires_in=expires_in)
|
|
108
|
+
|
|
109
|
+
async def get_payment(self, payment_id: str) -> Payment:
|
|
110
|
+
return Payment(**await self._request('GET', '/v1/payments/' + quote(payment_id, safe='')))
|
|
111
|
+
|
|
112
|
+
async def cancel_payment(self, payment_id: str) -> Payment:
|
|
113
|
+
return Payment(**await self._request('POST', '/v1/payments/' + quote(payment_id, safe='') + '/cancel'))
|
|
114
|
+
|
|
115
|
+
async def wait_for_payment(self, payment_id: str, *, timeout: float = 300, interval: float = 3) -> Payment:
|
|
116
|
+
"""Convenience polling for a few orders; not a durable background worker.
|
|
117
|
+
|
|
118
|
+
Returns paid/cancelled/expired. Raises TimeoutError if still pending/processing.
|
|
119
|
+
For many payments implement a bounded worker respecting 120 requests/min/app.
|
|
120
|
+
"""
|
|
121
|
+
if timeout <= 0 or interval < 1:
|
|
122
|
+
raise ValueError('timeout must be positive and interval >= 1')
|
|
123
|
+
deadline = time.monotonic() + timeout
|
|
124
|
+
while True:
|
|
125
|
+
remaining = deadline - time.monotonic()
|
|
126
|
+
if remaining <= 0:
|
|
127
|
+
raise TimeoutError('Payment remains pending; it has NOT been cancelled')
|
|
128
|
+
payment = await asyncio.wait_for(self.get_payment(payment_id), timeout=remaining)
|
|
129
|
+
if payment.status in ('paid', 'cancelled', 'expired'):
|
|
130
|
+
return payment
|
|
131
|
+
await asyncio.sleep(min(interval, max(0, deadline - time.monotonic())))
|