Проблема с оплатой CryptoPay в аиограм 3.x. Не найден счет, в чем проблема?
Помогите пожалуйста с кодом. После оплаты пишет "счет не найден"
import logging
from aiogram import Bot, Dispatcher, Router, F
from aiogram.types import BotCommand, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
from aiogram.filters import Command
import aiohttp
import asyncio
# Настройки
TELEGRAM_TOKEN = ''
CRYPTOPAY_API_TOKEN = ''
# Логирование
logging.basicConfig(level=logging.INFO)
# Создаем бота и диспетчер
bot = Bot(token=TELEGRAM_TOKEN)
dp = Dispatcher()
router = Router() # Создаем маршрутизатор
# Словарь для хранения данных счетов
invoices = {}
# Установка команд
async def set_commands(bot: Bot):
commands = [
BotCommand(command="start", description="Начать работу"),
BotCommand(command="invoice", description="Создать счет"),
]
await bot.set_my_commands(commands)
# Обработчик команды /start
@router.message(Command("start"))
async def send_welcome(message):
await message.answer("Привет! Я бот для работы с Crypto Pay. Используйте команду /invoice для создания счета.")
# Обработчик команды /invoice
@router.message(Command("invoice"))
async def create_invoice(message):
amount = 1.0 # Сумма
currency = 'USDT' # Валюта
description = 'Оплата за услуги'
invoice = await create_crypto_invoice(amount, currency, description)
if invoice:
pay_url = invoice.get('pay_url')
invoice_id = invoice.get('invoice_id')
invoices[invoice_id] = invoice # Сохраняем данные счета
# Создаем кнопку для проверки оплаты
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[InlineKeyboardButton(text="Проверить оплату", callback_data=f"check_payment:{invoice_id}")]
]
)
await message.answer(f"Счет создан! Оплатите по ссылке: {pay_url}", reply_markup=keyboard)
else:
await message.answer("Не удалось создать счет. Попробуйте позже.")
# Функция для создания счета через Crypto Pay API
async def create_crypto_invoice(amount, currency, description):
url = 'https://testnet-pay.crypt.bot/api/createInvoice'
headers = {
'Crypto-Pay-API-Token': CRYPTOPAY_API_TOKEN,
'Content-Type': 'application/json'
}
payload = {
'asset': currency,
'amount': amount,
'description': description
}
async with aiohttp.ClientSession() as session:
async with session.post(url, json=payload, headers=headers) as response:
response_text = await response.text()
logging.info(f"Запрос: {payload}")
logging.info(f"Ответ: {response_text}")
if response.status == 200:
result = await response.json()
if result.get('ok'):
return result.get('result')
logging.error(f"Ошибка при создании счета: {response.status}")
return None
# Обработчик кнопки "Проверить оплату"
@router.callback_query(F.data.startswith('check_payment'))
async def check_payment_status(callback: CallbackQuery):
invoice_id = callback.data.split(":")[1]
invoice = invoices.get(invoice_id)
if invoice:
status = await get_payment_status(invoice_id)
if status:
await callback.message.answer(f"Статус оплаты: {status}")
else:
await callback.message.answer("Не удалось получить статус оплаты.")
else:
await callback.message.answer("Счет не найден.")
# Функция для проверки статуса счета через Crypto Pay API
async def get_payment_status(invoice_id):
url = 'https://pay.crypt.bot/api/getInvoices'
headers = {
'Crypto-Pay-API-Token': CRYPTOPAY_API_TOKEN
}
payload = {
'invoice_ids': [invoice_id]
}
async with aiohttp.ClientSession() as session:
async with session.post(url, json=payload, headers=headers) as response:
response_text = await response.text()
logging.info(f"Запрос: {payload}")
logging.info(f"Ответ: {response_text}")
if response.status == 200:
result = await response.json()
if result.get('ok'):
invoices = result.get('result', [])
if invoices:
return invoices[0].get('status') # Возвращаем статус счета
logging.error(f"Ошибка при получении статуса счета: {response.status}")
return None
# Запуск бота
async def main():
await set_commands(bot)
dp.include_router(router) # Подключаем маршрутизатор
await dp.start_polling(bot)
if __name__ == '__main__':
asyncio.run(main())
Ответы (1 шт):
Автор решения: eri
→ Ссылка
Счёт создан в тестовой среде, а поиск статуса делаете в продуктовой. Проверьте домены и токены.