Implementacion Inicial SumUP
This commit is contained in:
+8
-1
@@ -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):
|
||||
|
||||
@@ -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),
|
||||
),
|
||||
]
|
||||
+12
-1
@@ -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})"
|
||||
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}"
|
||||
|
||||
@@ -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()}")
|
||||
@@ -0,0 +1,9 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
{% 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' %}
|
||||
@@ -0,0 +1,32 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Pago con SumUp</title>
|
||||
<script src="https://gateway.sumup.com/gateway/ecom/card/v2/sdk.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Pago con SumUp</h1>
|
||||
|
||||
{% if error %}
|
||||
<p style="color: red;">Error: {{ error }}</p>
|
||||
{% else %}
|
||||
<div id="sumup-card"></div>
|
||||
|
||||
<script>
|
||||
SumUpCard.mount({
|
||||
checkoutId: "{{ checkout_id }}",
|
||||
onResponse: function (type, body) {
|
||||
if (type === 'success') {
|
||||
alert("Pago exitoso. ID de transacción: " + body.transaction_code);
|
||||
console.log("Pago exitoso:", body);
|
||||
} else if (type === 'error') {
|
||||
alert("Error en el pago: " + body.message);
|
||||
console.error("Error en el pago:", body);
|
||||
}
|
||||
}
|
||||
});
|
||||
</script>
|
||||
{% endif %}
|
||||
</body>
|
||||
</html>
|
||||
@@ -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"),
|
||||
|
||||
]
|
||||
|
||||
|
||||
+45
-1
@@ -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)
|
||||
|
||||
@@ -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'
|
||||
|
||||
Reference in New Issue
Block a user