Closes the last "still .env-only" gap from the backlog (tariffs/HWID) and fixes a real bug found while building it: payment provider credentials and enabled-flags were frozen in api.py's process at import time, so a Platega secret rotation via the settings UI would leave api.py verifying inbound webhooks against the OLD secret until a manual `mbs restart` — while bot.py (which does get restarted on save) already had the new one. Same class of staleness affected HWID_LIMIT_ENABLED/HWID_FALLBACK_LIMIT and plan prices, neither of which had any settings UI at all before this. New `settings.py` module: get_plans()/get_plans_by_code() (live prices, falls back to config.py defaults), get_payment_settings(), get_hwid_settings(), yookassa_credentials()/platega_credentials(), set_plan_prices() — all backed by a new batched legal.read_env_vars() (one file read for N keys instead of N reads) and legal.update_env_var() (moved out of api.py's private _update_env_var, which is now a one-line delegate to avoid duplicating the same env-file-rewrite logic in two places). api.py and bot.py no longer import PLANS/PLANS_BY_CODE/PAYMENTS_ENABLED/ HWID_LIMIT_ENABLED/HWID_FALLBACK_LIMIT from config as frozen constants — every read goes through settings.py instead. payments.py no longer imports YOOKASSA_*/PLATEGA_* from config either; every provider call (create/check payment, verify webhook signature) reads live credentials at call time. Every call site inside a loop hoists the live lookup before the loop first (same N+1 discipline as the rest of tonight), so this doesn't regress get_subscription's hot path — one settings.get_hwid_settings() call per request, same as before. New routes: GET/POST /admin/api/payments/plan-settings (per-plan prices + a payments_enabled master toggle — there was previously no way to turn payment collection back off without deleting provider credentials), GET/POST /admin/api/hwid-settings. Both validate input strictly (prices: non-negative int; HWID limit: 1-1000) and reject the whole request instead of partially applying on bad input. admin.html: new "Тарифы" section in Платежи (price inputs rendered from the live plan list + payments toggle) and "Лимит устройств (HWID)" in Настройки, both using the existing .check checkbox / plain-input styling (no native <select>, per the earlier white-popup complaint). Removed the now-incorrect "выполни mbs restart" copy from the YooKassa/Platega settings hints and save-result messages, and added a doc-block for HWID (never had one) plus extended the Платежи doc-block to mention live-apply. Also dropped a dead `import links` in bot.py caught by pyflakes while verifying this. Verification: api.py/bot.py still can't be imported on this Windows machine (no prebuilt pydantic-core wheel for Python 3.14, confirmed again by a fresh pip attempt — same wall as every prior session), so relied on what's actually exercisable: py_compile + pyflakes (zero undefined names) across every module including api.py/bot.py, a real runtime test against an isolated .env fixture covering live price/toggle/HWID reads with zero reimport, write-idempotency (no duplicate .env lines on repeated saves), and the concrete bug this fixes end to end — computed an HMAC signature against an old Platega secret, rotated the secret via update_env_var (the same call the settings route makes), confirmed the old signature is now rejected and a new one computed against the rotated secret verifies, all in the same process with no reimport. Also ran the new CI step's exact heredoc locally byte-for-byte before adding it to ci.yml. GitHub Actions still won't trigger for this account (still under abuse-review, ticket open >2 days) so this is the same substitute-for-CI rigor used all night. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
139 lines
4.7 KiB
Python
139 lines
4.7 KiB
Python
import base64
|
|
import hashlib
|
|
import hmac
|
|
import json
|
|
import secrets
|
|
import urllib.request
|
|
|
|
from config import PANEL_DOMAIN
|
|
import settings
|
|
|
|
PROVIDER_NAMES = {"yookassa": "ЮKassa", "platega": "Platega"}
|
|
|
|
|
|
def available_providers() -> list[str]:
|
|
enabled = settings.get_payment_settings()
|
|
providers = []
|
|
if enabled["yookassa_enabled"]:
|
|
providers.append("yookassa")
|
|
if enabled["platega_enabled"]:
|
|
providers.append("platega")
|
|
return providers
|
|
|
|
|
|
def new_payment_id() -> str:
|
|
return secrets.token_hex(16)
|
|
|
|
|
|
def _post_json(url: str, body: dict, headers: dict, timeout: int = 15) -> dict:
|
|
data = json.dumps(body).encode()
|
|
req = urllib.request.Request(url, data=data, method="POST", headers=headers)
|
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
return json.loads(resp.read().decode())
|
|
|
|
|
|
def _get_json(url: str, headers: dict, timeout: int = 15) -> dict:
|
|
req = urllib.request.Request(url, method="GET", headers=headers)
|
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
return json.loads(resp.read().decode())
|
|
|
|
|
|
def create_yookassa_payment(payment_id: str, amount_rub: int, description: str) -> str:
|
|
shop_id, secret_key = settings.yookassa_credentials()
|
|
auth = base64.b64encode(f"{shop_id}:{secret_key}".encode()).decode()
|
|
data = _post_json(
|
|
"https://api.yookassa.ru/v3/payments",
|
|
{
|
|
"amount": {"value": f"{amount_rub}.00", "currency": "RUB"},
|
|
"confirmation": {"type": "redirect", "return_url": f"https://{PANEL_DOMAIN}/pay/done"},
|
|
"capture": True,
|
|
"description": description,
|
|
"metadata": {"payment_id": payment_id},
|
|
},
|
|
{
|
|
"Content-Type": "application/json",
|
|
"Authorization": f"Basic {auth}",
|
|
"Idempotence-Key": payment_id,
|
|
},
|
|
)
|
|
external_id = data["id"]
|
|
pay_url = data["confirmation"]["confirmation_url"]
|
|
return external_id, pay_url
|
|
|
|
|
|
def validate_yookassa_credentials(shop_id: str, secret_key: str) -> dict:
|
|
auth = base64.b64encode(f"{shop_id}:{secret_key}".encode()).decode()
|
|
return _get_json("https://api.yookassa.ru/v3/me", {"Authorization": f"Basic {auth}"})
|
|
|
|
|
|
def verify_yookassa_notification(body: dict) -> bool:
|
|
return body.get("event") == "payment.succeeded" and "object" in body
|
|
|
|
|
|
def check_yookassa_payment(external_id: str) -> str:
|
|
shop_id, secret_key = settings.yookassa_credentials()
|
|
auth = base64.b64encode(f"{shop_id}:{secret_key}".encode()).decode()
|
|
data = _get_json(
|
|
f"https://api.yookassa.ru/v3/payments/{external_id}",
|
|
{"Authorization": f"Basic {auth}"},
|
|
)
|
|
return data.get("status", "")
|
|
|
|
|
|
def create_platega_payment(payment_id: str, amount_rub: int, description: str) -> str:
|
|
merchant_id, secret = settings.platega_credentials()
|
|
data = _post_json(
|
|
"https://app.platega.io/transaction/process",
|
|
{
|
|
"paymentMethod": 2,
|
|
"id": payment_id,
|
|
"paymentDetails": {"amount": amount_rub, "currency": "RUB"},
|
|
"description": description,
|
|
"return": f"https://{PANEL_DOMAIN}/pay/done",
|
|
},
|
|
{
|
|
"Content-Type": "application/json",
|
|
"X-MerchantId": merchant_id,
|
|
"X-Secret": secret,
|
|
},
|
|
)
|
|
external_id = data.get("id") or data.get("transactionId")
|
|
pay_url = data.get("redirectUrl") or data.get("url")
|
|
return external_id, pay_url
|
|
|
|
|
|
def verify_platega_signature(raw_body: bytes, signature: str) -> bool:
|
|
if not signature:
|
|
return False
|
|
_, secret = settings.platega_credentials()
|
|
expected = hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
|
|
return hmac.compare_digest(expected, signature)
|
|
|
|
|
|
def check_platega_payment(external_id: str) -> str:
|
|
merchant_id, secret = settings.platega_credentials()
|
|
data = _get_json(
|
|
f"https://app.platega.io/transaction/{external_id}",
|
|
{"X-MerchantId": merchant_id, "X-Secret": secret},
|
|
)
|
|
return data.get("status", "")
|
|
|
|
|
|
PAID_STATUSES = {"succeeded", "CONFIRMED"}
|
|
FAILED_STATUSES = {"canceled", "CANCELED", "CHARGEBACKED"}
|
|
|
|
|
|
def create_payment_link(provider: str, payment_id: str, amount_rub: int, description: str):
|
|
if provider == "yookassa":
|
|
return create_yookassa_payment(payment_id, amount_rub, description)
|
|
if provider == "platega":
|
|
return create_platega_payment(payment_id, amount_rub, description)
|
|
raise ValueError(f"unknown provider: {provider}")
|
|
|
|
|
|
def check_payment_status(provider: str, external_id: str) -> str:
|
|
if provider == "yookassa":
|
|
return check_yookassa_payment(external_id)
|
|
if provider == "platega":
|
|
return check_platega_payment(external_id)
|
|
raise ValueError(f"unknown provider: {provider}")
|