JourneyJoker/payment/views.py

60 lines
1.8 KiB
Python
Raw Permalink Normal View History

2020-02-07 14:57:30 +00:00
from django.shortcuts import render, redirect
2020-01-26 10:53:25 +00:00
from django.views.generic import DetailView, TemplateView
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
2020-02-07 14:57:30 +00:00
from django.urls import reverse
2020-01-26 10:53:25 +00:00
2020-02-07 14:57:30 +00:00
from payment.models import Payment, PAYMENT_STATUS_AUTHORIZED, PAYMENT_STATUS_FAILURE, PAYMENT_STATUS_PENDING, PAYMENT_STATUS_REFUND, PAYMENT_STATUS_SUCCESS
2020-01-26 10:53:25 +00:00
from dbsettings.models import Setting
import stripe
2019-12-24 13:41:49 +00:00
# Create your views here.
2020-01-26 10:53:25 +00:00
class StatusView(DetailView):
model = Payment
template_name = "payment/status.html"
class StripeRedirectView(TemplateView):
template_name = "payment/redirect.html"
class StripeRedirectJSView(DetailView):
model = Payment
template_name = "payment/redirect_stripe.js"
@csrf_exempt
def stripe_webhook(request):
endpoint_secret = Setting.objects.get(key="stripe.webhook.secret").value # pylint: disable=no-member
payload = request.body
sig_header = request.META['HTTP_STRIPE_SIGNATURE']
event = None
try:
event = stripe.Webhook.construct_event(
payload, sig_header, endpoint_secret
)
except ValueError:
# Invalid payload
return HttpResponse(status=400)
except stripe.error.SignatureVerificationError:
# Invalid signature
return HttpResponse(status=400)
# Handle the checkout.session.completed event
if event['type'] == 'checkout.session.completed':
session = event['data']['object']
payment = Payment.objects.get(session=session["id"])
payment.session_status = event["type"]
return HttpResponse(status=200)
2020-02-07 14:57:30 +00:00
def callback(request, pk):
obj = Payment.objects.get(uuid=pk)
if obj.status() in (PAYMENT_STATUS_AUTHORIZED, PAYMENT_STATUS_SUCCESS):
return redirect(reverse("payment:status", args=[pk]))
else:
return obj.cancel()