GoPay
This commit is contained in:
374
backend/thirdparty/gopay/views.py
vendored
374
backend/thirdparty/gopay/views.py
vendored
@@ -1,233 +1,187 @@
|
||||
from django.shortcuts import render
|
||||
from typing import Optional
|
||||
|
||||
from django.shortcuts import get_object_or_404
|
||||
from django.conf import settings
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
|
||||
# Create your views here.
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework import status, permissions, serializers
|
||||
|
||||
import gopay
|
||||
from gopay.enums import TokenScope, Language
|
||||
import os
|
||||
from drf_spectacular.utils import extend_schema, OpenApiResponse, OpenApiExample, OpenApiParameter
|
||||
from .serializers import (
|
||||
GoPayCreatePaymentRequestSerializer,
|
||||
GoPayPaymentCreatedResponseSerializer,
|
||||
GoPayStatusResponseSerializer,
|
||||
GoPayRefundRequestSerializer,
|
||||
GoPayCaptureRequestSerializer,
|
||||
GoPayCreateRecurrenceRequestSerializer,
|
||||
)
|
||||
|
||||
from .models import GoPayPayment
|
||||
|
||||
|
||||
class GoPayClientMixin:
|
||||
"""Shared helpers for configuring GoPay client and formatting responses."""
|
||||
def get_gopay_client(self):
|
||||
gateway_url = os.getenv("GOPAY_GATEWAY_URL", "https://gw.sandbox.gopay.com/api")
|
||||
return gopay.payments({
|
||||
"goid": os.getenv("GOPAY_GOID"),
|
||||
"client_id": os.getenv("GOPAY_CLIENT_ID"),
|
||||
"client_secret": os.getenv("GOPAY_CLIENT_SECRET"),
|
||||
"gateway_url": gateway_url,
|
||||
"scope": TokenScope.ALL,
|
||||
"language": Language.CZECH,
|
||||
})
|
||||
|
||||
def _to_response(self, sdk_response):
|
||||
# The GoPay SDK returns a response object with has_succeed(), json, errors, status_code
|
||||
try:
|
||||
if hasattr(sdk_response, "has_succeed") and sdk_response.has_succeed():
|
||||
return Response(getattr(sdk_response, "json", {}))
|
||||
status = getattr(sdk_response, "status_code", 400)
|
||||
errors = getattr(sdk_response, "errors", None)
|
||||
if errors is None and hasattr(sdk_response, "json"):
|
||||
errors = sdk_response.json
|
||||
if errors is None:
|
||||
errors = {"detail": "GoPay request failed"}
|
||||
return Response({"errors": errors}, status=status)
|
||||
except Exception as e:
|
||||
return Response({"errors": str(e)}, status=500)
|
||||
def _gopay_api():
|
||||
# SDK handles token internally; credentials from settings/env
|
||||
return gopay.payments({
|
||||
"goid": settings.GOPAY_GOID,
|
||||
"client_id": settings.GOPAY_CLIENT_ID,
|
||||
"client_secret": settings.GOPAY_CLIENT_SECRET,
|
||||
"gateway_url": getattr(settings, 'GOPAY_GATEWAY_URL', 'https://gw.sandbox.gopay.com/api'),
|
||||
})
|
||||
|
||||
|
||||
class GoPayPaymentView(GoPayClientMixin, APIView):
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
@extend_schema(
|
||||
tags=["GoPay"],
|
||||
summary="Create GoPay payment",
|
||||
description="Creates a GoPay payment and returns gateway URL and payment info.",
|
||||
request=GoPayCreatePaymentRequestSerializer,
|
||||
responses={
|
||||
200: OpenApiResponse(response=GoPayPaymentCreatedResponseSerializer, description="Payment created"),
|
||||
400: OpenApiResponse(description="Validation error or SDK error"),
|
||||
},
|
||||
examples=[
|
||||
OpenApiExample(
|
||||
"Create payment",
|
||||
value={
|
||||
"amount": 123.45,
|
||||
"currency": "CZK",
|
||||
"order_number": "order-001",
|
||||
"order_description": "Example GoPay payment",
|
||||
"return_url": "https://yourfrontend.com/success",
|
||||
"notify_url": "https://yourbackend.com/gopay/notify",
|
||||
"preauthorize": False,
|
||||
},
|
||||
request_only=True,
|
||||
)
|
||||
]
|
||||
)
|
||||
def post(self, request):
|
||||
amount = request.data.get("amount")
|
||||
currency = request.data.get("currency", "CZK")
|
||||
order_number = request.data.get("order_number", "order-001")
|
||||
order_description = request.data.get("order_description", "Example GoPay payment")
|
||||
return_url = request.data.get("return_url", "https://yourfrontend.com/success")
|
||||
notify_url = request.data.get("notify_url", "https://yourbackend.com/gopay/notify")
|
||||
preauthorize = bool(request.data.get("preauthorize", False))
|
||||
|
||||
if not amount:
|
||||
return Response({"error": "Amount is required"}, status=400)
|
||||
|
||||
payments = self.get_gopay_client()
|
||||
|
||||
payment_data = {
|
||||
"payer": {
|
||||
"allowed_payment_instruments": ["PAYMENT_CARD"],
|
||||
"default_payment_instrument": "PAYMENT_CARD",
|
||||
"allowed_swifts": ["FIOB"],
|
||||
"contact": {
|
||||
"first_name": getattr(request.user, "first_name", ""),
|
||||
"last_name": getattr(request.user, "last_name", ""),
|
||||
"email": getattr(request.user, "email", ""),
|
||||
},
|
||||
},
|
||||
"amount": int(float(amount) * 100), # GoPay expects amount in cents
|
||||
"currency": currency,
|
||||
"order_number": order_number,
|
||||
"order_description": order_description,
|
||||
"items": [
|
||||
{"name": "Example Item", "amount": int(float(amount) * 100)}
|
||||
],
|
||||
"callback": {"return_url": return_url, "notify_url": notify_url},
|
||||
"preauthorize": preauthorize,
|
||||
}
|
||||
|
||||
resp = payments.create_payment(payment_data)
|
||||
return self._to_response(resp)
|
||||
def _as_dict(resp):
|
||||
if resp is None:
|
||||
return None
|
||||
if hasattr(resp, "json") and not callable(getattr(resp, "json")):
|
||||
return resp.json
|
||||
if hasattr(resp, "json") and callable(getattr(resp, "json")):
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
pass
|
||||
if isinstance(resp, dict):
|
||||
return resp
|
||||
try:
|
||||
return dict(resp)
|
||||
except Exception:
|
||||
return {"raw": str(resp)}
|
||||
|
||||
|
||||
class GoPayPaymentStatusView(GoPayClientMixin, APIView):
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
@extend_schema(
|
||||
tags=["GoPay"],
|
||||
summary="Get GoPay payment status",
|
||||
parameters=[OpenApiParameter(name="payment_id", required=True, type=int, location=OpenApiParameter.PATH)],
|
||||
responses={200: OpenApiResponse(response=GoPayStatusResponseSerializer, description="Payment status")},
|
||||
)
|
||||
def get(self, request, payment_id: int):
|
||||
payments = self.get_gopay_client()
|
||||
resp = payments.get_status(payment_id)
|
||||
return self._to_response(resp)
|
||||
def _map_status(provider_state: Optional[str]) -> str:
|
||||
if not provider_state:
|
||||
return 'UNKNOWN'
|
||||
state = provider_state.upper()
|
||||
if state == 'PAID':
|
||||
return 'PAID'
|
||||
if state in ('AUTHORIZED',):
|
||||
return 'AUTHORIZED'
|
||||
if state in ('PAYMENT_METHOD_CHOSEN',):
|
||||
return 'PAYMENT_METHOD_CHOSEN'
|
||||
if state in ('CREATED', 'CREATED_WITH_PAYMENT', 'PENDING'):
|
||||
return 'CREATED'
|
||||
if state in ('CANCELED', 'CANCELLED'):
|
||||
return 'CANCELED'
|
||||
if state in ('TIMEOUTED',):
|
||||
return 'TIMEOUTED'
|
||||
if state in ('REFUNDED',):
|
||||
return 'REFUNDED'
|
||||
if state in ('PARTIALLY_REFUNDED',):
|
||||
return 'PARTIALLY_REFUNDED'
|
||||
if state in ('FAILED', 'DECLINED'):
|
||||
return 'FAILED'
|
||||
return state
|
||||
|
||||
|
||||
class GoPayRefundPaymentView(GoPayClientMixin, APIView):
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
@extend_schema(
|
||||
tags=["GoPay"],
|
||||
summary="Refund GoPay payment",
|
||||
parameters=[OpenApiParameter(name="payment_id", required=True, type=int, location=OpenApiParameter.PATH)],
|
||||
request=GoPayRefundRequestSerializer,
|
||||
responses={200: OpenApiResponse(description="Refund processed")},
|
||||
)
|
||||
def post(self, request, payment_id: int):
|
||||
amount = request.data.get("amount") # optional for full refund
|
||||
payments = self.get_gopay_client()
|
||||
if amount is None or amount == "":
|
||||
# Full refund
|
||||
resp = payments.refund_payment(payment_id)
|
||||
else:
|
||||
resp = payments.refund_payment(payment_id, int(float(amount) * 100))
|
||||
return self._to_response(resp)
|
||||
# --- Serializers kept here (small and read-only) ---
|
||||
class GoPayRefundROSerializer(serializers.Serializer):
|
||||
id = serializers.IntegerField()
|
||||
amount_cents = serializers.IntegerField(allow_null=True)
|
||||
reason = serializers.CharField(allow_null=True, allow_blank=True)
|
||||
provider_refund_id = serializers.CharField(allow_null=True)
|
||||
created_at = serializers.DateTimeField()
|
||||
|
||||
|
||||
class GoPayCaptureAuthorizationView(GoPayClientMixin, APIView):
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
@extend_schema(
|
||||
tags=["GoPay"],
|
||||
summary="Capture GoPay authorization",
|
||||
parameters=[OpenApiParameter(name="payment_id", required=True, type=int, location=OpenApiParameter.PATH)],
|
||||
request=GoPayCaptureRequestSerializer,
|
||||
responses={200: OpenApiResponse(description="Capture processed")},
|
||||
)
|
||||
def post(self, request, payment_id: int):
|
||||
amount = request.data.get("amount") # optional for partial capture
|
||||
payments = self.get_gopay_client()
|
||||
if amount is None or amount == "":
|
||||
resp = payments.capture_authorization(payment_id)
|
||||
else:
|
||||
resp = payments.capture_authorization(payment_id, int(float(amount) * 100))
|
||||
return self._to_response(resp)
|
||||
class GoPayPaymentROSerializer(serializers.Serializer):
|
||||
id = serializers.IntegerField()
|
||||
order = serializers.IntegerField(source='order_id', allow_null=True)
|
||||
amount_cents = serializers.IntegerField()
|
||||
currency = serializers.CharField()
|
||||
status = serializers.CharField()
|
||||
refunded_amount_cents = serializers.IntegerField()
|
||||
gw_url = serializers.URLField(allow_null=True)
|
||||
provider_payment_id = serializers.IntegerField(allow_null=True)
|
||||
created_at = serializers.DateTimeField()
|
||||
updated_at = serializers.DateTimeField()
|
||||
|
||||
|
||||
class GoPayVoidAuthorizationView(GoPayClientMixin, APIView):
|
||||
permission_classes = [IsAuthenticated]
|
||||
class PaymentStatusView(APIView):
|
||||
"""
|
||||
GET /api/payments/payment/{id}
|
||||
- Refresh status from GoPay (if provider_payment_id present).
|
||||
- Return current local payment record (read-only).
|
||||
"""
|
||||
permission_classes = [permissions.IsAuthenticated]
|
||||
|
||||
@extend_schema(
|
||||
tags=["GoPay"],
|
||||
summary="Void GoPay authorization",
|
||||
parameters=[OpenApiParameter(name="payment_id", required=True, type=int, location=OpenApiParameter.PATH)],
|
||||
responses={200: OpenApiResponse(description="Authorization voided")},
|
||||
)
|
||||
def post(self, request, payment_id: int):
|
||||
payments = self.get_gopay_client()
|
||||
resp = payments.void_authorization(payment_id)
|
||||
return self._to_response(resp)
|
||||
def get(self, request, pk: int):
|
||||
payment = get_object_or_404(GoPayPayment, pk=pk)
|
||||
|
||||
if payment.provider_payment_id:
|
||||
api = _gopay_api()
|
||||
resp = api.get_status(payment.provider_payment_id)
|
||||
if getattr(resp, "success", False):
|
||||
data = getattr(resp, "json", None)
|
||||
payment.status = _map_status(data.get('state'))
|
||||
payment.raw_last_status = data
|
||||
payment.save(update_fields=['status', 'raw_last_status', 'updated_at'])
|
||||
else:
|
||||
err = getattr(resp, "json", None) or {"status_code": getattr(resp, "status_code", None), "raw": getattr(resp, "raw_body", None)}
|
||||
return Response({'detail': 'Failed to fetch status', 'error': err}, status=status.HTTP_502_BAD_GATEWAY)
|
||||
|
||||
serialized = GoPayPaymentROSerializer(payment)
|
||||
return Response(serialized.data)
|
||||
|
||||
|
||||
class GoPayCreateRecurrenceView(GoPayClientMixin, APIView):
|
||||
permission_classes = [IsAuthenticated]
|
||||
class PaymentRefundListView(APIView):
|
||||
"""
|
||||
GET /api/payments/payment/{id}/refunds
|
||||
- List local refund records for a payment (read-only).
|
||||
"""
|
||||
permission_classes = [permissions.IsAuthenticated]
|
||||
|
||||
@extend_schema(
|
||||
tags=["GoPay"],
|
||||
summary="Create GoPay recurrence",
|
||||
parameters=[OpenApiParameter(name="payment_id", required=True, type=int, location=OpenApiParameter.PATH)],
|
||||
request=GoPayCreateRecurrenceRequestSerializer,
|
||||
responses={200: OpenApiResponse(description="Recurrence created")},
|
||||
)
|
||||
def post(self, request, payment_id: int):
|
||||
amount = request.data.get("amount")
|
||||
currency = request.data.get("currency", "CZK")
|
||||
order_number = request.data.get("order_number", "recur-001")
|
||||
order_description = request.data.get("order_description", "Recurring payment")
|
||||
if not amount:
|
||||
return Response({"error": "Amount is required"}, status=400)
|
||||
payments = self.get_gopay_client()
|
||||
recurrence_payload = {
|
||||
"amount": int(float(amount) * 100),
|
||||
"currency": currency,
|
||||
"order_number": order_number,
|
||||
"order_description": order_description,
|
||||
}
|
||||
resp = payments.create_recurrence(payment_id, recurrence_payload)
|
||||
return self._to_response(resp)
|
||||
def get(self, request, pk: int):
|
||||
payment = get_object_or_404(GoPayPayment, pk=pk)
|
||||
refunds = payment.refunds.all().values(
|
||||
'id', 'amount_cents', 'reason', 'provider_refund_id', 'created_at'
|
||||
)
|
||||
ser = GoPayRefundROSerializer(refunds, many=True)
|
||||
return Response(ser.data)
|
||||
|
||||
|
||||
class GoPayPaymentInstrumentsView(GoPayClientMixin, APIView):
|
||||
permission_classes = [IsAuthenticated]
|
||||
@method_decorator(csrf_exempt, name='dispatch')
|
||||
class GoPayWebhookView(APIView):
|
||||
"""
|
||||
GET /api/payments/gopay/webhook?id=<provider_payment_id>
|
||||
- Called by GoPay (HTTP GET with query params) on payment state change.
|
||||
- We verify by fetching status via GoPay SDK and persist it locally.
|
||||
"""
|
||||
permission_classes = [permissions.AllowAny]
|
||||
|
||||
@extend_schema(
|
||||
tags=["GoPay"],
|
||||
summary="Get GoPay payment instruments",
|
||||
parameters=[OpenApiParameter(name="currency", required=False, type=str, location=OpenApiParameter.QUERY)],
|
||||
responses={200: OpenApiResponse(description="Available payment instruments returned")},
|
||||
)
|
||||
def get(self, request):
|
||||
currency = request.query_params.get("currency", "CZK")
|
||||
goid = os.getenv("GOPAY_GOID")
|
||||
if not goid:
|
||||
return Response({"error": "GOPAY_GOID is not configured"}, status=500)
|
||||
payments = self.get_gopay_client()
|
||||
resp = payments.get_payment_instruments(goid, currency)
|
||||
return self._to_response(resp)
|
||||
def get(self, request):
|
||||
provider_id = request.GET.get("id") or request.GET.get("payment_id")
|
||||
if not provider_id:
|
||||
return Response({"detail": "Missing payment id"}, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
try:
|
||||
provider_id_int = int(provider_id)
|
||||
except Exception:
|
||||
provider_id_int = provider_id # fallback
|
||||
|
||||
api = _gopay_api()
|
||||
resp = api.get_status(provider_id_int)
|
||||
if not getattr(resp, "success", False):
|
||||
err = getattr(resp, "json", None) or {"status_code": getattr(resp, "status_code", None), "raw": getattr(resp, "raw_body", None)}
|
||||
return Response({"detail": "Failed to verify status with GoPay", "error": err}, status=status.HTTP_502_BAD_GATEWAY)
|
||||
|
||||
data = getattr(resp, "json", None)
|
||||
state = data.get("state")
|
||||
|
||||
# Find local payment by provider id, fallback to order_number from response
|
||||
payment = None
|
||||
try:
|
||||
payment = GoPayPayment.objects.get(provider_payment_id=provider_id_int)
|
||||
except GoPayPayment.DoesNotExist:
|
||||
order_number = data.get("order_number")
|
||||
if order_number:
|
||||
try:
|
||||
payment = GoPayPayment.objects.get(pk=int(order_number))
|
||||
except Exception:
|
||||
payment = None
|
||||
|
||||
if not payment:
|
||||
return Response({"detail": "Payment not found locally", "provider_id": provider_id_int}, status=status.HTTP_202_ACCEPTED)
|
||||
|
||||
payment.status = _map_status(state)
|
||||
payment.raw_last_status = data
|
||||
payment.save(update_fields=["status", "raw_last_status", "updated_at"])
|
||||
|
||||
return Response({"ok": True})
|
||||
|
||||
# Implementation notes:
|
||||
# - GoPay notification is an HTTP GET to notification_url with ?id=...
|
||||
# - Always verify the state by calling get_status(id); never trust inbound payload alone.
|
||||
# - Amounts are kept in minor units (cents). States covered: CREATED, PAYMENT_METHOD_CHOSEN, AUTHORIZED, PAID, CANCELED, TIMEOUTED, PARTIALLY_REFUNDED, REFUNDED.
|
||||
|
||||
Reference in New Issue
Block a user