Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Product views
- from django.http import HttpResponseRedirect, HttpResponse
- from django.conf import settings
- from django.shortcuts import render, redirect
- # email
- from django.core.mail import send_mail
- # modelos
- from .models import Producto
- # , PedidoPagado
- # forms
- from .forms import FormularioPago
- # stripe
- import stripe
- # Debugging PDB
- import pdb
- stripe.api_key = settings.STRIPE_TEST_SECRET_KEY
- # Create your views here.
- def pagina_producto_flash_lightning(request):
- producto = Producto.objects.filter(titulo='Flash of Lightning')
- return render(request, 'pagina_producto_flash_lightning.html', {'producto': producto})
- def pagina_producto_twister(request):
- producto = Producto.objects.filter(titulo='Twister')
- return render(request, 'pagina_producto_twister.html', {'producto': producto})
- def pagina_productos(request):
- productos = Producto.objects.all()
- return render(request, 'pagina_productos.html', {'productos': productos})
- def vista_pedido(request, id):
- # Si el metodo del request es POST ->
- if request.method == 'POST':
- # crea una instancia del formulario y rellena los datos introducidos:
- form = FormularioPago(request.POST or None)
- # comprobamos la validez del formulario:
- if form.is_valid():
- # A partir de aqui se implementa la paserala de pagos Stripe.
- # Validamos la informacion y creamos token para stripe.
- nombre = form.cleaned_data['nombre']
- apellido = form.cleaned_data['apellido']
- apellido2 = form.cleaned_data['apellido2']
- email = form.cleaned_data['email']
- telefono = form.cleaned_data['telefono']
- direccion = form.cleaned_data['direccion']
- ciudad = form.cleaned_data['ciudad']
- provincia = form.cleaned_data['provincia']
- c_postal = form.cleaned_data['c_postal']
- cc = form.cleaned_data['cc_number']
- cvc = form.cleaned_data['cc_code']
- fexp = form.cleaned_data['cc_expiry']
- # Validamos fecha EXP cc
- fexp.split("/")
- # Creamos instancia del producto a traves de su id.
- producto_data = Producto.objects.filter(id=id)
- print(producto_data['precio'])
- send_mail('Datos TEST', str(fexp) + " " + str(producto_data['precio']), 'admin@ea-time.com', ['kmogun9@gmail.com'])
- token = stripe.Token.create(
- card={
- "number": cc,
- "exp_month": fexp[0:2],
- "exp_year": fexp[3:5],
- "cvc": cvc
- },
- )
- if token:
- try:
- global charge
- charge = stripe.Charge.create(
- amount=int(producto_data['precio']), # <<<--------- <<<<-------- <<<<------ DEFINIR CANTIDAD SEGUN PRODUCTO.
- currency="eur",
- source=token, # creado en el backend
- description="Random charge for test"
- )
- return HttpResponseRedirect('/thanks/')
- except stripe.error.CardError as e:
- # Since it's a decline, stripe.error.CardError will be caught
- body = e.json_body
- err = body.get('error', {})
- print("Status is: %s" % e.http_status)
- print("Type is: %s" % err.get('type'))
- print("Code is: %s" % err.get('code'))
- # param is '' in this case
- print("Param is: %s" % err.get('param'))
- print("Message is: %s" % err.get('message'))
- return HttpResponse(
- 'Card Error, status: '+str(e.http_status)+' Type: '
- + str(err.get('type'))+' Code: '+str(err.get('code')) +
- ' Param: '+str(err.get('param'))+' Mensage: '+str(err.get('message'))
- )
- except stripe.error.RateLimitError as e:
- return HttpResponse("Error, RateLimitError, Demasiadas peticiones. "+e, content_type='text/plain')
- except stripe.error.InvalidRequestError as e:
- return HttpResponse("Error, parametros enviados a la API incorrectos. "+e, content_type='text/plain')
- except stripe.error.AuthenticationError as e:
- send_mail('Error en las API keys', e, 'Admin@testdjangooo.com', ['kmogun9@gmail.com'])
- return HttpResponse("Error, en api keys, contacte con administrador. "+e, content_type='text/plain')
- except stripe.error.APIConnectionError as e:
- send_mail('Network error al conectar con Stripe.', e, 'Admin@testdjangooo.com', ['kmogun9@gmail.com'])
- return HttpResponse("Error de red, vuelve a intentar. "+e, content_type='text/plain')
- except stripe.error.StripeError as e:
- return HttpResponse("Error, generico. "+e, content_type='text/plain')
- except Exception as e:
- send_mail('Error generico. ', e, 'Admin@testdjangooo.com', ['kmogun9@gmail.com'])
- return HttpResponse('Error ajeno a Stripe '+e, content_type='text/plain')
- else:
- return HttpResponseRedirect('/')
- else:
- return HttpResponseRedirect('/')
- # si el metodo es get se crea el formulario y se devuelve el formulario vacio.
- else:
- form = FormularioPago()
- producto = Producto.objects.filter(id=id)
- return render(request, 'pagina_pedido.html', {'form': form, 'producto': producto})
- def vista_compra(request, id, *args, **kwargs):
- if request.method == 'POST':
- # crea una instancia del formulario y rellena los datos introducidos:
- form = FormularioPago(request.POST)
- # comprobamos la validez del formulario:
- if form.is_valid():
- # A partir de aqui se implementa la paserala de pagos Stripe.
- # Validamos la informacion y creamos token para stripe.
- producto = Producto.objects.filter(id=id)
- nombre = form.cleaned_data['nombre']
- apellido = form.cleaned_data['apellido']
- apellido2 = form.cleaned_data['segundo_apellido']
- email = form.cleaned_data['email']
- telefono = form.cleaned_data['telefono']
- direccion = form.cleaned_data['direccion']
- ciudad = form.cleaned_data['ciudad']
- provincia = form.cleaned_data['provincia']
- c_postal = form.cleaned_data['c_postal']
- cc = form.cleaned_data['cc_number']
- cvc = form.cleaned_data['cc_code']
- fexp = form.cleaned_data['cc_expiry']
- data = str(fexp)
- data = data.split("-")
- precio = str(producto[0].precio)
- # Separamos el precio en una lista de dos partes.
- precio = precio.split(".")
- precio1 = precio[0]
- precio2 = str(precio[1]).split("€")
- precio2 = str(precio2[0]).split(" ")
- token = stripe.Token.create(
- card={
- "number": cc,
- "exp_month": data[1],
- "exp_year": data[0],
- "cvc": cvc
- },
- )
- if token:
- try:
- # Use Stripe's library to make requests...
- stripe.Charge.create(
- amount=int(precio1+precio2[0]),
- currency="eur",
- source=token,
- description="Cargo por producto comprado -> " + producto[0].titulo
- )
- send_mail(
- 'Pago realizado',
- nombre + " " + apellido + " " + apellido2 + " Ha realizado un pedido de ... " + \
- producto[0].titulo + " Precio -> " + str(producto[0].precio),
- 'admin@ea-time.com',
- ['admin@ea-time.com'])
- # Pedido realizado correctamente....
- # PedidoPagado.objects.create(
- # nombre=nombre,
- # apellido=apellido,
- # segundo_apellido=apellido2,
- # email=email,
- # telefono=telefono,
- # direccion=direccion,
- # ciudad=ciudad,
- # provincia=provincia,
- # c_postal=c_postal,
- # pagado=True,
- #
- # )
- # pdb.set_trace()
- return redirect('gracias.html')
- except stripe.error.CardError as e:
- # Since it's a decline, stripe.error.CardError will be caught
- body = e.json_body
- err = body.get('error', {})
- print("Status is: %s" % e.http_status)
- print("Type is: %s" % err.get('type'))
- print("Code is: %s" % err.get('code'))
- # param is '' in this case
- print("Param is: %s" % err.get('param'))
- print("Message is: %s" % err.get('message'))
- return redirect('error_pago.html')
- except stripe.error.RateLimitError as e:
- # Too many requests made to the API too quickly
- return redirect('error_pago.html')
- except stripe.error.InvalidRequestError as e:
- # Invalid parameters were supplied to Stripe's API
- return redirect('error_pago.html')
- except stripe.error.AuthenticationError as e:
- # Authentication with Stripe's API failed
- # (maybe you changed API keys recently)
- return redirect('error_pago.html')
- except stripe.error.APIConnectionError as e:
- # Network communication with Stripe failed
- return redirect('error_pago.html')
- except stripe.error.StripeError as e:
- # Display a very generic error to the user, and maybe send
- # yourself an email
- return redirect('error_pago.html')
- except Exception as e:
- # Something else happened, completely unrelated to Stripe
- return redirect('error.html')
- send_mail('Datos TEST', str(fexp) + " ", 'admin@ea-time.com', ['kmogun9@gmail.com'])
- else:
- return redirect('/productos/')
- else:
- return redirect('/')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement