интеграция эквайринга
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
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")
|
||||
@@ -0,0 +1,55 @@
|
||||
from decimal import Decimal
|
||||
import uuid
|
||||
from typing import Dict, Any
|
||||
from yookassa import Configuration, Payment as YooPayment
|
||||
from tg_bot.config.settings import settings
|
||||
|
||||
|
||||
class YookassaClient:
|
||||
|
||||
def __init__(self):
|
||||
Configuration.configure(
|
||||
account_id=settings.YOOKASSA_SHOP_ID,
|
||||
secret_key=settings.YOOKASSA_SECRET_KEY
|
||||
)
|
||||
|
||||
async def create_payment(
|
||||
self,
|
||||
amount: Decimal,
|
||||
description: str,
|
||||
user_id: int
|
||||
) -> Dict[str, Any]:
|
||||
try:
|
||||
payment = YooPayment.create({
|
||||
"amount": {
|
||||
"value": f"{amount:.2f}",
|
||||
"currency": "RUB"
|
||||
},
|
||||
"payment_method_data": {
|
||||
"type": "bank_card"
|
||||
},
|
||||
"confirmation": {
|
||||
"type": "redirect",
|
||||
"return_url": settings.YOOKASSA_RETURN_URL
|
||||
},
|
||||
"capture": True,
|
||||
"description": description,
|
||||
"metadata": {
|
||||
"user_id": str(user_id),
|
||||
"telegram_payment": "true"
|
||||
},
|
||||
"save_payment_method": False
|
||||
})
|
||||
return {
|
||||
"id": payment.id,
|
||||
"status": payment.status,
|
||||
"confirmation_url": payment.confirmation.confirmation_url,
|
||||
"amount": payment.amount.value,
|
||||
"description": payment.description,
|
||||
"metadata": payment.metadata
|
||||
}
|
||||
except Exception as e:
|
||||
print(f"Error creating payment: {e}")
|
||||
raise
|
||||
|
||||
yookassa_client = YookassaClient()
|
||||
Reference in New Issue
Block a user