Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
534 lines
29 KiB
Python
534 lines
29 KiB
Python
import asyncio
|
|
from contextlib import closing
|
|
from decimal import Decimal, InvalidOperation
|
|
import hashlib
|
|
import json
|
|
import re
|
|
import secrets
|
|
import sqlite3
|
|
import time
|
|
from urllib.parse import urlsplit
|
|
|
|
import aiohttp
|
|
|
|
CURRENCY = 'USD'
|
|
MAX_CENTS = 1_000_000_000
|
|
MAX_REQUESTS = 10_000_000
|
|
CP_BASE = 'https://pay.crypt.bot/api'
|
|
# A createInvoice call whose outcome is unknown (network failure) is terminalised
|
|
# after this grace window. It must exceed aiohttp ClientTimeout(total=20) by a wide
|
|
# margin so a same-request_id retry cannot race an in-flight create and expose a
|
|
# second remote invoice for one request_id.
|
|
AMBIGUITY_GRACE = 180
|
|
_REQUEST = re.compile(r'[A-Za-z0-9:_-]{12,96}\Z')
|
|
_ID = re.compile(r'[A-Za-z0-9_-]{1,64}\Z')
|
|
_MODEL = re.compile(r'[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}\Z')
|
|
|
|
|
|
class CommerceError(ValueError):
|
|
def __init__(self, status, code, message):
|
|
super().__init__(message)
|
|
self.status, self.code, self.message = status, code, message
|
|
self.operation_rejected = status < 500 and code in {
|
|
'invalid_body', 'request_id_required', 'unknown_action', 'invalid_offer_id',
|
|
'invalid_invoice_id', 'offer_unavailable', 'insufficient_funds',
|
|
'entitlement_limit', 'payment_mismatch', 'invoice_not_found', 'wallet_limit',
|
|
'invoice_abandoned'}
|
|
|
|
|
|
def _fail(status, code, message):
|
|
raise CommerceError(status, code, message)
|
|
|
|
|
|
def _connect(db):
|
|
con = sqlite3.connect(str(db), timeout=15, isolation_level=None)
|
|
con.row_factory = sqlite3.Row
|
|
con.execute('PRAGMA busy_timeout=15000')
|
|
return con
|
|
|
|
|
|
def init_db(db):
|
|
with closing(_connect(db)) as con:
|
|
con.executescript('''
|
|
CREATE TABLE IF NOT EXISTS commerce_wallets (
|
|
uid INTEGER PRIMARY KEY, balance_cents INTEGER NOT NULL DEFAULT 0
|
|
CHECK(balance_cents>=0 AND balance_cents<=1000000000));
|
|
CREATE TABLE IF NOT EXISTS commerce_operations (
|
|
uid INTEGER NOT NULL, request_id TEXT NOT NULL, digest TEXT NOT NULL,
|
|
result TEXT NOT NULL, PRIMARY KEY(uid,request_id));
|
|
CREATE TABLE IF NOT EXISTS commerce_invoices (
|
|
id TEXT PRIMARY KEY, uid INTEGER NOT NULL, request_id TEXT NOT NULL,
|
|
digest TEXT NOT NULL, offer_id TEXT NOT NULL, amount_cents INTEGER NOT NULL
|
|
CHECK(amount_cents>0), currency TEXT NOT NULL CHECK(currency='USD'),
|
|
provider_invoice_id INTEGER UNIQUE, payload TEXT NOT NULL UNIQUE,
|
|
status TEXT NOT NULL, pay_url TEXT NOT NULL DEFAULT '',
|
|
created INTEGER NOT NULL, updated INTEGER NOT NULL, credited_at INTEGER,
|
|
UNIQUE(uid,request_id));
|
|
CREATE TABLE IF NOT EXISTS commerce_ledger (
|
|
id INTEGER PRIMARY KEY, uid INTEGER NOT NULL, delta_cents INTEGER NOT NULL,
|
|
kind TEXT NOT NULL, offer_id TEXT, invoice_id TEXT, request_id TEXT NOT NULL,
|
|
ts INTEGER NOT NULL);
|
|
CREATE UNIQUE INDEX IF NOT EXISTS commerce_payment_once
|
|
ON commerce_ledger(invoice_id) WHERE kind='payment';
|
|
CREATE TABLE IF NOT EXISTS commerce_grants (
|
|
id INTEGER PRIMARY KEY, uid INTEGER NOT NULL, kind TEXT NOT NULL,
|
|
requests INTEGER NOT NULL DEFAULT 0, model TEXT NOT NULL DEFAULT '',
|
|
expires_at INTEGER NOT NULL, base_granted INTEGER NOT NULL DEFAULT 0,
|
|
request_id TEXT NOT NULL, created INTEGER NOT NULL, UNIQUE(uid,request_id));
|
|
CREATE INDEX IF NOT EXISTS commerce_grants_uid ON commerce_grants(uid,expires_at);
|
|
CREATE INDEX IF NOT EXISTS commerce_ledger_uid ON commerce_ledger(uid,id);
|
|
CREATE INDEX IF NOT EXISTS commerce_invoices_uid ON commerce_invoices(uid,created);
|
|
''')
|
|
|
|
|
|
def _now(now):
|
|
return int(time.time()) if now is None else int(now)
|
|
|
|
|
|
def _user(con, uid):
|
|
if type(uid) is not int or not 0 < uid <= 9223372036854775807:
|
|
_fail(400, 'invalid_user', 'Некорректный пользователь.')
|
|
row = con.execute('SELECT * FROM users WHERE tg_id=?', (uid,)).fetchone()
|
|
if row is None:
|
|
_fail(403, 'not_registered', 'Сначала открой бота и зарегистрируйся.')
|
|
user = dict(row)
|
|
if user.get('banned') or user.get('api_blocked'):
|
|
_fail(403, 'blocked', 'Доступ к покупкам ограничен.')
|
|
return user
|
|
|
|
|
|
def configured_offers(offers=()):
|
|
"""Validate only operator-owned configuration. No default prices or products."""
|
|
if offers is None:
|
|
offers = []
|
|
if not isinstance(offers, (list, tuple)) or len(offers) > 100:
|
|
_fail(503, 'commerce_config_invalid', 'Конфигурация магазина недоступна.')
|
|
result, seen = [], set()
|
|
for item in offers:
|
|
if not isinstance(item, dict):
|
|
_fail(503, 'commerce_config_invalid', 'Конфигурация магазина недоступна.')
|
|
identity, kind, price = item.get('id'), item.get('kind'), item.get('price_cents')
|
|
if (not isinstance(identity, str) or not _ID.fullmatch(identity) or identity in seen
|
|
or kind not in ('wallet_topup', 'extra_requests', 'model_pass')
|
|
or type(price) is not int or not 0 < price <= MAX_CENTS):
|
|
_fail(503, 'commerce_config_invalid', 'Конфигурация магазина недоступна.')
|
|
offer = {'id': identity, 'kind': kind, 'price_cents': price, 'currency': CURRENCY,
|
|
'title': str(item.get('title') or identity)[:160]}
|
|
if kind == 'extra_requests':
|
|
requests = item.get('requests')
|
|
if type(requests) is not int or not 0 < requests <= MAX_REQUESTS:
|
|
_fail(503, 'commerce_config_invalid', 'Конфигурация магазина недоступна.')
|
|
offer.update(requests=requests, duration='msk_day')
|
|
elif kind == 'model_pass':
|
|
model = item.get('model')
|
|
if not isinstance(model, str) or not _MODEL.fullmatch(model):
|
|
_fail(503, 'commerce_config_invalid', 'Конфигурация магазина недоступна.')
|
|
offer.update(model=model, duration_seconds=86400)
|
|
seen.add(identity)
|
|
result.append(offer)
|
|
return result
|
|
|
|
|
|
def _offer(offers, identity, kinds):
|
|
available = configured_offers(offers)
|
|
if not available:
|
|
_fail(503, 'commerce_unavailable', 'Покупки пока не настроены.')
|
|
offer = next((item for item in available if item['id'] == identity), None)
|
|
if offer is None or offer['kind'] not in kinds:
|
|
_fail(400, 'offer_unavailable', 'Такое предложение недоступно.')
|
|
return offer
|
|
|
|
|
|
def _empty_entitlements():
|
|
return {'extra_requests': 0, 'models': [], 'expires_at': None}
|
|
|
|
|
|
def _has_grants(con):
|
|
return bool(con.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='commerce_grants'").fetchone())
|
|
|
|
|
|
def _entitlements(con, uid, now):
|
|
if not _has_grants(con):
|
|
return _empty_entitlements()
|
|
rows = con.execute('SELECT kind,requests,model,expires_at FROM commerce_grants '
|
|
'WHERE uid=? AND expires_at>?', (uid, now)).fetchall()
|
|
return {'extra_requests': sum(int(row['requests']) for row in rows if row['kind'] == 'extra_requests'),
|
|
'models': sorted({row['model'] for row in rows if row['kind'] == 'model_pass'}),
|
|
'expires_at': min((int(row['expires_at']) for row in rows), default=None)}
|
|
|
|
|
|
def entitlements(db, uid, now=None):
|
|
with closing(_connect(db)) as con:
|
|
try:
|
|
_user(con, uid)
|
|
except CommerceError as error:
|
|
if error.code in ('blocked', 'not_registered'):
|
|
return _empty_entitlements()
|
|
raise
|
|
return _entitlements(con, uid, _now(now))
|
|
|
|
|
|
def managed_model_passes(db, uid, now=None):
|
|
stamp = _now(now)
|
|
with closing(_connect(db)) as con:
|
|
if not _has_grants(con):
|
|
return []
|
|
rows = con.execute("SELECT model,MAX(expires_at) AS expires_at,MAX(base_granted) AS base_granted "
|
|
"FROM commerce_grants WHERE uid=? AND kind='model_pass' GROUP BY model ORDER BY model",
|
|
(uid,)).fetchall()
|
|
return [{'model': row['model'], 'expires_at': int(row['expires_at']),
|
|
'active': int(row['expires_at']) > stamp, 'base_granted': bool(row['base_granted'])}
|
|
for row in rows]
|
|
|
|
|
|
def token_model_scope(db, uid, base_models, now=None):
|
|
"""Union for upstream model_limits; safe ONLY with a per-request expiry gate."""
|
|
return list(dict.fromkeys(list(base_models) + entitlements(db, uid, now)['models']))
|
|
|
|
|
|
def model_access(db, uid, model, base_models, now=None):
|
|
"""A model gate, not an auth/ban/subscription override."""
|
|
with closing(_connect(db)) as con:
|
|
try:
|
|
_user(con, uid)
|
|
except CommerceError:
|
|
return False
|
|
return model in base_models or model in _entitlements(con, uid, _now(now))['models']
|
|
|
|
|
|
def _body(body):
|
|
if not isinstance(body, dict):
|
|
_fail(400, 'invalid_body', 'Ожидается JSON-объект.')
|
|
request_id = body.get('request_id')
|
|
if not isinstance(request_id, str) or not _REQUEST.fullmatch(request_id):
|
|
_fail(400, 'request_id_required', 'Нужен уникальный идентификатор операции.')
|
|
action = body.get('action')
|
|
if action == 'buy':
|
|
action = 'purchase'
|
|
fields = {'purchase': 'offer_id', 'create_invoice': 'offer_id', 'check_invoice': 'invoice_id'}
|
|
if action not in fields:
|
|
_fail(400, 'unknown_action', 'Неизвестное действие магазина.')
|
|
selector = fields[action]
|
|
# Amount, paid and target identity never cross the trusted settlement boundary.
|
|
if set(body) - {'action', 'request_id', selector}:
|
|
_fail(400, 'invalid_body', 'Переданы неподдерживаемые поля операции.')
|
|
value = body.get(selector)
|
|
if not isinstance(value, str) or not _ID.fullmatch(value):
|
|
_fail(400, 'invalid_' + selector, 'Некорректный идентификатор операции.')
|
|
normalized = {'action': action, 'request_id': request_id, selector: value}
|
|
digest = hashlib.sha256(json.dumps(normalized, sort_keys=True).encode()).hexdigest()
|
|
return normalized, digest
|
|
|
|
|
|
def _receipt(con, uid, request_id, digest):
|
|
row = con.execute('SELECT digest,result FROM commerce_operations WHERE uid=? AND request_id=?',
|
|
(uid, request_id)).fetchone()
|
|
if row is None:
|
|
pending = con.execute('SELECT digest FROM commerce_invoices WHERE uid=? AND request_id=?',
|
|
(uid, request_id)).fetchone()
|
|
if pending is not None and pending['digest'] != digest:
|
|
_fail(409, 'request_conflict', 'Идентификатор уже использован другой операцией.')
|
|
return None
|
|
if row['digest'] != digest:
|
|
_fail(409, 'request_conflict', 'Идентификатор уже использован другой операцией.')
|
|
return json.loads(row['result'])
|
|
|
|
|
|
def _save_receipt(con, uid, body, digest, result):
|
|
con.execute('INSERT INTO commerce_operations(uid,request_id,digest,result) VALUES(?,?,?,?)',
|
|
(uid, body['request_id'], digest, json.dumps(result)))
|
|
|
|
|
|
def _invoice_public(row):
|
|
return {'id': row['id'], 'amount_cents': int(row['amount_cents']), 'currency': row['currency'],
|
|
'status': row['status'], 'pay_url': row['pay_url'], 'created': int(row['created'])}
|
|
|
|
|
|
def _token(token):
|
|
if not isinstance(token, str) or not token.strip():
|
|
_fail(503, 'payment_unavailable', 'Платежи пока не настроены.')
|
|
return token.strip()
|
|
|
|
|
|
def snapshot(db, uid, offers=(), cryptopay_token='', now=None):
|
|
available = configured_offers(offers)
|
|
with closing(_connect(db)) as con:
|
|
con.execute('BEGIN')
|
|
_user(con, uid)
|
|
row = con.execute('SELECT balance_cents FROM commerce_wallets WHERE uid=?', (uid,)).fetchone()
|
|
history = [dict(item) for item in con.execute(
|
|
'SELECT id,delta_cents,kind,offer_id,invoice_id,ts FROM commerce_ledger '
|
|
'WHERE uid=? ORDER BY id DESC LIMIT 50', (uid,))]
|
|
invoices = [_invoice_public(item) for item in con.execute(
|
|
'SELECT * FROM commerce_invoices WHERE uid=? ORDER BY created DESC,id DESC LIMIT 30', (uid,))]
|
|
result = {'uid': uid, 'wallet_cents': int(row[0]) if row else 0, 'currency': CURRENCY, 'offers': available,
|
|
'entitlements': _entitlements(con, uid, _now(now)), 'history': history, 'invoices': invoices,
|
|
'payment_enabled': bool(isinstance(cryptopay_token, str) and cryptopay_token.strip()
|
|
and any(item['kind'] == 'wallet_topup' for item in available))}
|
|
if not available:
|
|
result['unavailable_reason'] = 'commerce_unavailable'
|
|
elif not result['payment_enabled']:
|
|
result['unavailable_reason'] = 'payment_unavailable'
|
|
con.commit()
|
|
return result
|
|
|
|
|
|
def purchase(db, uid, body, offers=(), now=None, base_models=(), available_models=None):
|
|
body, digest = _body(body)
|
|
if body['action'] != 'purchase':
|
|
_fail(400, 'unknown_action', 'Ожидалась покупка предложения.')
|
|
stamp = _now(now)
|
|
with closing(_connect(db)) as con:
|
|
try:
|
|
con.execute('BEGIN IMMEDIATE')
|
|
_user(con, uid)
|
|
previous = _receipt(con, uid, body['request_id'], digest)
|
|
if previous is not None:
|
|
con.rollback()
|
|
return dict(previous, replayed=True)
|
|
offer = _offer(offers, body['offer_id'], ('extra_requests', 'model_pass'))
|
|
if (offer["kind"] == "model_pass" and available_models is not None
|
|
and offer["model"] not in available_models):
|
|
_fail(503, "model_offer_unavailable", "Предложение модели недоступно. Средства не списаны.")
|
|
price = offer['price_cents']
|
|
con.execute('INSERT OR IGNORE INTO commerce_wallets(uid) VALUES(?)', (uid,))
|
|
if not con.execute('UPDATE commerce_wallets SET balance_cents=balance_cents-? '
|
|
'WHERE uid=? AND balance_cents>=?', (price, uid, price)).rowcount:
|
|
_fail(409, 'insufficient_funds', 'Недостаточно средств в денежном кошельке.')
|
|
expires = stamp - ((stamp + 10800) % 86400) + 86400 if offer['kind'] == 'extra_requests' else stamp + 86400
|
|
if offer['kind'] == 'extra_requests' and _entitlements(con, uid, stamp)['extra_requests'] + offer['requests'] > MAX_REQUESTS:
|
|
_fail(409, 'entitlement_limit', 'Достигнут максимальный дополнительный лимит.')
|
|
con.execute('INSERT INTO commerce_grants(uid,kind,requests,model,expires_at,base_granted,request_id,created) '
|
|
'VALUES(?,?,?,?,?,?,?,?)',
|
|
(uid, offer['kind'], offer.get('requests', 0), offer.get('model', ''), expires,
|
|
int(offer.get('model') in base_models), body['request_id'], stamp))
|
|
con.execute('INSERT INTO commerce_ledger(uid,delta_cents,kind,offer_id,request_id,ts) VALUES(?,?,?,?,?,?)',
|
|
(uid, -price, 'purchase', offer['id'], body['request_id'], stamp))
|
|
result = {'ok': True, 'action': 'purchase', 'offer_id': offer['id'], 'expires_at': expires,
|
|
'charged_cents': price}
|
|
_save_receipt(con, uid, body, digest, result)
|
|
con.commit()
|
|
return result
|
|
except BaseException:
|
|
con.rollback()
|
|
raise
|
|
|
|
|
|
async def _cp_post(token, method, data):
|
|
token = _token(token)
|
|
try:
|
|
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=20)) as session:
|
|
async with session.post(CP_BASE + '/' + method, json=data,
|
|
headers={'Crypto-Pay-API-Token': token}, allow_redirects=False) as response:
|
|
if response.status != 200:
|
|
_fail(503, 'payment_provider_unavailable', 'Платёжный сервис временно недоступен.')
|
|
result = await response.json()
|
|
except CommerceError:
|
|
# A provider-status failure already carries an exact message; do not let the
|
|
# broad ValueError net (CommerceError subclasses ValueError) swallow it.
|
|
raise
|
|
except (aiohttp.ClientError, asyncio.TimeoutError, ValueError):
|
|
_fail(503, 'payment_provider_unavailable', 'Не удалось подтвердить ответ платёжного сервиса.')
|
|
if not isinstance(result, dict) or result.get('ok') is not True:
|
|
_fail(503, 'payment_provider_unavailable', 'Платёжный сервис временно недоступен.')
|
|
return result.get('result')
|
|
|
|
|
|
def _invoice_matches(remote, local, paid=False):
|
|
if not isinstance(remote, dict):
|
|
_fail(409, 'payment_mismatch', 'Параметры счёта не подтверждены платёжным сервисом.')
|
|
try:
|
|
amount = Decimal(str(remote.get('amount')))
|
|
valid_amount = amount.is_finite() and amount == Decimal(local['amount_cents']) / 100
|
|
except (InvalidOperation, ValueError, TypeError):
|
|
valid_amount = False
|
|
valid = (type(remote.get('invoice_id')) is int and remote['invoice_id'] > 0 and valid_amount
|
|
and remote.get('currency_type') == 'fiat' and remote.get('fiat') == local['currency']
|
|
and remote.get('payload') == local['payload'])
|
|
if local['provider_invoice_id'] is not None:
|
|
valid = valid and remote.get('invoice_id') == local['provider_invoice_id']
|
|
if not valid or paid and remote.get('status') != 'paid':
|
|
_fail(409, 'payment_mismatch', 'Параметры счёта не подтверждены платёжным сервисом.')
|
|
|
|
|
|
def _reserve_invoice(db, uid, body, digest, offers, stamp):
|
|
with closing(_connect(db)) as con:
|
|
try:
|
|
con.execute('BEGIN IMMEDIATE')
|
|
_user(con, uid)
|
|
previous = _receipt(con, uid, body['request_id'], digest)
|
|
if previous is not None:
|
|
con.rollback()
|
|
return None, dict(previous, replayed=True)
|
|
row = con.execute('SELECT * FROM commerce_invoices WHERE uid=? AND request_id=?',
|
|
(uid, body['request_id'])).fetchone()
|
|
if row:
|
|
if row['digest'] != digest:
|
|
_fail(409, 'request_conflict', 'Идентификатор уже использован другой операцией.')
|
|
# No provider idempotency guarantee: never create a second remote invoice.
|
|
if row['provider_invoice_id'] is not None:
|
|
_fail(409, 'request_conflict', 'Счёт уже создан; повтор с тем же номером недоступен.')
|
|
if stamp - int(row['created']) < AMBIGUITY_GRACE:
|
|
# A concurrent create for this request_id may still commit; retryable.
|
|
_fail(503, 'invoice_unconfirmed',
|
|
'Создание счёта не подтверждено. Повтори проверку с тем же номером.')
|
|
# Past the grace window no create can still be in flight and this row
|
|
# never exposed a pay_url, so it is inert. Terminalise the retry so the
|
|
# client mints a new request_id instead of looping on 503 forever.
|
|
_fail(409, 'invoice_abandoned',
|
|
'Создание счёта не подтверждено и истекло. Создай новый счёт с новым номером операции.')
|
|
offer = _offer(offers, body['offer_id'], ('wallet_topup',))
|
|
identity, payload = secrets.token_hex(16), secrets.token_hex(24)
|
|
con.execute('INSERT INTO commerce_invoices(id,uid,request_id,digest,offer_id,amount_cents,currency,'
|
|
'payload,status,created,updated) VALUES(?,?,?,?,?,?,?,?,?,?,?)',
|
|
(identity, uid, body['request_id'], digest, offer['id'], offer['price_cents'],
|
|
CURRENCY, payload, 'creating', stamp, stamp))
|
|
row = dict(con.execute('SELECT * FROM commerce_invoices WHERE id=?', (identity,)).fetchone())
|
|
con.commit()
|
|
return row, None
|
|
except BaseException:
|
|
con.rollback()
|
|
raise
|
|
|
|
|
|
def _mark_uncertain(db, identity, stamp):
|
|
with closing(_connect(db)) as con:
|
|
con.execute("UPDATE commerce_invoices SET status='uncertain',updated=? WHERE id=? AND status='creating'",
|
|
(stamp, identity))
|
|
|
|
|
|
def _save_invoice(db, uid, body, digest, local, remote, stamp):
|
|
_invoice_matches(remote, local)
|
|
pay_url = remote.get('bot_invoice_url') or remote.get('mini_app_invoice_url') or remote.get('pay_url')
|
|
if not isinstance(pay_url, str):
|
|
_fail(503, 'invoice_unconfirmed', 'Ссылка на оплату не подтверждена.')
|
|
parsed = urlsplit(pay_url)
|
|
if (parsed.scheme != 'https' or parsed.hostname not in ('t.me', 'pay.crypt.bot', 'crypt.bot')
|
|
or parsed.username or parsed.password):
|
|
_fail(503, 'invoice_unconfirmed', 'Ссылка на оплату не подтверждена.')
|
|
with closing(_connect(db)) as con:
|
|
try:
|
|
con.execute('BEGIN IMMEDIATE')
|
|
_user(con, uid)
|
|
duplicate = con.execute('SELECT id FROM commerce_invoices WHERE provider_invoice_id=? AND id!=?',
|
|
(remote['invoice_id'], local['id'])).fetchone()
|
|
if duplicate is not None:
|
|
_fail(409, 'payment_mismatch', 'Платёжный сервис вернул ранее использованный счёт.')
|
|
con.execute("UPDATE commerce_invoices SET provider_invoice_id=?,status='pending',pay_url=?,updated=? "
|
|
"WHERE id=? AND uid=? AND status='creating'", (remote['invoice_id'], pay_url, stamp, local['id'], uid))
|
|
row = con.execute('SELECT * FROM commerce_invoices WHERE id=? AND uid=?', (local['id'], uid)).fetchone()
|
|
if row['provider_invoice_id'] != remote['invoice_id']:
|
|
_fail(503, 'invoice_unconfirmed', 'Счёт ожидает проверки поддержки.')
|
|
result = {'ok': True, 'action': 'create_invoice', 'invoice': _invoice_public(row)}
|
|
_save_receipt(con, uid, body, digest, result)
|
|
con.commit()
|
|
return result
|
|
except BaseException:
|
|
con.rollback()
|
|
raise
|
|
|
|
|
|
def _load_invoice(db, uid, body, digest):
|
|
with closing(_connect(db)) as con:
|
|
_user(con, uid)
|
|
previous = _receipt(con, uid, body['request_id'], digest)
|
|
if previous is not None:
|
|
return None, dict(previous, replayed=True)
|
|
row = con.execute('SELECT * FROM commerce_invoices WHERE id=? AND uid=?',
|
|
(body['invoice_id'], uid)).fetchone()
|
|
if row is None:
|
|
_fail(404, 'invoice_not_found', 'Счёт не найден.')
|
|
if row['provider_invoice_id'] is None:
|
|
_fail(503, 'invoice_unconfirmed', 'Счёт ожидает проверки поддержки.')
|
|
return dict(row), None
|
|
|
|
|
|
def _settle_invoice(db, uid, body, digest, local, remote, stamp):
|
|
_invoice_matches(remote, local)
|
|
if remote.get('status') not in ('active', 'paid', 'expired'):
|
|
_fail(503, 'payment_provider_unavailable', 'Статус оплаты не подтверждён.')
|
|
with closing(_connect(db)) as con:
|
|
try:
|
|
con.execute('BEGIN IMMEDIATE')
|
|
_user(con, uid)
|
|
previous = _receipt(con, uid, body['request_id'], digest)
|
|
if previous is not None:
|
|
con.rollback()
|
|
return dict(previous, replayed=True)
|
|
row = con.execute('SELECT * FROM commerce_invoices WHERE id=? AND uid=?', (local['id'], uid)).fetchone()
|
|
if row is None or row['provider_invoice_id'] != remote['invoice_id']:
|
|
_fail(409, 'payment_mismatch', 'Счёт не соответствует ожидаемому платежу.')
|
|
_invoice_matches(remote, row)
|
|
credited = row['credited_at'] is not None
|
|
if remote['status'] == 'paid' and not credited:
|
|
con.execute('INSERT OR IGNORE INTO commerce_wallets(uid) VALUES(?)', (uid,))
|
|
if not con.execute('UPDATE commerce_wallets SET balance_cents=balance_cents+? '
|
|
'WHERE uid=? AND balance_cents<=?',
|
|
(row['amount_cents'], uid, MAX_CENTS-row['amount_cents'])).rowcount:
|
|
_fail(409, 'wallet_limit', 'Лимит кошелька превышен. Обратись в поддержку.')
|
|
con.execute('INSERT INTO commerce_ledger(uid,delta_cents,kind,offer_id,invoice_id,request_id,ts) '
|
|
"VALUES(?,?,'payment',?,?,?,?)",
|
|
(uid, row['amount_cents'], row['offer_id'], row['id'], body['request_id'], stamp))
|
|
con.execute("UPDATE commerce_invoices SET status='credited',credited_at=?,updated=? WHERE id=?",
|
|
(stamp, stamp, row['id']))
|
|
credited = True
|
|
elif not credited:
|
|
con.execute('UPDATE commerce_invoices SET status=?,updated=? WHERE id=?',
|
|
('expired' if remote['status'] == 'expired' else 'pending', stamp, row['id']))
|
|
row = con.execute('SELECT * FROM commerce_invoices WHERE id=?', (row['id'],)).fetchone()
|
|
result = {'ok': True, 'action': 'check_invoice', 'paid': credited,
|
|
'credited_cents': int(row['amount_cents']) if credited else 0,
|
|
'invoice': _invoice_public(row)}
|
|
_save_receipt(con, uid, body, digest, result)
|
|
con.commit()
|
|
return result
|
|
except BaseException:
|
|
con.rollback()
|
|
raise
|
|
|
|
|
|
async def act(db, uid, body, offers=(), cryptopay_token='', now=None, base_models=(), available_models=None):
|
|
"""Authenticated UID and offers/token must come from the server, not the body.
|
|
|
|
Each SQLite phase is a short transaction on a worker thread. No network I/O
|
|
occurs in a transaction. A failed/ambiguous create cannot mint a second invoice.
|
|
A confirmed pending check is a completed receipt; polling uses a new request_id.
|
|
"""
|
|
body, digest = _body(body)
|
|
stamp = _now(now)
|
|
if body['action'] == 'purchase':
|
|
result = await asyncio.to_thread(purchase, db, uid, body, offers, stamp, base_models, available_models)
|
|
elif body['action'] == 'create_invoice':
|
|
_token(cryptopay_token)
|
|
local, result = await asyncio.to_thread(_reserve_invoice, db, uid, body, digest, offers, stamp)
|
|
if result is None:
|
|
try:
|
|
remote = await _cp_post(cryptopay_token, 'createInvoice', {
|
|
'currency_type': 'fiat', 'fiat': local['currency'],
|
|
'amount': format(Decimal(local['amount_cents']) / 100, '.2f'),
|
|
'payload': local['payload'], 'description': 'IISHKO USD wallet',
|
|
'allow_comments': False, 'allow_anonymous': False, 'expires_in': 3600})
|
|
result = await asyncio.to_thread(_save_invoice, db, uid, body, digest, local, remote, stamp)
|
|
except BaseException as error:
|
|
await asyncio.to_thread(_mark_uncertain, db, local['id'], stamp)
|
|
if isinstance(error, CommerceError):
|
|
error.operation_rejected = False # A remote invoice may already exist.
|
|
raise
|
|
else:
|
|
# Local receipts are safe to replay even when a payment token is later disabled.
|
|
local, result = await asyncio.to_thread(_load_invoice, db, uid, body, digest)
|
|
if result is None:
|
|
_token(cryptopay_token)
|
|
response = await _cp_post(cryptopay_token, 'getInvoices', {'invoice_ids': str(local['provider_invoice_id'])})
|
|
items = response.get('items') if isinstance(response, dict) else None
|
|
if not isinstance(items, list) or len(items) != 1:
|
|
_fail(409, 'payment_mismatch', 'Платёжный сервис не подтвердил единственный ожидаемый счёт.')
|
|
result = await asyncio.to_thread(_settle_invoice, db, uid, body, digest, local, items[0], stamp)
|
|
try:
|
|
result['state'] = await asyncio.to_thread(snapshot, db, uid, offers, cryptopay_token, stamp)
|
|
except (CommerceError, sqlite3.Error, OSError, ValueError, TypeError, KeyError):
|
|
# The mutation already committed above; a best-effort state refresh must not
|
|
# mask a committed purchase/settle with a false error. The receipt stands.
|
|
result['state'] = None
|
|
return result
|