From 6365624e25e551dde38aeff6150d71f2398d7b64 Mon Sep 17 00:00:00 2001 From: adevopg <133045315+adevopg@users.noreply.github.com> Date: Sun, 2 Mar 2025 17:37:33 +0100 Subject: [PATCH] Implementacion Inicial SumUP --- home/admin.py | 9 +++- ...er_guildrenamesettings_options_and_more.py | 32 +++++++++++++ home/models.py | 13 +++++- home/pagos_sumup.py | 45 ++++++++++++++++++ home/templates/account/pago_sumup.html | 9 ++++ home/templates/partials/pago_sumup.html | 32 +++++++++++++ home/urls.py | 2 + home/views.py | 46 ++++++++++++++++++- novawow/settings.py | 8 ++++ 9 files changed, 193 insertions(+), 3 deletions(-) create mode 100644 home/migrations/0011_pedido_alter_guildrenamesettings_options_and_more.py create mode 100644 home/pagos_sumup.py create mode 100644 home/templates/account/pago_sumup.html create mode 100644 home/templates/partials/pago_sumup.html diff --git a/home/admin.py b/home/admin.py index 0c494b7..d2441fe 100644 --- a/home/admin.py +++ b/home/admin.py @@ -4,7 +4,7 @@ from django import forms from .models import ( Noticia, ClienteCategoria, SistemaOperativo, ServerSelection, RecruitAFriend, DownloadClientPage, ContentCreator, RecruitReward, GuildRenameSettings, VoteSite, RenamePrice, CustomizePrice, ChangeRacePrice, ChangeFactionPrice, LevelUpPrice, GoldPrice, TransferPrice, MaintenanceMode, - StripeLog + StripeLog, Pedido ) from django.db import connections import logging @@ -22,6 +22,13 @@ class StripeLogAdmin(admin.ModelAdmin): list_filter = ('mode', 'timestamp') # Filtros por campo en la parte lateral search_fields = ('username', 'product_name', 'session_id', 'email', 'stripe_ip') # Ahora incluye 'stripe_ip' en la búsqueda ordering = ('-timestamp',) # Ordenar por timestamp descendentes + +@admin.register(Pedido) +class PedidoLogAdmin(admin.ModelAdmin): # Ahora esta es una clase de admin + list_display = ('transaction_id', 'email_cliente', 'estado', 'monto') # Campos que se mostrarán en el panel + search_fields = ('transaction_id', 'email_cliente') # Habilita búsqueda por ID y email + list_filter = ('estado',) # Filtro por estado de pago + @admin.register(ChangeFactionPrice) class ChangeFactionPriceAdmin(admin.ModelAdmin): diff --git a/home/migrations/0011_pedido_alter_guildrenamesettings_options_and_more.py b/home/migrations/0011_pedido_alter_guildrenamesettings_options_and_more.py new file mode 100644 index 0000000..cbfec1c --- /dev/null +++ b/home/migrations/0011_pedido_alter_guildrenamesettings_options_and_more.py @@ -0,0 +1,32 @@ +# Generated by Django 5.1.4 on 2025-03-02 16:23 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('home', '0010_loginattempt'), + ] + + operations = [ + migrations.CreateModel( + name='Pedido', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('transaction_id', models.CharField(blank=True, max_length=100, null=True, unique=True)), + ('email_cliente', models.EmailField(max_length=254)), + ('estado', models.CharField(default='Pendiente', max_length=20)), + ('monto', models.DecimalField(decimal_places=2, max_digits=10)), + ], + ), + migrations.AlterModelOptions( + name='guildrenamesettings', + options={}, + ), + migrations.AlterField( + model_name='guildrenamesettings', + name='cost', + field=models.DecimalField(decimal_places=2, default=10, help_text='Costo en euros para renombrar una hermandad.', max_digits=10), + ), + ] diff --git a/home/models.py b/home/models.py index f370fac..732bc5d 100644 --- a/home/models.py +++ b/home/models.py @@ -293,4 +293,15 @@ class StripeLog(models.Model): timestamp = models.DateTimeField(auto_now_add=True) # Fecha y hora def __str__(self): - return f"{self.username} compró {self.product_name} por {self.amount}€ ({self.mode})" \ No newline at end of file + return f"{self.username} compró {self.product_name} por {self.amount}€ ({self.mode})" + + +class Pedido(models.Model): + transaction_id = models.CharField(max_length=100, unique=True, null=True, blank=True) + email_cliente = models.EmailField() + estado = models.CharField(max_length=20, default="Pendiente") + monto = models.DecimalField(max_digits=10, decimal_places=2) + + def __str__(self): + return f"Pedido {self.transaction_id} - {self.estado}" + \ No newline at end of file diff --git a/home/pagos_sumup.py b/home/pagos_sumup.py new file mode 100644 index 0000000..94cd753 --- /dev/null +++ b/home/pagos_sumup.py @@ -0,0 +1,45 @@ +from django.conf import settings +import requests + + +SUMUP_CLIENT_ID = settings.SUMUP_CLIENT_ID +SUMUP_CLIENT_SECRET = settings.SUMUP_CLIENT_SECRET +SUMUP_EMAIL = settings.SUMUP_MERCHANT_EMAIL + +def obtener_token(): + """Obtiene un access token de SumUp""" + url = "https://api.sumup.com/token" + data = { + "grant_type": "client_credentials", + "client_id": SUMUP_CLIENT_ID, + "client_secret": SUMUP_CLIENT_SECRET + } + headers = {"Content-Type": "application/x-www-form-urlencoded"} + + response = requests.post(url, headers=headers, data=data) + if response.status_code == 200: + return response.json().get("access_token") + else: + raise Exception(f"Error al obtener token: {response.json()}") + +def crear_checkout(monto, moneda="EUR"): + """Crea un pago en SumUp y devuelve el checkout_id""" + access_token = obtener_token() + url = "https://api.sumup.com/v0.1/checkouts" + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json" + } + data = { + "checkout_reference": "pedido-12345", + "amount": monto, + "currency": moneda, + "pay_to_email": SUMUP_EMAIL, + "description": "Pago de prueba" + } + + response = requests.post(url, headers=headers, json=data) + if response.status_code == 201: + return response.json().get("id") # checkout_id + else: + raise Exception(f"Error al crear checkout: {response.json()}") diff --git a/home/templates/account/pago_sumup.html b/home/templates/account/pago_sumup.html new file mode 100644 index 0000000..4aff5c4 --- /dev/null +++ b/home/templates/account/pago_sumup.html @@ -0,0 +1,9 @@ + + + {% include 'partials/head.html' %} + {% include 'partials/header.html' %} + {% include 'partials/video.html' %} + {% include 'partials/pago_sumup.html' %} + {% include 'partials/social.html' %} + {% include 'partials/footer.html' %} + {% include 'partials/final.html' %} \ No newline at end of file diff --git a/home/templates/partials/pago_sumup.html b/home/templates/partials/pago_sumup.html new file mode 100644 index 0000000..d409e8f --- /dev/null +++ b/home/templates/partials/pago_sumup.html @@ -0,0 +1,32 @@ + + +
+ +Error: {{ error }}
+ {% else %} + + + + {% endif %} + + diff --git a/home/urls.py b/home/urls.py index faf05f6..711a426 100644 --- a/home/urls.py +++ b/home/urls.py @@ -75,6 +75,8 @@ urlpatterns = [ path("webhook/stripe/", stripe_webhook, name="stripe-webhook"), path('guild-success/', views.guild_rename_success_view, name='guild-success'), path('guild-cancel/', views.guild_rename_cancel_view, name='guild-cancel'), + path("pagar-sumup/", views.pagar_sumup, name="pagar_sumup"), + path("sumup-webhook/", views.sumup_webhook, name="sumup_webhook"), ] diff --git a/home/views.py b/home/views.py index 44bb2ad..7719538 100644 --- a/home/views.py +++ b/home/views.py @@ -5,10 +5,11 @@ from django.http import HttpResponse, JsonResponse from django.db import connections from django.contrib import messages from django.contrib.auth import logout +from .pagos_sumup import crear_checkout from django import forms import stripe from .pagos_stripe import create_checkout_session -from .models import Noticia, ClienteCategoria, ServerSelection, RecruitAFriend, DownloadClientPage, ContentCreator, RecruitReward, ClaimedReward, AccountActivation, SecurityToken, GuildRenameSettings, VoteSite, VoteLog, HomeApiPoints, UnstuckHistory, ReviveHistory, RenamePrice, CustomizePrice, ChangeRacePrice, ChangeFactionPrice, LevelUpPrice, GoldPrice, TransferPrice, Category, Item, StripeLog, LoginAttempt +from .models import Noticia, ClienteCategoria, ServerSelection, RecruitAFriend, DownloadClientPage, ContentCreator, RecruitReward, ClaimedReward, AccountActivation, SecurityToken, GuildRenameSettings, VoteSite, VoteLog, HomeApiPoints, UnstuckHistory, ReviveHistory, RenamePrice, CustomizePrice, ChangeRacePrice, ChangeFactionPrice, LevelUpPrice, GoldPrice, TransferPrice, Category, Item, StripeLog, LoginAttempt, Pedido from django.views.decorators.csrf import csrf_exempt from datetime import datetime, timedelta @@ -2895,3 +2896,46 @@ def novawow_players_view(request): 'classes_data': classes_data, 'first_realm_data': first_realm_data }) + + +def pagar_sumup(request): + """Genera un pago de prueba y lo muestra en el widget""" + try: + checkout_id = crear_checkout(10.00) # Pago de 10 EUR + pedido = Pedido.objects.create(email_cliente="cliente@example.com", monto=10.00) + return render(request, "account/pago_sumup.html", {"checkout_id": checkout_id, "pedido": pedido}) + except Exception as e: + return render(request, "account/pago_sumup.html", {"error": str(e)}) + + + +@csrf_exempt +def sumup_webhook(request): + """Recibe el webhook de SumUp y actualiza la base de datos""" + if request.method == "POST": + try: + data = json.loads(request.body) + + # Verificar si el evento es un pago exitoso + if data.get("event_type") == "transaction.successful": + transaction_id = data.get("data", {}).get("transaction_id") + amount = data.get("data", {}).get("amount") + email_cliente = data.get("data", {}).get("customer_email") + + # Buscar el pedido y actualizarlo como pagado + pedido = Pedido.objects.filter(email_cliente=email_cliente, monto=amount).first() + if pedido: + pedido.transaction_id = transaction_id + pedido.estado = "Pagado" + pedido.save() + return JsonResponse({"message": "Pago actualizado"}, status=200) + else: + return JsonResponse({"error": "Pedido no encontrado"}, status=404) + + return JsonResponse({"error": "Evento no reconocido"}, status=400) + + except json.JSONDecodeError: + return JsonResponse({"error": "JSON inválido"}, status=400) + + return JsonResponse({"error": "Método no permitido"}, status=405) + \ No newline at end of file diff --git a/novawow/settings.py b/novawow/settings.py index 85796ca..68d2082 100644 --- a/novawow/settings.py +++ b/novawow/settings.py @@ -67,6 +67,14 @@ AC_SOAP_USER = "AC_SOAP" AC_SOAP_PASSWORD = "Ladyamy89" AC_SOAP_URN = "urn:AC" + +# Configuración de SumUp en settings.py +SUMUP_CLIENT_ID = "cc_classic_O8FbtnaHdjzOs6OyHMxyqwBo0pg1L" +SUMUP_CLIENT_SECRET = "cc_sk_classic_dFi7EwkHauWQnjN8FsC25TxlY1WAN2uVXtOBktzn4OCo8ZrMa8" +SUMUP_MERCHANT_EMAIL = "poveda.gandia@proton.me" +SUMUP_CURRENCY = "EUR" # Puedes cambiarlo si necesitas otra moneda + + # Configuración del correo electrónico para SMTP de Gmail EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com'