-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpayment.py
More file actions
87 lines (71 loc) · 2.29 KB
/
payment.py
File metadata and controls
87 lines (71 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import os
import httpx
import hashlib
TERMINAL_KEY = os.environ["TERMINAL_KEY"]
TERMINAL_PASSWORD = os.environ["TERMINAL_PASSWORD"]
ENV = os.getenv("TERMINAL_ENV", "test")
BASE_URL = (
"https://securepay.tinkoff.ru/v2"
if ENV == "prod"
else "https://rest-api-test.tinkoff.ru/v2"
)
# Список тестовых карт Тинькофф:
# https://developer.tbank.ru/eacq/intro/errors/test
#
# 4300 0000 0000 0777
# 12/30
# 111
PAYMENT_STATUSES = {
"NEW": "не оплачен",
"CONFIRMED": "оплачен",
"AUTHORIZED": "оплачен",
"CANCELED": "отменён",
"EXPIRED": "истёк",
}
def _generate_token(params: dict) -> str:
data = params.copy()
data["Password"] = TERMINAL_PASSWORD
token_str = "".join(str(data[k]) for k in sorted(data.keys()))
return hashlib.sha256(token_str.encode()).hexdigest()
async def init_payment(
order_id: str,
amount: int,
description: str,
success_url: str | None = None,
fail_url: str | None = None,
) -> dict:
payload = {
"TerminalKey": TERMINAL_KEY,
"Amount": amount,
"OrderId": order_id,
"Description": description,
}
if success_url:
payload["SuccessURL"] = success_url
if fail_url:
payload["FailURL"] = fail_url
payload["Token"] = _generate_token(payload)
async with httpx.AsyncClient(timeout=10.0) as client:
response = await client.post(f"{BASE_URL}/Init", json=payload)
response.raise_for_status()
return response.json()
async def get_payment_state(payment_id: int) -> dict:
payload = {
"TerminalKey": TERMINAL_KEY,
"PaymentId": payment_id,
}
payload["Token"] = _generate_token(payload)
async with httpx.AsyncClient(timeout=10.0) as client:
response = await client.post(f"{BASE_URL}/GetState", json=payload)
response.raise_for_status()
return response.json()
async def cancel_payment(payment_id: int) -> dict:
payload = {
"TerminalKey": TERMINAL_KEY,
"PaymentId": payment_id,
}
payload["Token"] = _generate_token(payload)
async with httpx.AsyncClient(timeout=10.0) as client:
response = await client.post(f"{BASE_URL}/Cancel", json=payload)
response.raise_for_status()
return response.json()