Advertisement
Guest User

Untitled

a guest
Apr 3rd, 2019
386
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.03 KB | None | 0 0
  1. # Product views
  2. from django.http import HttpResponseRedirect, HttpResponse
  3. from django.conf import settings
  4. from django.shortcuts import render, redirect
  5.  
  6. # email
  7. from django.core.mail import send_mail
  8.  
  9. # modelos
  10. from .models import Producto
  11.     # , PedidoPagado
  12.  
  13. # forms
  14. from .forms import FormularioPago
  15.  
  16. # stripe
  17. import stripe
  18.  
  19. # Debugging PDB
  20. import pdb
  21.  
  22. stripe.api_key = settings.STRIPE_TEST_SECRET_KEY
  23.  
  24.  
  25. # Create your views here.
  26.  
  27. def pagina_producto_flash_lightning(request):
  28.  
  29.     producto = Producto.objects.filter(titulo='Flash of Lightning')
  30.     return render(request, 'pagina_producto_flash_lightning.html', {'producto': producto})
  31.  
  32. def pagina_producto_twister(request):
  33.  
  34.     producto = Producto.objects.filter(titulo='Twister')
  35.     return render(request, 'pagina_producto_twister.html', {'producto': producto})
  36.  
  37. def pagina_productos(request):
  38.  
  39.     productos = Producto.objects.all()
  40.     return render(request, 'pagina_productos.html', {'productos': productos})
  41.  
  42. def vista_pedido(request, id):
  43.  
  44.     # Si el metodo del request es POST ->
  45.     if request.method == 'POST':
  46.         # crea una instancia del formulario y rellena los datos introducidos:
  47.         form = FormularioPago(request.POST or None)
  48.         # comprobamos la validez del formulario:
  49.         if form.is_valid():
  50.  
  51.             # A partir de aqui se implementa la paserala de pagos Stripe.
  52.             # Validamos la informacion y creamos token para stripe.
  53.  
  54.             nombre      = form.cleaned_data['nombre']
  55.             apellido    = form.cleaned_data['apellido']
  56.             apellido2   = form.cleaned_data['apellido2']
  57.             email       = form.cleaned_data['email']
  58.             telefono    = form.cleaned_data['telefono']
  59.             direccion   = form.cleaned_data['direccion']
  60.             ciudad      = form.cleaned_data['ciudad']
  61.             provincia   = form.cleaned_data['provincia']
  62.             c_postal    = form.cleaned_data['c_postal']
  63.  
  64.             cc          = form.cleaned_data['cc_number']
  65.             cvc         = form.cleaned_data['cc_code']
  66.             fexp        = form.cleaned_data['cc_expiry']
  67.  
  68.             # Validamos fecha EXP cc
  69.             fexp.split("/")
  70.  
  71.             # Creamos instancia del producto a traves de su id.
  72.             producto_data = Producto.objects.filter(id=id)
  73.             print(producto_data['precio'])
  74.  
  75.             send_mail('Datos TEST', str(fexp) + " " + str(producto_data['precio']), 'admin@ea-time.com', ['kmogun9@gmail.com'])
  76.  
  77.             token = stripe.Token.create(
  78.                 card={
  79.                     "number": cc,
  80.                     "exp_month": fexp[0:2],
  81.                     "exp_year": fexp[3:5],
  82.                     "cvc": cvc
  83.                 },
  84.             )
  85.  
  86.             if token:
  87.                 try:
  88.                     global charge
  89.                     charge = stripe.Charge.create(
  90.                         amount=int(producto_data['precio']), # <<<--------- <<<<-------- <<<<------ DEFINIR CANTIDAD SEGUN PRODUCTO.
  91.                         currency="eur",
  92.                         source=token,  # creado en el backend
  93.                         description="Random charge for test"
  94.                     )
  95.                     return HttpResponseRedirect('/thanks/')
  96.  
  97.                 except stripe.error.CardError as e:
  98.                     # Since it's a decline, stripe.error.CardError will be caught
  99.                     body = e.json_body
  100.                     err = body.get('error', {})
  101.  
  102.                     print("Status is: %s" % e.http_status)
  103.                     print("Type is: %s" % err.get('type'))
  104.                     print("Code is: %s" % err.get('code'))
  105.                     # param is '' in this case
  106.                     print("Param is: %s" % err.get('param'))
  107.                     print("Message is: %s" % err.get('message'))
  108.                     return HttpResponse(
  109.                         'Card Error, status: '+str(e.http_status)+' Type: '
  110.                         + str(err.get('type'))+' Code: '+str(err.get('code')) +
  111.                         ' Param: '+str(err.get('param'))+' Mensage: '+str(err.get('message'))
  112.                     )
  113.  
  114.                 except stripe.error.RateLimitError as e:
  115.                     return HttpResponse("Error, RateLimitError, Demasiadas peticiones. "+e, content_type='text/plain')
  116.  
  117.                 except stripe.error.InvalidRequestError as e:
  118.                     return HttpResponse("Error, parametros enviados a la API incorrectos. "+e, content_type='text/plain')
  119.  
  120.                 except stripe.error.AuthenticationError as e:
  121.                     send_mail('Error en las API keys', e, 'Admin@testdjangooo.com', ['kmogun9@gmail.com'])
  122.                     return HttpResponse("Error, en api keys, contacte con administrador. "+e, content_type='text/plain')
  123.  
  124.                 except stripe.error.APIConnectionError as e:
  125.                     send_mail('Network error al conectar con Stripe.', e, 'Admin@testdjangooo.com', ['kmogun9@gmail.com'])
  126.                     return HttpResponse("Error de red, vuelve a intentar. "+e, content_type='text/plain')
  127.  
  128.                 except stripe.error.StripeError as e:
  129.                     return HttpResponse("Error, generico. "+e, content_type='text/plain')
  130.  
  131.                 except Exception as e:
  132.                     send_mail('Error generico. ', e, 'Admin@testdjangooo.com', ['kmogun9@gmail.com'])
  133.                     return HttpResponse('Error ajeno a Stripe '+e, content_type='text/plain')
  134.  
  135.             else:
  136.                 return HttpResponseRedirect('/')
  137.  
  138.         else:
  139.             return HttpResponseRedirect('/')
  140.  
  141.     # si el metodo es get se crea el formulario y se devuelve el formulario vacio.
  142.  
  143.     else:
  144.         form = FormularioPago()
  145.         producto = Producto.objects.filter(id=id)
  146.  
  147.     return render(request, 'pagina_pedido.html', {'form': form, 'producto': producto})
  148.  
  149. def vista_compra(request, id, *args, **kwargs):
  150.  
  151.     if request.method == 'POST':
  152.         # crea una instancia del formulario y rellena los datos introducidos:
  153.         form = FormularioPago(request.POST)
  154.         # comprobamos la validez del formulario:
  155.  
  156.         if form.is_valid():
  157.  
  158.             # A partir de aqui se implementa la paserala de pagos Stripe.
  159.             # Validamos la informacion y creamos token para stripe.
  160.  
  161.             producto    = Producto.objects.filter(id=id)
  162.             nombre      = form.cleaned_data['nombre']
  163.             apellido    = form.cleaned_data['apellido']
  164.             apellido2   = form.cleaned_data['segundo_apellido']
  165.             email       = form.cleaned_data['email']
  166.             telefono    = form.cleaned_data['telefono']
  167.             direccion   = form.cleaned_data['direccion']
  168.             ciudad      = form.cleaned_data['ciudad']
  169.             provincia   = form.cleaned_data['provincia']
  170.             c_postal    = form.cleaned_data['c_postal']
  171.  
  172.             cc          = form.cleaned_data['cc_number']
  173.             cvc         = form.cleaned_data['cc_code']
  174.             fexp        = form.cleaned_data['cc_expiry']
  175.             data = str(fexp)
  176.             data = data.split("-")
  177.  
  178.             precio = str(producto[0].precio)
  179.             # Separamos el precio en una lista de dos partes.
  180.             precio = precio.split(".")
  181.             precio1 = precio[0]
  182.             precio2 = str(precio[1]).split("€")
  183.             precio2 = str(precio2[0]).split(" ")
  184.  
  185.             token = stripe.Token.create(
  186.                 card={
  187.                     "number": cc,
  188.                     "exp_month": data[1],
  189.                     "exp_year": data[0],
  190.                     "cvc": cvc
  191.                 },
  192.             )
  193.             if token:
  194.                 try:
  195.                     # Use Stripe's library to make requests...
  196.                     stripe.Charge.create(
  197.                         amount=int(precio1+precio2[0]),
  198.                         currency="eur",
  199.                         source=token,
  200.                         description="Cargo por producto comprado -> " + producto[0].titulo
  201.                     )
  202.                     send_mail(
  203.                         'Pago realizado',
  204.                         nombre + " " + apellido + " " + apellido2 + " Ha realizado un pedido de ... " + \
  205.                         producto[0].titulo + " Precio -> " + str(producto[0].precio),
  206.                         'admin@ea-time.com',
  207.                         ['admin@ea-time.com'])
  208.  
  209.  
  210.                     # Pedido realizado correctamente....
  211.                     # PedidoPagado.objects.create(
  212.                     #     nombre=nombre,
  213.                     #     apellido=apellido,
  214.                     #     segundo_apellido=apellido2,
  215.                     #     email=email,
  216.                     #     telefono=telefono,
  217.                     #     direccion=direccion,
  218.                     #     ciudad=ciudad,
  219.                     #     provincia=provincia,
  220.                     #     c_postal=c_postal,
  221.                     #     pagado=True,
  222.                     #
  223.                     # )
  224.  
  225.                     # pdb.set_trace()
  226.  
  227.                     return redirect('gracias.html')
  228.                 except stripe.error.CardError as e:
  229.                     # Since it's a decline, stripe.error.CardError will be caught
  230.                     body = e.json_body
  231.                     err = body.get('error', {})
  232.  
  233.                     print("Status is: %s" % e.http_status)
  234.                     print("Type is: %s" % err.get('type'))
  235.                     print("Code is: %s" % err.get('code'))
  236.                     # param is '' in this case
  237.                     print("Param is: %s" % err.get('param'))
  238.                     print("Message is: %s" % err.get('message'))
  239.                     return redirect('error_pago.html')
  240.                 except stripe.error.RateLimitError as e:
  241.                     # Too many requests made to the API too quickly
  242.                     return redirect('error_pago.html')
  243.                 except stripe.error.InvalidRequestError as e:
  244.                     # Invalid parameters were supplied to Stripe's API
  245.                     return redirect('error_pago.html')
  246.  
  247.                 except stripe.error.AuthenticationError as e:
  248.                     # Authentication with Stripe's API failed
  249.                     # (maybe you changed API keys recently)
  250.                     return redirect('error_pago.html')
  251.  
  252.                 except stripe.error.APIConnectionError as e:
  253.                     # Network communication with Stripe failed
  254.                     return redirect('error_pago.html')
  255.  
  256.                 except stripe.error.StripeError as e:
  257.                     # Display a very generic error to the user, and maybe send
  258.                     # yourself an email
  259.                     return redirect('error_pago.html')
  260.  
  261.                 except Exception as e:
  262.                     # Something else happened, completely unrelated to Stripe
  263.                     return redirect('error.html')
  264.  
  265.  
  266.             send_mail('Datos TEST', str(fexp) + " ", 'admin@ea-time.com', ['kmogun9@gmail.com'])
  267.         else:
  268.             return redirect('/productos/')
  269.     else:
  270.         return redirect('/')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement