2025-12-24 15:16:27 +03:00

65 lines
2.8 KiB
Python

import json
from fastapi import APIRouter, Request, HTTPException
from fastapi.responses import JSONResponse
import sys
import os
from datetime import datetime, timedelta
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
router = APIRouter()
@router.post("/payment/webhook")
async def handle_yookassa_webhook(request: Request):
try:
data = await request.json()
event_type = data.get("event")
print(f"Webhook received: {event_type}")
try:
from tg_bot.config.settings import settings
from tg_bot.domain.user_service import UserService
from aiogram import Bot
if event_type == "payment.succeeded":
payment = data.get("object", {})
user_id = payment.get("metadata", {}).get("user_id")
if user_id:
user_service = UserService()
success = await user_service.activate_premium(int(user_id))
if success:
print(f"Premium activated for user {user_id}")
user = await user_service.get_user_by_telegram_id(int(user_id))
if user and settings.TELEGRAM_BOT_TOKEN:
try:
bot = Bot(token=settings.TELEGRAM_BOT_TOKEN)
premium_until = user.premium_until or datetime.now() + timedelta(days=30)
notification = (
f"<b>Оплата подтверждена!</b>\n\n"
f"Premium активирован до {premium_until.strftime('%d.%m.%Y')}"
)
await bot.send_message(
chat_id=int(user_id),
text=notification,
parse_mode="HTML"
)
print(f"Notification sent to user {user_id}")
await bot.session.close()
except Exception as e:
print(f"Error sending notification: {e}")
else:
print(f"User {user_id} not found or failed to activate premium")
except ImportError as e:
print(f"Import error: {e}")
return JSONResponse({"status": "ok", "message": "Webhook processed"})
except Exception as e:
print(f"Error processing webhook: {e}")
raise HTTPException(status_code=500, detail="Internal server error")