Add files via upload

This commit is contained in:
Egor
2026-01-17 01:18:02 +03:00
committed by GitHub
parent 1b4758cdbf
commit 5fcc202542
3 changed files with 27 additions and 14 deletions

View File

@@ -6,7 +6,7 @@ from typing import Any, Dict, Optional
from aiohttp import web
from app.config import settings
from app.database.database import get_db
from app.database.database import AsyncSessionLocal
from app.external.heleket import HeleketService
from app.services.payment_service import PaymentService
@@ -33,8 +33,14 @@ class HeleketWebhookHandler:
return web.json_response({"status": "error", "reason": "invalid_signature"}, status=401)
processed: Optional[bool] = None
async for db in get_db():
processed = await self.payment_service.process_heleket_webhook(db, payload)
async with AsyncSessionLocal() as db:
try:
processed = await self.payment_service.process_heleket_webhook(db, payload)
await db.commit()
except Exception as e:
logger.error(f"Ошибка обработки Heleket webhook: {e}")
await db.rollback()
return web.json_response({"status": "error", "reason": "internal_error"}, status=500)
if processed:
return web.json_response({"status": "ok"}, status=200)

View File

@@ -14,7 +14,7 @@ from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
from app.config import settings
from app.database.database import get_db
from app.database.database import AsyncSessionLocal
from app.services.payment_service import PaymentService
logger = logging.getLogger(__name__)
@@ -170,11 +170,14 @@ class WataWebhookHandler:
)
processed: Optional[bool] = None
async for db in get_db():
processed = await self.payment_service.process_wata_webhook(db, payload)
# Allow the generator to finish naturally so it can commit/rollback.
# get_db() yields only once, so exiting the loop body without breaking
# triggers the generator cleanup logic on the next iteration attempt.
async with AsyncSessionLocal() as db:
try:
processed = await self.payment_service.process_wata_webhook(db, payload)
await db.commit()
except Exception as e:
logger.error(f"Ошибка обработки WATA webhook: {e}")
await db.rollback()
return web.json_response({"status": "error", "reason": "internal_error"}, status=500)
if processed is None:
logger.error("Не удалось обработать WATA webhook: нет сессии БД")

View File

@@ -15,7 +15,7 @@ from typing import Iterable, Optional, Dict, Any, List, Union, Tuple, TYPE_CHECK
from aiohttp import web
from app.config import settings
from app.database.database import get_db
from app.database.database import AsyncSessionLocal
if TYPE_CHECKING:
from app.services.payment_service import PaymentService
@@ -273,7 +273,7 @@ class YooKassaWebhookHandler:
logger.info(f" Игнорируем событие YooKassa: {event_type}")
return web.Response(status=200, text="OK")
async for db in get_db():
async with AsyncSessionLocal() as db:
try:
# Проверяем, не обрабатывается ли этот платеж уже (защита от дублирования)
from app.database.models import PaymentMethod
@@ -285,18 +285,22 @@ class YooKassaWebhookHandler:
if existing_transaction and event_type == "payment.succeeded":
logger.info(f" Платеж YooKassa {yookassa_payment_id} уже был обработан. Пропускаем дублирующий вебхук.")
return web.Response(status=200, text="OK")
success = await self.payment_service.process_yookassa_webhook(db, webhook_data)
if success:
await db.commit()
logger.info(f"✅ Успешно обработан webhook YooKassa: {event_type} для платежа {yookassa_payment_id}")
return web.Response(status=200, text="OK")
else:
await db.rollback()
logger.error(f"❌ Ошибка обработки webhook YooKassa: {event_type} для платежа {yookassa_payment_id}")
return web.Response(status=500, text="Processing error")
finally:
await db.close()
except Exception as e:
await db.rollback()
logger.error(f"❌ Ошибка обработки webhook YooKassa: {e}", exc_info=True)
return web.Response(status=500, text="Processing error")
except Exception as e:
logger.error(f"❌ Критическая ошибка обработки webhook YooKassa: {e}", exc_info=True)