JourneyJoker/payment/views.py

60 lines
No EOL
1.8 KiB
Python

from django.shortcuts import render, redirect
from django.views.generic import DetailView, TemplateView
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.urls import reverse
from payment.models import Payment, PAYMENT_STATUS_AUTHORIZED, PAYMENT_STATUS_FAILURE, PAYMENT_STATUS_PENDING, PAYMENT_STATUS_REFUND, PAYMENT_STATUS_SUCCESS
from dbsettings.models import Setting
import stripe
# Create your views here.
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)
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()