from drf_spectacular.utils import ( OpenApiExample, extend_schema, inline_serializer, ) from rest_framework import serializers from rest_framework.permissions import AllowAny from rest_framework.response import Response from rest_framework.views import APIView from apps.common.schema import error_responses from .serializers import PaymentWebhookSerializer from .services import handle_yookassa_webhook TAGS = ["Платежи"] class YooKassaWebhookView(APIView): """Receives ЮKassa notifications. TODO: verify the source IP / signature before applying the event. """ permission_classes = [AllowAny] authentication_classes: list = [] serializer_class = PaymentWebhookSerializer @extend_schema( tags=TAGS, summary="Уведомление ЮKassa", description=( "Служебный метод: его вызывает платёжный провайдер, а не клиент. " "Применяет событие к платежу и заказу.\n\n" "Поддерживаемые события: `payment.succeeded`, `payment.canceled`, " "`refund.succeeded`. После успешной оплаты статус оплаты заказа " "пересчитывается по сумме всех успешных платежей — заказ может быть " "оплачен частично.\n\n" "Неизвестный платёж не считается ошибкой: ответ `200` с `detail: ignored`, " "чтобы провайдер не повторял доставку бесконечно." ), request=PaymentWebhookSerializer, responses={ 200: inline_serializer( name="PaymentWebhookResponse", fields={ "detail": serializers.CharField( help_text="`ok` — событие применено, `ignored` — платёж не найден." ) }, ), **error_responses(400), }, examples=[ OpenApiExample( "Оплата прошла", value={ "event": "payment.succeeded", "object": { "id": "2f1a9c74-000f-5000-9000-1a2b3c4d5e6f", "status": "succeeded", "amount": {"value": "21583.00", "currency": "RUB"}, }, }, request_only=True, ), OpenApiExample( "Событие применено", value={"detail": "ok"}, response_only=True, ), ], ) def post(self, request): payment = handle_yookassa_webhook(request.data) if payment is None: return Response({"detail": "ignored"}) return Response({"detail": "ok"})