This commit is contained in:
2025-11-05 02:05:35 +01:00
parent a324a9cf49
commit de5f54f4bc
8 changed files with 317 additions and 434 deletions

View File

@@ -1,206 +1,60 @@
from django.db import models
from __future__ import annotations
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
import gopay # GoPay official SDK
def _gopay_api():
"""
Instantiate the GoPay SDK; SDK manages access token internally.
https://doc.gopay.cz/
"""
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"),
})
def _as_dict(resp):
"""
Try to normalize SDK response to a dict for persistence.
The SDK usually exposes `.json` (attr or method).
"""
if resp is None:
return None
# attr style
if hasattr(resp, "json") and not callable(getattr(resp, "json")):
return resp.json
# method style
if hasattr(resp, "json") and callable(getattr(resp, "json")):
try:
return resp.json()
except Exception:
pass
# already a dict
if isinstance(resp, dict):
return resp
# best-effort fallback
try:
return dict(resp) # may fail for non-mapping
except Exception:
return {"raw": str(resp)}
from django.db import models
from django.utils import timezone
class GoPayPayment(models.Model):
"""
Local representation of a GoPay payment. Creating this model will create a real payment
at GoPay (via post_save hook) and persist provider identifiers and gateway URL.
Amounts are stored in minor units (cents/haléře).
"""
# Optional link to your Order model
order = models.ForeignKey(
'commerce.Order',
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name='gopay_payments',
# Optional user association
user = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="gopay_payments"
)
# External identifiers and core attributes
gopay_id = models.CharField(max_length=64, unique=True, db_index=True)
order_number = models.CharField(max_length=128, blank=True, default="")
amount = models.BigIntegerField(help_text="Amount in minor units (e.g., CZK in haléř).")
currency = models.CharField(max_length=10)
status = models.CharField(max_length=64, db_index=True, default="")
preauthorized = models.BooleanField(default=False)
captured_amount = models.BigIntegerField(default=0)
# Basic money + currency
amount_cents = models.PositiveBigIntegerField()
currency = models.CharField(max_length=8, default='CZK')
# Raw payloads for traceability
request_payload = models.JSONField(default=dict, blank=True)
response_payload = models.JSONField(default=dict, blank=True)
# Provider identifiers + redirect URL
provider_payment_id = models.BigIntegerField(null=True, blank=True, unique=True)
gw_url = models.URLField(null=True, blank=True)
# Status bookkeeping
status = models.CharField(max_length=64, default='CREATED') # CREATED, PAID, CANCELED, REFUNDED, PARTIALLY_REFUNDED, FAILED
refunded_amount_cents = models.PositiveBigIntegerField(default=0)
# Raw responses for auditing
raw_create_response = models.JSONField(null=True, blank=True)
raw_last_status = models.JSONField(null=True, blank=True)
# Optional text for statements/UX
description = models.CharField(max_length=255, null=True, blank=True)
# Timestamps
created_at = models.DateTimeField(auto_now_add=True)
created_at = models.DateTimeField(default=timezone.now, db_index=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self) -> str:
return f'GoPayPayment#{self.pk} {self.amount_cents} {self.currency} [{self.status}]'
return f"GoPayPayment(id={self.gopay_id}, status={self.status}, amount={self.amount} {self.currency})"
class GoPayRefund(models.Model):
"""
Local representation of a GoPay refund. Creating this model will trigger
a refund call at GoPay (via post_save hook).
If amount_cents is null, a full refund is attempted by provider.
"""
payment = models.ForeignKey(GoPayPayment, on_delete=models.CASCADE, related_name='refunds')
amount_cents = models.PositiveBigIntegerField(null=True, blank=True) # null => full refund
reason = models.CharField(max_length=255, null=True, blank=True)
payment = models.ForeignKey(GoPayPayment, on_delete=models.CASCADE, null=True, blank=True, related_name="refunds")
gopay_refund_id = models.CharField(max_length=64, blank=True, default="")
amount = models.BigIntegerField(help_text="Amount in minor units.")
status = models.CharField(max_length=64, blank=True, default="")
payload = models.JSONField(default=dict, blank=True)
provider_refund_id = models.CharField(max_length=128, null=True, blank=True)
raw_response = models.JSONField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created_at']
created_at = models.DateTimeField(default=timezone.now, db_index=True)
def __str__(self) -> str:
amount = self.amount_cents if self.amount_cents is not None else 'FULL'
return f'GoPayRefund#{self.pk} payment={self.payment_id} amount={amount}'
return f"GoPayRefund(payment={self.payment_id}, amount={self.amount}, status={self.status})"
@receiver(post_save, sender=GoPayPayment)
def create_gopay_payment(sender, instance: GoPayPayment, created: bool, **kwargs):
"""
On first save (creation), create the payment at GoPay.
class GoPaySubscription(models.Model):
parent_payment = models.ForeignKey(GoPayPayment, on_delete=models.CASCADE, related_name="subscriptions")
recurrence_id = models.CharField(max_length=64, blank=True, default="")
status = models.CharField(max_length=64, blank=True, default="")
interval = models.CharField(max_length=64, blank=True, default="")
next_payment_on = models.DateTimeField(null=True, blank=True)
payload = models.JSONField(default=dict, blank=True)
Per docs:
- return_url: user is redirected back with ?id=<payment_id>
- notification_url: GoPay sends HTTP GET with ?id=<payment_id> on state changes
- Always verify state via API get_status(id)
"""
if not created:
return
# Already linked to provider (unlikely on brand-new rows)
if instance.provider_payment_id:
return
canceled = models.BooleanField(default=False)
canceled_at = models.DateTimeField(null=True, blank=True)
api = _gopay_api()
created_at = models.DateTimeField(default=timezone.now, db_index=True)
payload = {
"amount": int(instance.amount_cents), # GoPay expects minor units
"currency": (instance.currency or "CZK").upper(),
"order_number": str(instance.pk),
"order_description": instance.description or (f"Order {instance.order_id}" if instance.order_id else "Payment"),
"lang": "CS",
"callback": {
"return_url": f"{getattr(settings, 'FRONTEND_URL', 'http://localhost:5173')}/payment/return",
# Per docs: GoPay sends HTTP GET notification to this URL with ?id=<payment_id>
"notification_url": getattr(settings, "GOPAY_NOTIFICATION_URL", None),
},
# Optionally add items here if you later extend the model to store them.
}
resp = api.create_payment(payload)
# SDK returns Response object (no exceptions); check success + use .json
if getattr(resp, "success", False):
data = getattr(resp, "json", None)
instance.provider_payment_id = data.get("id")
instance.gw_url = data.get("gw_url")
instance.raw_create_response = data
instance.status = 'CREATED'
instance.save(update_fields=["provider_payment_id", "gw_url", "raw_create_response", "status", "updated_at"])
else:
# Persist error payload and mark as FAILED
err = getattr(resp, "json", None) or {"status_code": getattr(resp, "status_code", None), "raw": getattr(resp, "raw_body", None)}
instance.raw_create_response = {"error": err}
instance.status = "FAILED"
instance.save(update_fields=["raw_create_response", "status", "updated_at"])
@receiver(post_save, sender=GoPayRefund)
def create_gopay_refund(sender, instance: GoPayRefund, created: bool, **kwargs):
"""
On first save (creation), request a refund at GoPay.
- amount_cents None => full refund
- Updates parent payment refunded amount and status.
- Stores raw provider response.
"""
if not created:
return
# If already linked (e.g., imported), skip
if instance.provider_refund_id:
return
payment = instance.payment
if not payment.provider_payment_id:
# Payment was not created at provider; record as failed in raw_response
instance.raw_response = {"error": "Missing provider payment id"}
instance.save(update_fields=["raw_response"])
return
api = _gopay_api()
# Compute amount to refund. If not provided -> refund remaining (full if none refunded yet).
refund_amount = instance.amount_cents
if refund_amount is None:
remaining = max(0, int(payment.amount_cents) - int(payment.refunded_amount_cents))
refund_amount = remaining
resp = api.refund_payment(payment.provider_payment_id, int(refund_amount))
if getattr(resp, "success", False):
data = getattr(resp, "json", None)
instance.provider_refund_id = str(data.get("id")) if data and data.get("id") is not None else None
instance.raw_response = data
instance.save(update_fields=["provider_refund_id", "raw_response"])
# Update parent payment bookkeeping against the remaining balance
new_total = min(payment.amount_cents, payment.refunded_amount_cents + int(refund_amount))
payment.refunded_amount_cents = new_total
payment.status = "REFUNDED" if new_total >= payment.amount_cents else "PARTIALLY_REFUNDED"
payment.save(update_fields=["refunded_amount_cents", "status", "updated_at"])
else:
err = getattr(resp, "json", None) or {"status_code": getattr(resp, "status_code", None), "raw": getattr(resp, "raw_body", None)}
instance.raw_response = {"error": err}
instance.save(update_fields=["raw_response"])
def __str__(self) -> str:
return f"GoPaySubscription(parent={self.parent_payment_id}, status={self.status})"