forked from HSE_team/BetterCallPraskovia
71 lines
3.0 KiB
Python
71 lines
3.0 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.services.user_service import UserService
|
|
from tg_bot.infrastructure.database.database import SessionLocal
|
|
from tg_bot.infrastructure.database.models import UserModel
|
|
from aiogram import Bot
|
|
|
|
session = SessionLocal()
|
|
if event_type == "payment.succeeded":
|
|
payment = data.get("object", {})
|
|
user_id = payment.get("metadata", {}).get("user_id")
|
|
|
|
if user_id:
|
|
user_service = UserService(session)
|
|
success = await user_service.activate_premium(int(user_id))
|
|
if success:
|
|
print(f"Premium activated for user {user_id}")
|
|
|
|
user = session.query(UserModel).filter_by(
|
|
telegram_id=str(user_id)
|
|
).first()
|
|
|
|
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")
|
|
session.close()
|
|
|
|
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")
|