shopbot/bot/services/payments.py
2024-12-25 04:30:33 +03:00

155 lines
6.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import logging
from typing import Tuple
from aiogram.types import CallbackQuery
from aiogram_dialog import DialogManager, StartMode
from aiogram_dialog.widgets.kbd import Button
from AsyncPayments.cryptoBot import AsyncCryptoBot
from AsyncPayments.lolz import AsyncLolzteamMarketPayment
from environs import Env
from shopbot.bot.database import update_balance
from shopbot.bot.states import ProfileSG
env = Env()
env.read_env()
LOLZ_TOKEN = env("LOLZ_TOKEN")
CRYPTOBOT_TOKEN = env("CRYPTOBOT_TOKEN")
lolz_payment = AsyncLolzteamMarketPayment(token=LOLZ_TOKEN)
cryptobot_payment = AsyncCryptoBot(token=CRYPTOBOT_TOKEN)
async def create_paylink_lolz(amount: int) -> str:
return lolz_payment.get_payment_link(amount=amount)
async def create_paylink_cryptobot(amount: int) -> Tuple[str, str]:
try:
invoice = await cryptobot_payment.create_invoice(
amount=float(amount),
currency_type="fiat",
fiat="RUB",
description="Пополнение баланса",
accepted_assets=[
"USDT",
"TON",
"SOL",
"BTC",
"LTC",
"ETH",
"BNB",
"TRX",
"USDC",
],
)
return invoice.pay_url, str(invoice.invoice_id)
except Exception as e:
if "AMOUNT_TOO_SMALL" in str(e):
logging.error(f"Error creating CryptoBot invoice: {e}", exc_info=True)
return (
None,
"Сумма для пополнения должна быть не менее 0.01 USD (примерно 1 руб). Пожалуйста, проверьте и попробуйте снова, либо выберите другой способ оплаты.",
)
logging.error(f"Error creating CryptoBot invoice: {e}", exc_info=True)
return (
None,
"Произошла ошибка при создании ссылки для оплаты через CryptoBot. Попробуйте позже.",
)
async def check_pay_lolz(
callback: CallbackQuery, button: Button, manager: DialogManager, **kwargs
):
pay_data = manager.current_context().dialog_data.get("pay_data")
if not pay_data:
await callback.message.answer(
"Ошибка: данные оплаты не найдены. Попробуйте еще раз. ❌"
)
return
order_id = pay_data.get("order_id")
amount = pay_data.get("amount")
if not order_id or not amount:
await callback.message.answer(
"Ошибка: неверные данные оплаты. Попробуйте еще раз. ❌"
)
return
if manager.current_context().dialog_data.get("is_payment_processed", False):
await callback.answer("Оплата уже обработана.", show_alert=True)
return
try:
if not isinstance(amount, int):
amount = int(amount)
status = await lolz_payment.check_status_payment(
pay_amount=amount, comment=order_id
)
if status:
manager.current_context().dialog_data["is_payment_processed"] = True
await update_balance(callback.from_user.id, amount)
await callback.message.edit_text(
f"Поздравляем, счет пополнен на {amount} руб 🎉"
)
else:
await callback.message.answer(
"Счет не оплачен, проверьте оплату или проверьте еще раз! ⚠️"
)
except Exception as e:
logging.error(f"Error checking Lolz payment: {e}", exc_info=True)
await callback.message.answer(
"Произошла ошибка при проверке оплаты Lolz. Попробуйте позже. ❌"
)
async def check_pay_crypto_bot(
callback: CallbackQuery, button: Button, manager: DialogManager, **kwargs
):
pay_data = manager.current_context().dialog_data.get("pay_data")
if not pay_data:
await callback.message.answer(
"Ошибка: данные для оплаты не найдены. Попробуйте позже. ❌"
)
return
order_id = pay_data.get("order_id")
amount = pay_data.get("amount")
if not order_id or not amount:
await callback.message.answer(
"Ошибка: неверные данные оплаты. Попробуйте еще раз. ❌"
)
return
if manager.current_context().dialog_data.get("is_payment_processed", False):
await callback.answer("Оплата уже обработана.", show_alert=True)
return
try:
if not isinstance(amount, int):
amount = int(amount)
invoices = await cryptobot_payment.get_invoices(invoice_ids=[order_id])
if not invoices:
logging.warning(f"No invoices found with id: {order_id}")
await callback.message.answer("Оплата не найдена. Попробуйте позже. ⏳")
return
invoice = invoices[0]
if invoice.status == "paid":
manager.current_context().dialog_data["is_payment_processed"] = True
await update_balance(callback.from_user.id, amount)
await callback.message.answer(
f"Поздравляем, счет пополнен на {amount} руб 🎉"
)
await callback.message.delete()
await manager.start(state=ProfileSG.profile, mode=StartMode.RESET_STACK)
else:
logging.warning(f"Invoice with id: {order_id} status is: {invoice.status}")
await callback.message.answer("Оплата не найдена. Попробуйте позже. ⏳")
except Exception as e:
logging.error(f"Error checking CryptoBot payment: {e}", exc_info=True)
await callback.message.answer(
"Произошла ошибка при проверке оплаты через CryptoBot. Попробуйте позже. ❌"
)