From 6a3b4a6947e067a1b9c0e9350099076527d94ceb Mon Sep 17 00:00:00 2001 From: machka-pasla Date: Wed, 3 Sep 2025 10:12:15 +0300 Subject: [PATCH] Safely extract and serialize payment method details in YooKassa webhook handling - Enhanced the yookassa_webhook_route to safely extract payment method details, including card information, from the payment notification. - Implemented error handling to log exceptions during serialization, improving reliability and debugging capabilities. - Updated the payment processing dictionary to use the newly structured payment method data. --- bot/handlers/user/payment.py | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/bot/handlers/user/payment.py b/bot/handlers/user/payment.py index 1d6c00a..ddee8f0 100644 --- a/bot/handlers/user/payment.py +++ b/bot/handlers/user/payment.py @@ -328,6 +328,33 @@ async def yookassa_webhook_route(request: web.Request): ) return web.Response(status=200, text="ok_error_no_metadata") + # Safely extract payment_method details (SDK objects may not have to_dict) + pm_obj = getattr(payment_data_from_notification, 'payment_method', None) + pm_dict = None + if pm_obj is not None: + try: + card_obj = getattr(pm_obj, 'card', None) + pm_dict = { + "id": getattr(pm_obj, 'id', None), + "type": getattr(pm_obj, 'type', None), + "saved": bool(getattr(pm_obj, 'saved', False)), + "title": getattr(pm_obj, 'title', None), + "card": ( + { + "first6": getattr(card_obj, 'first6', None), + "last4": getattr(card_obj, 'last4', None), + "expiry_month": getattr(card_obj, 'expiry_month', None), + "expiry_year": getattr(card_obj, 'expiry_year', None), + "card_type": getattr(card_obj, 'card_type', None), + } + if card_obj is not None + else None + ), + } + except Exception: + logging.exception("Failed to serialize YooKassa payment_method from webhook") + pm_dict = None + payment_dict_for_processing = { "id": str(payment_data_from_notification.id), @@ -344,8 +371,7 @@ async def yookassa_webhook_route(request: web.Request): "description": str(payment_data_from_notification.description) if payment_data_from_notification.description else None, - "payment_method": payment_data_from_notification.payment_method.to_dict() - if getattr(payment_data_from_notification, 'payment_method', None) else None, + "payment_method": pm_dict, } async with payment_processing_lock: