uzpay 0.1.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.
- uzpay/__init__.py +12 -0
- uzpay/click.py +205 -0
- uzpay/contrib/__init__.py +0 -0
- uzpay/contrib/django/__init__.py +1 -0
- uzpay/contrib/django/apps.py +8 -0
- uzpay/contrib/django/migrations/0001_initial.py +35 -0
- uzpay/contrib/django/migrations/__init__.py +0 -0
- uzpay/contrib/django/models.py +34 -0
- uzpay/contrib/django/store.py +49 -0
- uzpay/contrib/django/views.py +41 -0
- uzpay/core.py +159 -0
- uzpay/payme.py +303 -0
- uzpay-0.1.0.dist-info/METADATA +204 -0
- uzpay-0.1.0.dist-info/RECORD +16 -0
- uzpay-0.1.0.dist-info/WHEEL +4 -0
- uzpay-0.1.0.dist-info/licenses/LICENSE +21 -0
uzpay/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""uzpay: Click and Payme merchant APIs for Python, with no dependencies."""
|
|
2
|
+
|
|
3
|
+
from .click import Click, ClickError
|
|
4
|
+
from .core import MemoryStore, OrderHandler, State, Store, Transaction
|
|
5
|
+
from .payme import Payme, PaymeError, Reason, som_to_tiyin
|
|
6
|
+
|
|
7
|
+
__version__ = "0.1.0"
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"Click", "ClickError", "Payme", "PaymeError", "Reason", "som_to_tiyin",
|
|
11
|
+
"OrderHandler", "Store", "MemoryStore", "Transaction", "State",
|
|
12
|
+
]
|
uzpay/click.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Click SHOP API (Prepare / Complete) merchant side.
|
|
2
|
+
|
|
3
|
+
Docs: https://docs.click.uz/click-api-request/
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
import hmac
|
|
10
|
+
from decimal import Decimal, InvalidOperation
|
|
11
|
+
from typing import Callable, Mapping, Optional
|
|
12
|
+
from urllib.parse import urlencode
|
|
13
|
+
|
|
14
|
+
from .core import OrderHandler, State, Store, Transaction, now_ms, to_decimal
|
|
15
|
+
|
|
16
|
+
PAY_URL = "https://my.click.uz/services/pay"
|
|
17
|
+
PROVIDER = "click"
|
|
18
|
+
|
|
19
|
+
PREPARE = 0
|
|
20
|
+
COMPLETE = 1
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ClickError:
|
|
24
|
+
SUCCESS = 0
|
|
25
|
+
SIGN_CHECK_FAILED = -1
|
|
26
|
+
INCORRECT_AMOUNT = -2
|
|
27
|
+
ACTION_NOT_FOUND = -3
|
|
28
|
+
ALREADY_PAID = -4
|
|
29
|
+
ORDER_NOT_FOUND = -5
|
|
30
|
+
TRANSACTION_NOT_FOUND = -6
|
|
31
|
+
FAILED_TO_UPDATE = -7
|
|
32
|
+
BAD_REQUEST = -8
|
|
33
|
+
TRANSACTION_CANCELLED = -9
|
|
34
|
+
|
|
35
|
+
NOTES = {
|
|
36
|
+
0: "Success",
|
|
37
|
+
-1: "SIGN CHECK FAILED!",
|
|
38
|
+
-2: "Incorrect parameter amount",
|
|
39
|
+
-3: "Action not found",
|
|
40
|
+
-4: "Already paid",
|
|
41
|
+
-5: "User does not exist",
|
|
42
|
+
-6: "Transaction does not exist",
|
|
43
|
+
-7: "Failed to update user",
|
|
44
|
+
-8: "Error in request from click",
|
|
45
|
+
-9: "Transaction cancelled",
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
_REQUIRED = ("click_trans_id", "service_id", "merchant_trans_id", "amount", "action", "sign_time", "sign_string")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Click:
|
|
53
|
+
"""Merchant side of the Click SHOP API.
|
|
54
|
+
|
|
55
|
+
>>> click = Click(service_id=123, merchant_id=456, secret_key="...", orders=MyOrders(), store=MemoryStore())
|
|
56
|
+
>>> click.checkout_url(order_id=42, amount=150000, return_url="https://shop.uz/thanks")
|
|
57
|
+
>>> response = click.handle(request.POST) # same view for Prepare and Complete
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
def __init__(self, service_id, merchant_id, secret_key: str, orders: OrderHandler, store: Store,
|
|
61
|
+
merchant_user_id=None, clock: Callable[[], int] = now_ms) -> None:
|
|
62
|
+
self.service_id = str(service_id)
|
|
63
|
+
self.merchant_id = str(merchant_id)
|
|
64
|
+
self.secret_key = secret_key
|
|
65
|
+
self.merchant_user_id = merchant_user_id
|
|
66
|
+
self.orders = orders
|
|
67
|
+
self.store = store
|
|
68
|
+
self.clock = clock
|
|
69
|
+
|
|
70
|
+
# ---- links -------------------------------------------------------------
|
|
71
|
+
|
|
72
|
+
def checkout_url(self, order_id, amount, return_url: Optional[str] = None,
|
|
73
|
+
card_type: Optional[str] = None) -> str:
|
|
74
|
+
"""Link that opens Click's payment page for ``amount`` so'm."""
|
|
75
|
+
params = {
|
|
76
|
+
"service_id": self.service_id,
|
|
77
|
+
"merchant_id": self.merchant_id,
|
|
78
|
+
"amount": _fmt_amount(to_decimal(amount)),
|
|
79
|
+
"transaction_param": str(order_id),
|
|
80
|
+
}
|
|
81
|
+
if self.merchant_user_id is not None:
|
|
82
|
+
params["merchant_user_id"] = str(self.merchant_user_id)
|
|
83
|
+
if return_url:
|
|
84
|
+
params["return_url"] = return_url
|
|
85
|
+
if card_type:
|
|
86
|
+
params["card_type"] = card_type
|
|
87
|
+
return f"{PAY_URL}?{urlencode(params)}"
|
|
88
|
+
|
|
89
|
+
# ---- signature ---------------------------------------------------------
|
|
90
|
+
|
|
91
|
+
def sign(self, p: Mapping[str, str]) -> str:
|
|
92
|
+
parts = [p["click_trans_id"], p["service_id"], self.secret_key, p["merchant_trans_id"]]
|
|
93
|
+
if str(p["action"]) == str(COMPLETE):
|
|
94
|
+
parts.append(p.get("merchant_prepare_id", ""))
|
|
95
|
+
parts += [p["amount"], p["action"], p["sign_time"]]
|
|
96
|
+
return hashlib.md5("".join(str(x) for x in parts).encode()).hexdigest()
|
|
97
|
+
|
|
98
|
+
# ---- request handling --------------------------------------------------
|
|
99
|
+
|
|
100
|
+
def handle(self, params: Mapping[str, str]) -> dict:
|
|
101
|
+
"""Handle a Prepare or Complete request. Return the dict to send back as JSON."""
|
|
102
|
+
p = {k: _first(params.get(k)) for k in (*_REQUIRED, "merchant_prepare_id", "error", "click_paydoc_id")}
|
|
103
|
+
if any(p[k] in (None, "") for k in _REQUIRED):
|
|
104
|
+
return self._reply(p, ClickError.BAD_REQUEST)
|
|
105
|
+
if str(p["action"]) == str(COMPLETE) and not p["merchant_prepare_id"]:
|
|
106
|
+
return self._reply(p, ClickError.BAD_REQUEST)
|
|
107
|
+
if not hmac.compare_digest(self.sign(p).lower(), str(p["sign_string"]).lower()):
|
|
108
|
+
return self._reply(p, ClickError.SIGN_CHECK_FAILED)
|
|
109
|
+
if str(p["service_id"]) != self.service_id:
|
|
110
|
+
return self._reply(p, ClickError.BAD_REQUEST)
|
|
111
|
+
try:
|
|
112
|
+
amount = Decimal(str(p["amount"]))
|
|
113
|
+
except InvalidOperation:
|
|
114
|
+
return self._reply(p, ClickError.INCORRECT_AMOUNT)
|
|
115
|
+
|
|
116
|
+
action = str(p["action"])
|
|
117
|
+
if action == str(PREPARE):
|
|
118
|
+
return self._prepare(p, amount)
|
|
119
|
+
if action == str(COMPLETE):
|
|
120
|
+
return self._complete(p, amount)
|
|
121
|
+
return self._reply(p, ClickError.ACTION_NOT_FOUND)
|
|
122
|
+
|
|
123
|
+
def _prepare(self, p, amount: Decimal) -> dict:
|
|
124
|
+
order_id = str(p["merchant_trans_id"])
|
|
125
|
+
existing = self.store.get(PROVIDER, str(p["click_trans_id"]))
|
|
126
|
+
if existing:
|
|
127
|
+
if existing.is_performed:
|
|
128
|
+
return self._reply(p, ClickError.ALREADY_PAID)
|
|
129
|
+
if existing.is_cancelled:
|
|
130
|
+
return self._reply(p, ClickError.TRANSACTION_CANCELLED)
|
|
131
|
+
return self._reply(p, ClickError.SUCCESS, merchant_prepare_id=existing.id)
|
|
132
|
+
|
|
133
|
+
due = self.orders.get_amount(order_id)
|
|
134
|
+
if due is None:
|
|
135
|
+
return self._reply(p, ClickError.ORDER_NOT_FOUND)
|
|
136
|
+
if not self.orders.is_payable(order_id):
|
|
137
|
+
return self._reply(p, ClickError.ALREADY_PAID)
|
|
138
|
+
if to_decimal(due) != amount:
|
|
139
|
+
return self._reply(p, ClickError.INCORRECT_AMOUNT)
|
|
140
|
+
|
|
141
|
+
tx = self.store.create(Transaction(
|
|
142
|
+
provider=PROVIDER, external_id=str(p["click_trans_id"]), order_id=order_id, amount=amount,
|
|
143
|
+
state=State.CREATED, create_time=self.clock(),
|
|
144
|
+
extra={"click_paydoc_id": p.get("click_paydoc_id")},
|
|
145
|
+
))
|
|
146
|
+
return self._reply(p, ClickError.SUCCESS, merchant_prepare_id=tx.id)
|
|
147
|
+
|
|
148
|
+
def _complete(self, p, amount: Decimal) -> dict:
|
|
149
|
+
try:
|
|
150
|
+
tx = self.store.get_by_id(PROVIDER, int(p["merchant_prepare_id"]))
|
|
151
|
+
except (TypeError, ValueError):
|
|
152
|
+
tx = None
|
|
153
|
+
if tx is None or tx.external_id != str(p["click_trans_id"]) or tx.order_id != str(p["merchant_trans_id"]):
|
|
154
|
+
return self._reply(p, ClickError.TRANSACTION_NOT_FOUND)
|
|
155
|
+
if tx.is_performed:
|
|
156
|
+
return self._reply(p, ClickError.ALREADY_PAID, merchant_confirm_id=tx.id)
|
|
157
|
+
if tx.is_cancelled:
|
|
158
|
+
return self._reply(p, ClickError.TRANSACTION_CANCELLED)
|
|
159
|
+
|
|
160
|
+
if _int(p.get("error")) < 0:
|
|
161
|
+
# Click reports a failure on its side: cancel our transaction.
|
|
162
|
+
tx.state, tx.cancel_time = State.CANCELLED, self.clock()
|
|
163
|
+
self.store.update(tx)
|
|
164
|
+
self.orders.on_cancelled(tx.order_id, tx)
|
|
165
|
+
return self._reply(p, ClickError.TRANSACTION_CANCELLED)
|
|
166
|
+
|
|
167
|
+
if tx.amount != amount:
|
|
168
|
+
return self._reply(p, ClickError.INCORRECT_AMOUNT)
|
|
169
|
+
|
|
170
|
+
tx.state, tx.perform_time = State.PERFORMED, self.clock()
|
|
171
|
+
try:
|
|
172
|
+
self.orders.on_paid(tx.order_id, tx)
|
|
173
|
+
except Exception:
|
|
174
|
+
return self._reply(p, ClickError.FAILED_TO_UPDATE)
|
|
175
|
+
self.store.update(tx)
|
|
176
|
+
return self._reply(p, ClickError.SUCCESS, merchant_confirm_id=tx.id)
|
|
177
|
+
|
|
178
|
+
@staticmethod
|
|
179
|
+
def _reply(p, code: int, **extra) -> dict:
|
|
180
|
+
out = {
|
|
181
|
+
"click_trans_id": _int(p.get("click_trans_id")) if p.get("click_trans_id") else None,
|
|
182
|
+
"merchant_trans_id": p.get("merchant_trans_id"),
|
|
183
|
+
"error": code,
|
|
184
|
+
"error_note": ClickError.NOTES[code],
|
|
185
|
+
}
|
|
186
|
+
out.update(extra)
|
|
187
|
+
return out
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _first(v):
|
|
191
|
+
# Django QueryDict.get / plain dicts give a str; parse_qs gives a list.
|
|
192
|
+
if isinstance(v, (list, tuple)):
|
|
193
|
+
return v[0] if v else None
|
|
194
|
+
return v
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _int(v) -> int:
|
|
198
|
+
try:
|
|
199
|
+
return int(v)
|
|
200
|
+
except (TypeError, ValueError):
|
|
201
|
+
return 0
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _fmt_amount(d: Decimal) -> str:
|
|
205
|
+
return str(d.quantize(Decimal("1"))) if d == d.to_integral_value() else f"{d:.2f}"
|
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Django integration. Add ``"uzpay.contrib.django"`` to INSTALLED_APPS and run migrate."""
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Generated by Django 6.1.4 on 2026-12-06 07:07
|
|
2
|
+
|
|
3
|
+
from django.db import migrations, models
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Migration(migrations.Migration):
|
|
7
|
+
|
|
8
|
+
initial = True
|
|
9
|
+
|
|
10
|
+
dependencies = [
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
operations = [
|
|
14
|
+
migrations.CreateModel(
|
|
15
|
+
name='PaymentTransaction',
|
|
16
|
+
fields=[
|
|
17
|
+
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
|
18
|
+
('provider', models.CharField(max_length=10)),
|
|
19
|
+
('external_id', models.CharField(max_length=64)),
|
|
20
|
+
('order_id', models.CharField(max_length=64)),
|
|
21
|
+
('amount', models.DecimalField(decimal_places=2, max_digits=18)),
|
|
22
|
+
('state', models.SmallIntegerField(choices=[(1, 'Created'), (2, 'Paid'), (-1, 'Cancelled'), (-2, 'Cancelled after payment')], default=1)),
|
|
23
|
+
('create_time', models.BigIntegerField(default=0)),
|
|
24
|
+
('perform_time', models.BigIntegerField(default=0)),
|
|
25
|
+
('cancel_time', models.BigIntegerField(default=0)),
|
|
26
|
+
('reason', models.SmallIntegerField(blank=True, null=True)),
|
|
27
|
+
('extra', models.JSONField(blank=True, default=dict)),
|
|
28
|
+
],
|
|
29
|
+
options={
|
|
30
|
+
'ordering': ['-create_time'],
|
|
31
|
+
'indexes': [models.Index(fields=['provider', 'order_id', 'state'], name='uzpay_order_state'), models.Index(fields=['provider', 'create_time'], name='uzpay_create_time')],
|
|
32
|
+
'constraints': [models.UniqueConstraint(fields=('provider', 'external_id'), name='uzpay_provider_external_id')],
|
|
33
|
+
},
|
|
34
|
+
),
|
|
35
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from django.db import models
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class PaymentTransaction(models.Model):
|
|
5
|
+
STATE_CHOICES = [
|
|
6
|
+
(1, "Created"),
|
|
7
|
+
(2, "Paid"),
|
|
8
|
+
(-1, "Cancelled"),
|
|
9
|
+
(-2, "Cancelled after payment"),
|
|
10
|
+
]
|
|
11
|
+
|
|
12
|
+
provider = models.CharField(max_length=10)
|
|
13
|
+
external_id = models.CharField(max_length=64)
|
|
14
|
+
order_id = models.CharField(max_length=64)
|
|
15
|
+
amount = models.DecimalField(max_digits=18, decimal_places=2)
|
|
16
|
+
state = models.SmallIntegerField(choices=STATE_CHOICES, default=1)
|
|
17
|
+
create_time = models.BigIntegerField(default=0)
|
|
18
|
+
perform_time = models.BigIntegerField(default=0)
|
|
19
|
+
cancel_time = models.BigIntegerField(default=0)
|
|
20
|
+
reason = models.SmallIntegerField(null=True, blank=True)
|
|
21
|
+
extra = models.JSONField(default=dict, blank=True)
|
|
22
|
+
|
|
23
|
+
class Meta:
|
|
24
|
+
constraints = [
|
|
25
|
+
models.UniqueConstraint(fields=["provider", "external_id"], name="uzpay_provider_external_id"),
|
|
26
|
+
]
|
|
27
|
+
indexes = [
|
|
28
|
+
models.Index(fields=["provider", "order_id", "state"], name="uzpay_order_state"),
|
|
29
|
+
models.Index(fields=["provider", "create_time"], name="uzpay_create_time"),
|
|
30
|
+
]
|
|
31
|
+
ordering = ["-create_time"]
|
|
32
|
+
|
|
33
|
+
def __str__(self):
|
|
34
|
+
return f"{self.provider} {self.external_id} -> {self.order_id} ({self.get_state_display()})"
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from django.db import transaction as db_transaction
|
|
2
|
+
|
|
3
|
+
from ...core import Store, Transaction
|
|
4
|
+
from .models import PaymentTransaction
|
|
5
|
+
|
|
6
|
+
_FIELDS = ("provider", "external_id", "order_id", "amount", "state", "create_time",
|
|
7
|
+
"perform_time", "cancel_time", "reason", "extra")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _to_tx(row: PaymentTransaction) -> Transaction:
|
|
11
|
+
return Transaction(id=row.pk, **{f: getattr(row, f) for f in _FIELDS})
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class DjangoStore(Store):
|
|
15
|
+
"""Keeps transactions in the ``PaymentTransaction`` model.
|
|
16
|
+
|
|
17
|
+
Rows are locked with SELECT ... FOR UPDATE when called inside ``transaction.atomic``
|
|
18
|
+
(the bundled views always are).
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def _qs(self):
|
|
22
|
+
qs = PaymentTransaction.objects.all()
|
|
23
|
+
if db_transaction.get_connection().in_atomic_block:
|
|
24
|
+
qs = qs.select_for_update()
|
|
25
|
+
return qs
|
|
26
|
+
|
|
27
|
+
def get(self, provider, external_id):
|
|
28
|
+
row = self._qs().filter(provider=provider, external_id=external_id).first()
|
|
29
|
+
return _to_tx(row) if row else None
|
|
30
|
+
|
|
31
|
+
def get_by_id(self, provider, tx_id):
|
|
32
|
+
row = self._qs().filter(provider=provider, pk=tx_id).first()
|
|
33
|
+
return _to_tx(row) if row else None
|
|
34
|
+
|
|
35
|
+
def create(self, tx):
|
|
36
|
+
row = PaymentTransaction.objects.create(**{f: getattr(tx, f) for f in _FIELDS})
|
|
37
|
+
return _to_tx(row)
|
|
38
|
+
|
|
39
|
+
def update(self, tx):
|
|
40
|
+
PaymentTransaction.objects.filter(pk=tx.id).update(**{f: getattr(tx, f) for f in _FIELDS})
|
|
41
|
+
|
|
42
|
+
def active_for_order(self, provider, order_id):
|
|
43
|
+
row = self._qs().filter(provider=provider, order_id=order_id, state=1).first()
|
|
44
|
+
return _to_tx(row) if row else None
|
|
45
|
+
|
|
46
|
+
def between(self, provider, from_ms, to_ms):
|
|
47
|
+
rows = PaymentTransaction.objects.filter(
|
|
48
|
+
provider=provider, create_time__gte=from_ms, create_time__lte=to_ms).order_by("create_time")
|
|
49
|
+
return [_to_tx(r) for r in rows]
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Ready-made Django views.
|
|
2
|
+
|
|
3
|
+
# urls.py
|
|
4
|
+
from uzpay.contrib.django.views import click_view, payme_view
|
|
5
|
+
from .payments import click, payme # your configured Click / Payme objects
|
|
6
|
+
|
|
7
|
+
urlpatterns = [
|
|
8
|
+
path("pay/click/", click_view(click)),
|
|
9
|
+
path("pay/payme/", payme_view(payme)),
|
|
10
|
+
]
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from django.db import transaction
|
|
14
|
+
from django.http import HttpResponseNotAllowed, JsonResponse
|
|
15
|
+
from django.views.decorators.csrf import csrf_exempt
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def click_view(click):
|
|
19
|
+
"""One endpoint for both Click Prepare and Complete URLs."""
|
|
20
|
+
|
|
21
|
+
@csrf_exempt
|
|
22
|
+
def view(request):
|
|
23
|
+
if request.method != "POST":
|
|
24
|
+
return HttpResponseNotAllowed(["POST"])
|
|
25
|
+
with transaction.atomic():
|
|
26
|
+
result = click.handle(request.POST)
|
|
27
|
+
return JsonResponse(result)
|
|
28
|
+
|
|
29
|
+
return view
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def payme_view(payme):
|
|
33
|
+
@csrf_exempt
|
|
34
|
+
def view(request):
|
|
35
|
+
if request.method != "POST":
|
|
36
|
+
return HttpResponseNotAllowed(["POST"])
|
|
37
|
+
with transaction.atomic():
|
|
38
|
+
result = payme.handle(request.body, request.META.get("HTTP_AUTHORIZATION"))
|
|
39
|
+
return JsonResponse(result, json_dumps_params={"ensure_ascii": False})
|
|
40
|
+
|
|
41
|
+
return view
|
uzpay/core.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Shared building blocks: transaction record, order hooks and storage."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import itertools
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
from dataclasses import dataclass, field, replace
|
|
9
|
+
from decimal import Decimal
|
|
10
|
+
from typing import Any, Iterable, Optional
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class State:
|
|
14
|
+
"""Transaction states (the same numbers Payme uses)."""
|
|
15
|
+
|
|
16
|
+
CREATED = 1
|
|
17
|
+
PERFORMED = 2
|
|
18
|
+
CANCELLED = -1
|
|
19
|
+
CANCELLED_AFTER_PERFORM = -2
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def now_ms() -> int:
|
|
23
|
+
return int(time.time() * 1000)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def to_decimal(value: Any) -> Decimal:
|
|
27
|
+
"""Convert an amount in so'm (int, str, float or Decimal) to Decimal."""
|
|
28
|
+
if isinstance(value, Decimal):
|
|
29
|
+
return value
|
|
30
|
+
if isinstance(value, float):
|
|
31
|
+
value = repr(value)
|
|
32
|
+
return Decimal(str(value))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class Transaction:
|
|
37
|
+
"""One payment attempt coming from a provider.
|
|
38
|
+
|
|
39
|
+
``amount`` is always in so'm (Decimal), even for Payme, which talks in tiyin.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
provider: str
|
|
43
|
+
external_id: str
|
|
44
|
+
order_id: str
|
|
45
|
+
amount: Decimal
|
|
46
|
+
state: int = State.CREATED
|
|
47
|
+
create_time: int = 0
|
|
48
|
+
perform_time: int = 0
|
|
49
|
+
cancel_time: int = 0
|
|
50
|
+
reason: Optional[int] = None
|
|
51
|
+
extra: dict = field(default_factory=dict)
|
|
52
|
+
id: Optional[int] = None
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def is_active(self) -> bool:
|
|
56
|
+
return self.state == State.CREATED
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def is_performed(self) -> bool:
|
|
60
|
+
return self.state == State.PERFORMED
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def is_cancelled(self) -> bool:
|
|
64
|
+
return self.state in (State.CANCELLED, State.CANCELLED_AFTER_PERFORM)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class OrderHandler:
|
|
68
|
+
"""Connect uzpay to your own orders. Subclass it and override the methods.
|
|
69
|
+
|
|
70
|
+
Only :meth:`get_amount` and :meth:`on_paid` are required.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
def get_amount(self, order_id: str) -> Optional[Any]:
|
|
74
|
+
"""Return the amount due for ``order_id`` in so'm, or ``None`` if there is no such order."""
|
|
75
|
+
raise NotImplementedError
|
|
76
|
+
|
|
77
|
+
def is_payable(self, order_id: str) -> bool:
|
|
78
|
+
"""Return ``False`` if the order is already paid, cancelled or otherwise closed."""
|
|
79
|
+
return True
|
|
80
|
+
|
|
81
|
+
def on_paid(self, order_id: str, tx: Transaction) -> None:
|
|
82
|
+
"""Called once, when the money has been received. Mark the order paid here."""
|
|
83
|
+
raise NotImplementedError
|
|
84
|
+
|
|
85
|
+
def on_cancelled(self, order_id: str, tx: Transaction) -> None:
|
|
86
|
+
"""Called when a transaction is cancelled (before or after payment)."""
|
|
87
|
+
|
|
88
|
+
def can_cancel_paid(self, order_id: str, tx: Transaction) -> bool:
|
|
89
|
+
"""Allow Payme to cancel (refund) an already paid transaction. Default: no."""
|
|
90
|
+
return False
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class Store:
|
|
94
|
+
"""Where transactions are kept. Use :class:`MemoryStore` for tests or the Django store."""
|
|
95
|
+
|
|
96
|
+
def get(self, provider: str, external_id: str) -> Optional[Transaction]:
|
|
97
|
+
raise NotImplementedError
|
|
98
|
+
|
|
99
|
+
def get_by_id(self, provider: str, tx_id: int) -> Optional[Transaction]:
|
|
100
|
+
raise NotImplementedError
|
|
101
|
+
|
|
102
|
+
def create(self, tx: Transaction) -> Transaction:
|
|
103
|
+
"""Save a new transaction and return it with ``id`` filled in."""
|
|
104
|
+
raise NotImplementedError
|
|
105
|
+
|
|
106
|
+
def update(self, tx: Transaction) -> None:
|
|
107
|
+
raise NotImplementedError
|
|
108
|
+
|
|
109
|
+
def active_for_order(self, provider: str, order_id: str) -> Optional[Transaction]:
|
|
110
|
+
"""Return a transaction in state CREATED for this order, if any."""
|
|
111
|
+
raise NotImplementedError
|
|
112
|
+
|
|
113
|
+
def between(self, provider: str, from_ms: int, to_ms: int) -> Iterable[Transaction]:
|
|
114
|
+
"""Transactions created in ``[from_ms, to_ms]``, oldest first."""
|
|
115
|
+
raise NotImplementedError
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class MemoryStore(Store):
|
|
119
|
+
"""Thread-safe in-memory store. Fine for tests and demos, not for production."""
|
|
120
|
+
|
|
121
|
+
def __init__(self) -> None:
|
|
122
|
+
self._rows: dict[int, Transaction] = {}
|
|
123
|
+
self._ids = itertools.count(1)
|
|
124
|
+
self._lock = threading.Lock()
|
|
125
|
+
|
|
126
|
+
def get(self, provider, external_id):
|
|
127
|
+
with self._lock:
|
|
128
|
+
for tx in self._rows.values():
|
|
129
|
+
if tx.provider == provider and tx.external_id == external_id:
|
|
130
|
+
return replace(tx)
|
|
131
|
+
return None
|
|
132
|
+
|
|
133
|
+
def get_by_id(self, provider, tx_id):
|
|
134
|
+
with self._lock:
|
|
135
|
+
tx = self._rows.get(int(tx_id))
|
|
136
|
+
return replace(tx) if tx and tx.provider == provider else None
|
|
137
|
+
|
|
138
|
+
def create(self, tx):
|
|
139
|
+
with self._lock:
|
|
140
|
+
tx = replace(tx, id=next(self._ids))
|
|
141
|
+
self._rows[tx.id] = replace(tx)
|
|
142
|
+
return tx
|
|
143
|
+
|
|
144
|
+
def update(self, tx):
|
|
145
|
+
with self._lock:
|
|
146
|
+
self._rows[tx.id] = replace(tx)
|
|
147
|
+
|
|
148
|
+
def active_for_order(self, provider, order_id):
|
|
149
|
+
with self._lock:
|
|
150
|
+
for tx in self._rows.values():
|
|
151
|
+
if tx.provider == provider and tx.order_id == order_id and tx.is_active:
|
|
152
|
+
return replace(tx)
|
|
153
|
+
return None
|
|
154
|
+
|
|
155
|
+
def between(self, provider, from_ms, to_ms):
|
|
156
|
+
with self._lock:
|
|
157
|
+
rows = [replace(t) for t in self._rows.values()
|
|
158
|
+
if t.provider == provider and from_ms <= t.create_time <= to_ms]
|
|
159
|
+
return sorted(rows, key=lambda t: t.create_time)
|
uzpay/payme.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
"""Payme (Paycom) Merchant API, merchant side.
|
|
2
|
+
|
|
3
|
+
Docs: https://developer.help.paycom.uz/metody-merchant-api/
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import base64
|
|
9
|
+
import binascii
|
|
10
|
+
import hmac
|
|
11
|
+
import json
|
|
12
|
+
from decimal import Decimal
|
|
13
|
+
from typing import Any, Callable, Mapping, Optional, Union
|
|
14
|
+
|
|
15
|
+
from .core import OrderHandler, State, Store, Transaction, now_ms, to_decimal
|
|
16
|
+
|
|
17
|
+
CHECKOUT_URL = "https://checkout.paycom.uz"
|
|
18
|
+
TEST_CHECKOUT_URL = "https://test.paycom.uz"
|
|
19
|
+
PROVIDER = "payme"
|
|
20
|
+
TIMEOUT_MS = 12 * 60 * 60 * 1000 # a created transaction lives 12 hours
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Reason:
|
|
24
|
+
"""Cancel reasons (``reason`` in CancelTransaction / CheckTransaction)."""
|
|
25
|
+
|
|
26
|
+
RECEIVER_NOT_FOUND = 1
|
|
27
|
+
DEBIT_ERROR = 2
|
|
28
|
+
TRANSACTION_ERROR = 3
|
|
29
|
+
TIMEOUT = 4
|
|
30
|
+
REFUND = 5
|
|
31
|
+
UNKNOWN = 10
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class PaymeError(Exception):
|
|
35
|
+
PARSE_ERROR = -32700
|
|
36
|
+
INVALID_REQUEST = -32600
|
|
37
|
+
METHOD_NOT_FOUND = -32601
|
|
38
|
+
INSUFFICIENT_PRIVILEGE = -32504
|
|
39
|
+
INTERNAL = -32400
|
|
40
|
+
WRONG_AMOUNT = -31001
|
|
41
|
+
TRANSACTION_NOT_FOUND = -31003
|
|
42
|
+
CANT_CANCEL = -31007
|
|
43
|
+
CANT_PERFORM = -31008
|
|
44
|
+
ORDER_NOT_FOUND = -31050
|
|
45
|
+
ORDER_NOT_PAYABLE = -31051
|
|
46
|
+
ORDER_BUSY = -31052
|
|
47
|
+
|
|
48
|
+
MESSAGES = {
|
|
49
|
+
-32700: ("Ошибка разбора JSON", "JSON xato", "Parse error"),
|
|
50
|
+
-32600: ("Неверный запрос", "Noto'g'ri so'rov", "Invalid request"),
|
|
51
|
+
-32601: ("Метод не найден", "Metod topilmadi", "Method not found"),
|
|
52
|
+
-32504: ("Недостаточно привилегий", "Ruxsat yo'q", "Insufficient privilege"),
|
|
53
|
+
-32400: ("Системная ошибка", "Tizim xatosi", "Internal error"),
|
|
54
|
+
-31001: ("Неверная сумма", "Noto'g'ri summa", "Wrong amount"),
|
|
55
|
+
-31003: ("Транзакция не найдена", "Tranzaksiya topilmadi", "Transaction not found"),
|
|
56
|
+
-31007: ("Невозможно отменить транзакцию", "Tranzaksiyani bekor qilib bo'lmaydi", "Unable to cancel transaction"),
|
|
57
|
+
-31008: ("Невозможно выполнить операцию", "Amalni bajarib bo'lmaydi", "Unable to perform operation"),
|
|
58
|
+
-31050: ("Заказ не найден", "Buyurtma topilmadi", "Order not found"),
|
|
59
|
+
-31051: ("Заказ уже оплачен или закрыт", "Buyurtma to'langan yoki yopilgan", "Order is already paid or closed"),
|
|
60
|
+
-31052: ("Заказ ожидает оплаты в другой транзакции", "Buyurtma boshqa tranzaksiyada to'lanmoqda",
|
|
61
|
+
"Order is being paid in another transaction"),
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
def __init__(self, code: int, data: Any = None) -> None:
|
|
65
|
+
super().__init__(code)
|
|
66
|
+
self.code = code
|
|
67
|
+
self.data = data
|
|
68
|
+
|
|
69
|
+
def to_dict(self) -> dict:
|
|
70
|
+
ru, uz, en = self.MESSAGES.get(self.code, self.MESSAGES[-32400])
|
|
71
|
+
out = {"code": self.code, "message": {"ru": ru, "uz": uz, "en": en}}
|
|
72
|
+
if self.data is not None:
|
|
73
|
+
out["data"] = self.data
|
|
74
|
+
return out
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class Payme:
|
|
78
|
+
"""Merchant side of the Payme Merchant API.
|
|
79
|
+
|
|
80
|
+
>>> payme = Payme(merchant_id="5e73...", key="SECRET", orders=MyOrders(), store=MemoryStore())
|
|
81
|
+
>>> payme.checkout_url(order_id=42, amount=150000) # amount in so'm
|
|
82
|
+
>>> response = payme.handle(request.body, request.headers.get("Authorization"))
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
def __init__(self, merchant_id: str, key: str, orders: OrderHandler, store: Store,
|
|
86
|
+
account_field: str = "order_id", test: bool = False,
|
|
87
|
+
clock: Callable[[], int] = now_ms) -> None:
|
|
88
|
+
self.merchant_id = merchant_id
|
|
89
|
+
self.key = key
|
|
90
|
+
self.account_field = account_field
|
|
91
|
+
self.test = test
|
|
92
|
+
self.orders = orders
|
|
93
|
+
self.store = store
|
|
94
|
+
self.clock = clock
|
|
95
|
+
|
|
96
|
+
# ---- links -------------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
def checkout_url(self, order_id, amount, return_url: Optional[str] = None, lang: Optional[str] = None,
|
|
99
|
+
callback_timeout: Optional[int] = None) -> str:
|
|
100
|
+
"""Link that opens Payme's checkout for ``amount`` so'm."""
|
|
101
|
+
parts = [f"m={self.merchant_id}", f"ac.{self.account_field}={order_id}", f"a={som_to_tiyin(amount)}"]
|
|
102
|
+
if lang:
|
|
103
|
+
parts.append(f"l={lang}")
|
|
104
|
+
if return_url:
|
|
105
|
+
parts.append(f"c={return_url}")
|
|
106
|
+
if callback_timeout is not None:
|
|
107
|
+
parts.append(f"ct={int(callback_timeout)}")
|
|
108
|
+
encoded = base64.b64encode(";".join(parts).encode()).decode()
|
|
109
|
+
return f"{TEST_CHECKOUT_URL if self.test else CHECKOUT_URL}/{encoded}"
|
|
110
|
+
|
|
111
|
+
# ---- request handling --------------------------------------------------
|
|
112
|
+
|
|
113
|
+
def check_auth(self, authorization: Optional[str]) -> bool:
|
|
114
|
+
if not self.key or not authorization or not authorization.startswith("Basic "):
|
|
115
|
+
return False # an unset key must never let requests through
|
|
116
|
+
try:
|
|
117
|
+
login, _, password = base64.b64decode(authorization[6:].strip()).decode().partition(":")
|
|
118
|
+
except (binascii.Error, UnicodeDecodeError):
|
|
119
|
+
return False
|
|
120
|
+
return login == "Paycom" and hmac.compare_digest(password.encode(), self.key.encode())
|
|
121
|
+
|
|
122
|
+
def handle(self, body: Union[bytes, str, Mapping], authorization: Optional[str]) -> dict:
|
|
123
|
+
"""Handle one JSON-RPC request. Always answer HTTP 200 with the returned dict as JSON."""
|
|
124
|
+
req_id = None
|
|
125
|
+
try:
|
|
126
|
+
if isinstance(body, Mapping):
|
|
127
|
+
req = dict(body)
|
|
128
|
+
else:
|
|
129
|
+
try:
|
|
130
|
+
req = json.loads(body)
|
|
131
|
+
except (ValueError, TypeError):
|
|
132
|
+
raise PaymeError(PaymeError.PARSE_ERROR)
|
|
133
|
+
if not isinstance(req, dict):
|
|
134
|
+
raise PaymeError(PaymeError.INVALID_REQUEST)
|
|
135
|
+
req_id = req.get("id")
|
|
136
|
+
if not self.check_auth(authorization):
|
|
137
|
+
raise PaymeError(PaymeError.INSUFFICIENT_PRIVILEGE)
|
|
138
|
+
method, params = req.get("method"), req.get("params")
|
|
139
|
+
if not isinstance(method, str) or not isinstance(params, dict):
|
|
140
|
+
raise PaymeError(PaymeError.INVALID_REQUEST)
|
|
141
|
+
fn = self._methods().get(method)
|
|
142
|
+
if fn is None:
|
|
143
|
+
raise PaymeError(PaymeError.METHOD_NOT_FOUND, method)
|
|
144
|
+
return {"jsonrpc": "2.0", "id": req_id, "result": fn(params)}
|
|
145
|
+
except PaymeError as e:
|
|
146
|
+
return {"jsonrpc": "2.0", "id": req_id, "error": e.to_dict()}
|
|
147
|
+
|
|
148
|
+
def _methods(self) -> dict:
|
|
149
|
+
return {
|
|
150
|
+
"CheckPerformTransaction": self.check_perform_transaction,
|
|
151
|
+
"CreateTransaction": self.create_transaction,
|
|
152
|
+
"PerformTransaction": self.perform_transaction,
|
|
153
|
+
"CancelTransaction": self.cancel_transaction,
|
|
154
|
+
"CheckTransaction": self.check_transaction,
|
|
155
|
+
"GetStatement": self.get_statement,
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
# ---- methods -----------------------------------------------------------
|
|
159
|
+
|
|
160
|
+
def check_perform_transaction(self, params: dict) -> dict:
|
|
161
|
+
order_id, amount = self._order_and_amount(params)
|
|
162
|
+
self._check_order(order_id, amount)
|
|
163
|
+
return {"allow": True}
|
|
164
|
+
|
|
165
|
+
def create_transaction(self, params: dict) -> dict:
|
|
166
|
+
payme_id = _required_str(params, "id")
|
|
167
|
+
payme_time = _required_int(params, "time")
|
|
168
|
+
order_id, amount = self._order_and_amount(params)
|
|
169
|
+
|
|
170
|
+
tx = self.store.get(PROVIDER, payme_id)
|
|
171
|
+
if tx:
|
|
172
|
+
if not tx.is_active:
|
|
173
|
+
raise PaymeError(PaymeError.CANT_PERFORM, "transaction")
|
|
174
|
+
if self._expired(tx):
|
|
175
|
+
self._cancel(tx, Reason.TIMEOUT)
|
|
176
|
+
raise PaymeError(PaymeError.CANT_PERFORM, "timeout")
|
|
177
|
+
return self._created(tx)
|
|
178
|
+
|
|
179
|
+
self._check_order(order_id, amount)
|
|
180
|
+
if self.clock() - payme_time >= TIMEOUT_MS:
|
|
181
|
+
raise PaymeError(PaymeError.CANT_PERFORM, "timeout")
|
|
182
|
+
if self.store.active_for_order(PROVIDER, order_id):
|
|
183
|
+
raise PaymeError(PaymeError.ORDER_BUSY, self.account_field)
|
|
184
|
+
|
|
185
|
+
tx = self.store.create(Transaction(
|
|
186
|
+
provider=PROVIDER, external_id=payme_id, order_id=order_id, amount=amount,
|
|
187
|
+
state=State.CREATED, create_time=self.clock(),
|
|
188
|
+
extra={"time": payme_time, "account": params.get("account")},
|
|
189
|
+
))
|
|
190
|
+
return self._created(tx)
|
|
191
|
+
|
|
192
|
+
def perform_transaction(self, params: dict) -> dict:
|
|
193
|
+
tx = self._get(params)
|
|
194
|
+
if tx.is_performed:
|
|
195
|
+
return {"transaction": str(tx.id), "perform_time": tx.perform_time, "state": tx.state}
|
|
196
|
+
if not tx.is_active:
|
|
197
|
+
raise PaymeError(PaymeError.CANT_PERFORM, "transaction")
|
|
198
|
+
if self._expired(tx):
|
|
199
|
+
self._cancel(tx, Reason.TIMEOUT)
|
|
200
|
+
raise PaymeError(PaymeError.CANT_PERFORM, "timeout")
|
|
201
|
+
|
|
202
|
+
tx.state, tx.perform_time = State.PERFORMED, self.clock()
|
|
203
|
+
try:
|
|
204
|
+
self.orders.on_paid(tx.order_id, tx)
|
|
205
|
+
except Exception:
|
|
206
|
+
raise PaymeError(PaymeError.INTERNAL)
|
|
207
|
+
self.store.update(tx)
|
|
208
|
+
return {"transaction": str(tx.id), "perform_time": tx.perform_time, "state": tx.state}
|
|
209
|
+
|
|
210
|
+
def cancel_transaction(self, params: dict) -> dict:
|
|
211
|
+
tx = self._get(params)
|
|
212
|
+
reason = params.get("reason")
|
|
213
|
+
if tx.is_active:
|
|
214
|
+
self._cancel(tx, reason)
|
|
215
|
+
elif tx.is_performed:
|
|
216
|
+
if not self.orders.can_cancel_paid(tx.order_id, tx):
|
|
217
|
+
raise PaymeError(PaymeError.CANT_CANCEL)
|
|
218
|
+
self._cancel(tx, reason)
|
|
219
|
+
return {"transaction": str(tx.id), "cancel_time": tx.cancel_time, "state": tx.state}
|
|
220
|
+
|
|
221
|
+
def check_transaction(self, params: dict) -> dict:
|
|
222
|
+
tx = self._get(params)
|
|
223
|
+
return {
|
|
224
|
+
"create_time": tx.create_time,
|
|
225
|
+
"perform_time": tx.perform_time,
|
|
226
|
+
"cancel_time": tx.cancel_time,
|
|
227
|
+
"transaction": str(tx.id),
|
|
228
|
+
"state": tx.state,
|
|
229
|
+
"reason": tx.reason,
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
def get_statement(self, params: dict) -> dict:
|
|
233
|
+
start, end = _required_int(params, "from"), _required_int(params, "to")
|
|
234
|
+
return {"transactions": [{
|
|
235
|
+
"id": tx.external_id,
|
|
236
|
+
"time": tx.extra.get("time", tx.create_time),
|
|
237
|
+
"amount": som_to_tiyin(tx.amount),
|
|
238
|
+
"account": tx.extra.get("account") or {self.account_field: tx.order_id},
|
|
239
|
+
"create_time": tx.create_time,
|
|
240
|
+
"perform_time": tx.perform_time,
|
|
241
|
+
"cancel_time": tx.cancel_time,
|
|
242
|
+
"transaction": str(tx.id),
|
|
243
|
+
"state": tx.state,
|
|
244
|
+
"reason": tx.reason,
|
|
245
|
+
} for tx in self.store.between(PROVIDER, start, end)]}
|
|
246
|
+
|
|
247
|
+
# ---- helpers -----------------------------------------------------------
|
|
248
|
+
|
|
249
|
+
def _order_and_amount(self, params: dict) -> tuple[str, Decimal]:
|
|
250
|
+
tiyin = params.get("amount")
|
|
251
|
+
if isinstance(tiyin, bool) or not isinstance(tiyin, (int, float)) or tiyin <= 0:
|
|
252
|
+
raise PaymeError(PaymeError.WRONG_AMOUNT)
|
|
253
|
+
account = params.get("account")
|
|
254
|
+
if not isinstance(account, dict) or account.get(self.account_field) in (None, ""):
|
|
255
|
+
raise PaymeError(PaymeError.ORDER_NOT_FOUND, self.account_field)
|
|
256
|
+
return str(account[self.account_field]), Decimal(int(tiyin)) / 100
|
|
257
|
+
|
|
258
|
+
def _check_order(self, order_id: str, amount: Decimal) -> None:
|
|
259
|
+
due = self.orders.get_amount(order_id)
|
|
260
|
+
if due is None:
|
|
261
|
+
raise PaymeError(PaymeError.ORDER_NOT_FOUND, self.account_field)
|
|
262
|
+
if not self.orders.is_payable(order_id):
|
|
263
|
+
raise PaymeError(PaymeError.ORDER_NOT_PAYABLE, self.account_field)
|
|
264
|
+
if som_to_tiyin(due) != som_to_tiyin(amount):
|
|
265
|
+
raise PaymeError(PaymeError.WRONG_AMOUNT)
|
|
266
|
+
|
|
267
|
+
def _get(self, params: dict) -> Transaction:
|
|
268
|
+
tx = self.store.get(PROVIDER, _required_str(params, "id"))
|
|
269
|
+
if tx is None:
|
|
270
|
+
raise PaymeError(PaymeError.TRANSACTION_NOT_FOUND)
|
|
271
|
+
return tx
|
|
272
|
+
|
|
273
|
+
def _expired(self, tx: Transaction) -> bool:
|
|
274
|
+
return self.clock() - tx.create_time > TIMEOUT_MS
|
|
275
|
+
|
|
276
|
+
def _cancel(self, tx: Transaction, reason) -> None:
|
|
277
|
+
tx.state = State.CANCELLED_AFTER_PERFORM if tx.is_performed else State.CANCELLED
|
|
278
|
+
tx.cancel_time = self.clock()
|
|
279
|
+
tx.reason = int(reason) if isinstance(reason, int) else Reason.UNKNOWN
|
|
280
|
+
self.store.update(tx)
|
|
281
|
+
self.orders.on_cancelled(tx.order_id, tx)
|
|
282
|
+
|
|
283
|
+
@staticmethod
|
|
284
|
+
def _created(tx: Transaction) -> dict:
|
|
285
|
+
return {"create_time": tx.create_time, "transaction": str(tx.id), "state": tx.state}
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def som_to_tiyin(amount) -> int:
|
|
289
|
+
return int((to_decimal(amount) * 100).to_integral_value())
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _required_str(params: dict, name: str) -> str:
|
|
293
|
+
v = params.get(name)
|
|
294
|
+
if not isinstance(v, str) or not v:
|
|
295
|
+
raise PaymeError(PaymeError.INVALID_REQUEST, name)
|
|
296
|
+
return v
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _required_int(params: dict, name: str) -> int:
|
|
300
|
+
v = params.get(name)
|
|
301
|
+
if isinstance(v, bool) or not isinstance(v, int):
|
|
302
|
+
raise PaymeError(PaymeError.INVALID_REQUEST, name)
|
|
303
|
+
return v
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: uzpay
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Click and Payme merchant APIs for Python: checkout links, webhook handling, Django integration. No dependencies.
|
|
5
|
+
Project-URL: Homepage, https://github.com/hamidillomannopov-stack/uzpay
|
|
6
|
+
Project-URL: Issues, https://github.com/hamidillomannopov-stack/uzpay/issues
|
|
7
|
+
Project-URL: Changelog, https://github.com/hamidillomannopov-stack/uzpay/blob/main/CHANGELOG.md
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: click,django,merchant-api,paycom,payme,payments,uzbekistan
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Framework :: Django
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Provides-Extra: django
|
|
19
|
+
Requires-Dist: django>=4.2; extra == 'django'
|
|
20
|
+
Provides-Extra: test
|
|
21
|
+
Requires-Dist: django>=4.2; extra == 'test'
|
|
22
|
+
Requires-Dist: pytest-django>=4.5; extra == 'test'
|
|
23
|
+
Requires-Dist: pytest>=7; extra == 'test'
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# uzpay
|
|
27
|
+
|
|
28
|
+
[](https://github.com/hamidillomannopov-stack/uzpay/actions/workflows/tests.yml)
|
|
29
|
+
[](https://github.com/hamidillomannopov-stack/uzpay/blob/main/LICENSE)
|
|
30
|
+
|
|
31
|
+
**Click and Payme for Python, done right.** Payment links and the merchant-side webhook
|
|
32
|
+
protocols for Uzbekistan's two main payment systems, with a ready Django integration.
|
|
33
|
+
|
|
34
|
+
## Why uzpay
|
|
35
|
+
|
|
36
|
+
- **Both providers, one API.** Click and Payme share the same `OrderHandler` and the same transaction
|
|
37
|
+
table, so adding the second provider is three lines, not a second integration.
|
|
38
|
+
- **A protocol checker you can point at production.** `tools/payme_check.py` plays Payme and runs 32
|
|
39
|
+
scenarios against any endpoint, written with uzpay or not.
|
|
40
|
+
- **Nothing to install.** The core is pure standard library.
|
|
41
|
+
|
|
42
|
+
## Features
|
|
43
|
+
|
|
44
|
+
- No dependencies in the core: works with Django, FastAPI, Flask or plain WSGI.
|
|
45
|
+
- Full protocol: Click Prepare/Complete with signature check; all six Payme Merchant API methods,
|
|
46
|
+
including the 12-hour timeout, idempotent retries, cancellations and `GetStatement`.
|
|
47
|
+
- You write three small methods ("how much is this order", "it's paid", optionally "it's cancelled").
|
|
48
|
+
uzpay keeps the transaction state machine.
|
|
49
|
+
- Tested: 31 unit tests plus a 32-scenario HTTP check of the Payme protocol.
|
|
50
|
+
|
|
51
|
+
[O'zbekcha qo'llanma pastda](#ozbekcha)
|
|
52
|
+
|
|
53
|
+
## Install
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
pip install uzpay # core
|
|
57
|
+
pip install "uzpay[django]" # with the Django app
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## 1. Tell uzpay about your orders
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from uzpay import OrderHandler
|
|
64
|
+
|
|
65
|
+
class ShopOrders(OrderHandler):
|
|
66
|
+
def get_amount(self, order_id):
|
|
67
|
+
order = Order.objects.filter(pk=order_id).first()
|
|
68
|
+
return order.total if order else None # so'm; None = no such order
|
|
69
|
+
|
|
70
|
+
def is_payable(self, order_id):
|
|
71
|
+
return Order.objects.filter(pk=order_id, status="new").exists()
|
|
72
|
+
|
|
73
|
+
def on_paid(self, order_id, tx):
|
|
74
|
+
Order.objects.filter(pk=order_id).update(status="paid")
|
|
75
|
+
|
|
76
|
+
def on_cancelled(self, order_id, tx): # optional
|
|
77
|
+
...
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## 2. Configure the providers
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
from uzpay import Click, Payme
|
|
84
|
+
from uzpay.contrib.django.store import DjangoStore # or MemoryStore / your own Store
|
|
85
|
+
|
|
86
|
+
click = Click(service_id=CLICK_SERVICE_ID, merchant_id=CLICK_MERCHANT_ID,
|
|
87
|
+
secret_key=CLICK_SECRET_KEY, orders=ShopOrders(), store=DjangoStore())
|
|
88
|
+
|
|
89
|
+
payme = Payme(merchant_id=PAYME_MERCHANT_ID, key=PAYME_KEY,
|
|
90
|
+
orders=ShopOrders(), store=DjangoStore(),
|
|
91
|
+
test=False) # True -> test.paycom.uz
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## 3. Send the customer to pay
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
click.checkout_url(order.pk, order.total, return_url="https://shop.uz/thanks")
|
|
98
|
+
payme.checkout_url(order.pk, order.total, return_url="https://shop.uz/thanks", lang="uz")
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Amounts are always in **so'm**. uzpay converts to tiyin for Payme.
|
|
102
|
+
|
|
103
|
+
## 4. Receive the webhooks
|
|
104
|
+
|
|
105
|
+
### Django
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
# settings.py
|
|
109
|
+
INSTALLED_APPS += ["uzpay.contrib.django"] # then: python manage.py migrate
|
|
110
|
+
|
|
111
|
+
# urls.py
|
|
112
|
+
from uzpay.contrib.django.views import click_view, payme_view
|
|
113
|
+
|
|
114
|
+
urlpatterns += [
|
|
115
|
+
path("pay/click/", click_view(click)), # set as both Prepare URL and Complete URL in Click
|
|
116
|
+
path("pay/payme/", payme_view(payme)), # set as the endpoint in the Payme cabinet
|
|
117
|
+
]
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
The views run inside `transaction.atomic()` and lock the transaction row, so parallel retries are safe.
|
|
121
|
+
Transactions show up in the `PaymentTransaction` model.
|
|
122
|
+
|
|
123
|
+
### FastAPI (or anything else)
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
@app.post("/pay/click")
|
|
127
|
+
async def click_hook(request: Request):
|
|
128
|
+
return click.handle(dict(await request.form()))
|
|
129
|
+
|
|
130
|
+
@app.post("/pay/payme")
|
|
131
|
+
async def payme_hook(request: Request):
|
|
132
|
+
return payme.handle(await request.body(), request.headers.get("authorization"))
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Outside Django, implement `uzpay.Store` (7 short methods) on top of your database, or use
|
|
136
|
+
`MemoryStore` for tests.
|
|
137
|
+
|
|
138
|
+
## Options
|
|
139
|
+
|
|
140
|
+
| Option | Default | Meaning |
|
|
141
|
+
|---|---|---|
|
|
142
|
+
| `Payme(account_field=...)` | `"order_id"` | Name of the account field configured in your Payme cabinet |
|
|
143
|
+
| `Payme(test=True)` | `False` | Checkout links point to `test.paycom.uz` |
|
|
144
|
+
| `OrderHandler.can_cancel_paid` | `False` | Allow Payme to cancel (refund) a paid transaction |
|
|
145
|
+
| `Click(merchant_user_id=...)` | `None` | Added to checkout links if your Click service requires it |
|
|
146
|
+
|
|
147
|
+
## Error codes
|
|
148
|
+
|
|
149
|
+
uzpay answers with the codes each provider expects:
|
|
150
|
+
|
|
151
|
+
- **Click:** `-1` bad signature, `-2` wrong amount, `-4` already paid, `-5` order not found,
|
|
152
|
+
`-6` transaction not found, `-7` `on_paid` raised, `-8` bad request, `-9` cancelled.
|
|
153
|
+
- **Payme:** `-32504` bad key, `-31001` wrong amount, `-31003` transaction not found,
|
|
154
|
+
`-31007` cannot cancel, `-31008` cannot perform (state or timeout), `-31050` order not found,
|
|
155
|
+
`-31051` order already paid, `-31052` order is being paid in another transaction.
|
|
156
|
+
|
|
157
|
+
## Check any Payme endpoint
|
|
158
|
+
|
|
159
|
+
`tools/payme_check.py` plays the role of Payme and runs 32 sandbox-style scenarios (bad key,
|
|
160
|
+
wrong amount, unknown order, retries, refunds, cancellations, 12-hour timeout, `GetStatement`)
|
|
161
|
+
against a live URL. It works with any Merchant API implementation, not only uzpay, and needs only
|
|
162
|
+
the standard library:
|
|
163
|
+
|
|
164
|
+
```bash
|
|
165
|
+
python tools/payme_check.py https://shop.uz/pay/payme/ --key TEST_KEY --orders 11,12,13 --amount 1000
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
A runnable demo shop lives in [examples/django_demo](https://github.com/hamidillomannopov-stack/uzpay/tree/main/examples/django_demo).
|
|
169
|
+
|
|
170
|
+
## Development
|
|
171
|
+
|
|
172
|
+
```bash
|
|
173
|
+
pip install -e ".[test]"
|
|
174
|
+
pytest
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
---
|
|
178
|
+
|
|
179
|
+
## O'zbekcha
|
|
180
|
+
|
|
181
|
+
**uzpay** — Click va Payme to'lov tizimlarini Python loyihangizga ulash uchun kutubxona.
|
|
182
|
+
|
|
183
|
+
**Nima qiladi:**
|
|
184
|
+
- to'lov havolasini yaratadi (`checkout_url`);
|
|
185
|
+
- Click va Payme serverlaridan keladigan so'rovlarni to'liq qayta ishlaydi: imzo va kalitni tekshiradi,
|
|
186
|
+
tranzaksiya holatini saqlaydi, takroriy so'rovlarga to'g'ri javob beradi, 12 soatlik muddatni kuzatadi;
|
|
187
|
+
- Django uchun tayyor model, migratsiya va view'lar bor.
|
|
188
|
+
|
|
189
|
+
**Sizdan kerak bo'lgani** — `OrderHandler`'dan meros olib, uchta metod yozish:
|
|
190
|
+
|
|
191
|
+
| Metod | Vazifasi |
|
|
192
|
+
|---|---|
|
|
193
|
+
| `get_amount(order_id)` | Buyurtma summasini so'mda qaytaring, topilmasa `None` |
|
|
194
|
+
| `is_payable(order_id)` | Buyurtma allaqachon to'langan yoki yopilgan bo'lsa `False` |
|
|
195
|
+
| `on_paid(order_id, tx)` | Pul tushdi: buyurtmani «to'langan» deb belgilang |
|
|
196
|
+
|
|
197
|
+
Keyin yuqoridagi 2–4-qadamlarni bajaring. Click kabinetida **Prepare URL** va **Complete URL** uchun
|
|
198
|
+
bitta manzilni (`/pay/click/`) bering, Payme kabinetida esa endpoint sifatida `/pay/payme/` ni.
|
|
199
|
+
|
|
200
|
+
Savol va takliflar uchun issue oching, PR'lar mamnuniyat bilan qabul qilinadi.
|
|
201
|
+
|
|
202
|
+
## License
|
|
203
|
+
|
|
204
|
+
MIT
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
uzpay/__init__.py,sha256=OZrGMfGN7SFK466rIAFxeZ6qjMqsMMZyx_blNmeUR5E,427
|
|
2
|
+
uzpay/click.py,sha256=zIvys6aUqVr1AmcI2N3D5H3vBT3g9RIS-can3ygxMpQ,7906
|
|
3
|
+
uzpay/core.py,sha256=XIE6dPAfxw9irdE8r0H3tIPSWDOWqvLU5ieBHDm9YSo,5080
|
|
4
|
+
uzpay/payme.py,sha256=bDsTFpROjtYsV6XTGrWCdExDvyjFPLhRw77nhKsBtqM,12932
|
|
5
|
+
uzpay/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
uzpay/contrib/django/__init__.py,sha256=7i21wVmGSvdY7n-qcen-JfmsEViZWCGjOpIzg8OWWJA,92
|
|
7
|
+
uzpay/contrib/django/apps.py,sha256=Rj-Tu1_tUJADyDUlMpfTL_Gn-0Re_O_6l69mQPdi0j4,212
|
|
8
|
+
uzpay/contrib/django/models.py,sha256=W-Jcc_5e5uAmGacrXvfrSyyDdHTiu5z3dz6i2HbF32M,1299
|
|
9
|
+
uzpay/contrib/django/store.py,sha256=M1Sn8uNnoQybrCOuHXNATIYejV5FgTMHKZArUUV1x6U,1840
|
|
10
|
+
uzpay/contrib/django/views.py,sha256=MrgaGJFjDXr6a2dvS8H7Ybq1mpgaVcMwAlvwXoM3QGI,1197
|
|
11
|
+
uzpay/contrib/django/migrations/0001_initial.py,sha256=V7WFhc7iQLT5puM0u0vfAfnFcQi_lGsivWZaf3H2QOU,1622
|
|
12
|
+
uzpay/contrib/django/migrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
13
|
+
uzpay-0.1.0.dist-info/METADATA,sha256=nMjrPVJnTgEckF4yUi1-QVejrCwcO3vLVixhd2F_dFE,7770
|
|
14
|
+
uzpay-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
15
|
+
uzpay-0.1.0.dist-info/licenses/LICENSE,sha256=9t6yzgwJ9zYLPe92A7XBSZPSuzY4x7oJhrFKjAXNH4s,1075
|
|
16
|
+
uzpay-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hamidillo Mannopov
|
|
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.
|