Implement OTP and show received callbacks
This commit is contained in:
@@ -19,10 +19,10 @@ logger = logging.getLogger(__name__)
|
||||
# Create your views here
|
||||
|
||||
|
||||
class Home(View):
|
||||
class Home(LoginRequiredMixin, View):
|
||||
template_name = "index.html"
|
||||
|
||||
async def get(self, request):
|
||||
def get(self, request):
|
||||
return render(request, self.template_name)
|
||||
|
||||
|
||||
|
||||
@@ -1,104 +1,51 @@
|
||||
import logging
|
||||
from datetime import datetime
|
||||
import uuid
|
||||
|
||||
import stripe
|
||||
from django.conf import settings
|
||||
from django.http import HttpResponse, JsonResponse
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from rest_framework.parsers import JSONParser
|
||||
from rest_framework.views import APIView
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.http import HttpResponseBadRequest
|
||||
from django.shortcuts import render
|
||||
from django.views import View
|
||||
|
||||
from core.models import Plan, Session, User
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
from core.models import Callback, Hook
|
||||
|
||||
|
||||
class Callback(APIView):
|
||||
parser_classes = [JSONParser]
|
||||
def get_callbacks(hook=None, user=None):
|
||||
if user:
|
||||
callbacks = Callback.objects.filter(hook__user=user)
|
||||
elif hook:
|
||||
callbacks = Callback.objects.filter(hook=hook)
|
||||
print("CALLBACKS", callbacks)
|
||||
return callbacks
|
||||
|
||||
# TODO: make async
|
||||
@csrf_exempt
|
||||
def post(self, request):
|
||||
payload = request.body
|
||||
sig_header = request.META["HTTP_STRIPE_SIGNATURE"]
|
||||
try:
|
||||
stripe.Webhook.construct_event(
|
||||
payload, sig_header, settings.STRIPE_ENDPOINT_SECRET
|
||||
)
|
||||
except ValueError:
|
||||
# Invalid payload
|
||||
logger.error("Invalid payload")
|
||||
return HttpResponse(status=400)
|
||||
except stripe.error.SignatureVerificationError:
|
||||
# Invalid signature
|
||||
logger.error("Invalid signature")
|
||||
return HttpResponse(status=400)
|
||||
|
||||
if request.data is None:
|
||||
return JsonResponse({"success": False}, status=500)
|
||||
if "type" in request.data.keys():
|
||||
rtype = request.data["type"]
|
||||
if rtype == "checkout.session.completed":
|
||||
session = request.data["data"]["object"]["id"]
|
||||
subscription_id = request.data["data"]["object"]["subscription"]
|
||||
session_map = Session.objects.get(session=session)
|
||||
if not session_map:
|
||||
return JsonResponse({"success": False}, status=500)
|
||||
user = session_map.user
|
||||
session_map.subscription_id = subscription_id
|
||||
session_map.save()
|
||||
class Callbacks(LoginRequiredMixin, View):
|
||||
allowed_types = ["modal", "widget", "window", "page"]
|
||||
window_content = "window-content/callbacks.html"
|
||||
|
||||
if rtype == "customer.subscription.updated":
|
||||
stripe_id = request.data["data"]["object"]["customer"]
|
||||
if not stripe_id:
|
||||
logging.error("No stripe id")
|
||||
return JsonResponse({"success": False}, status=500)
|
||||
user = User.objects.get(stripe_id=stripe_id)
|
||||
# ssubscription_active
|
||||
subscription_id = request.data["data"]["object"]["id"]
|
||||
sessions = Session.objects.filter(user=user)
|
||||
session = None
|
||||
for session_iter in sessions:
|
||||
if session_iter.subscription_id == subscription_id:
|
||||
session = session_iter
|
||||
if not session:
|
||||
logging.error(
|
||||
f"No session found for subscription id {subscription_id}"
|
||||
)
|
||||
return JsonResponse({"success": False}, status=500)
|
||||
# query Session objects
|
||||
# iterate and check against product_id
|
||||
session.request = request.data["request"]["id"]
|
||||
product_id = request.data["data"]["object"]["plan"]["id"]
|
||||
plan = Plan.objects.get(product_id=product_id)
|
||||
if not plan:
|
||||
logging.error(f"Plan not found: {product_id}")
|
||||
return JsonResponse({"success": False}, status=500)
|
||||
session.plan = plan
|
||||
session.save()
|
||||
async def get(self, request, type, hook_id=None):
|
||||
if type not in self.allowed_types:
|
||||
return HttpResponseBadRequest
|
||||
template_name = f"wm/{type}.html"
|
||||
unique = str(uuid.uuid4())[:8]
|
||||
|
||||
elif rtype == "payment_intent.succeeded":
|
||||
customer = request.data["data"]["object"]["customer"]
|
||||
user = User.objects.get(stripe_id=customer)
|
||||
if not user:
|
||||
logging.error(f"No user found for customer: {customer}")
|
||||
return JsonResponse({"success": False}, status=500)
|
||||
session = Session.objects.get(request=request.data["request"]["id"])
|
||||
|
||||
user.plans.add(session.plan)
|
||||
user.last_payment = datetime.utcnow()
|
||||
user.save()
|
||||
|
||||
elif rtype == "customer.subscription.deleted":
|
||||
customer = request.data["data"]["object"]["customer"]
|
||||
user = User.objects.get(stripe_id=customer)
|
||||
if not user:
|
||||
logging.error(f"No user found for customer {customer}")
|
||||
return JsonResponse({"success": False}, status=500)
|
||||
product_id = request.data["data"]["object"]["plan"]["id"]
|
||||
plan = Plan.objects.get(product_id=product_id)
|
||||
user.plans.remove(plan)
|
||||
user.save()
|
||||
if hook_id:
|
||||
try:
|
||||
hook = Hook.objects.get(id=hook_id, user=request.user)
|
||||
except Hook.DoesNotExist:
|
||||
message = "Hook does not exist."
|
||||
message_class = "danger"
|
||||
context = {
|
||||
"message": message,
|
||||
"class": message_class,
|
||||
}
|
||||
return render(request, "wm/modal.html", context)
|
||||
callbacks = get_callbacks(hook)
|
||||
else:
|
||||
return JsonResponse({"success": False}, status=500)
|
||||
return JsonResponse({"success": True})
|
||||
callbacks = get_callbacks(user=request.user)
|
||||
|
||||
context = {
|
||||
"title": f"Callbacks ({type})",
|
||||
"unique": unique,
|
||||
"window_content": self.window_content,
|
||||
"items": callbacks,
|
||||
}
|
||||
return render(request, template_name, context)
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import uuid
|
||||
|
||||
import orjson
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.http import HttpResponseBadRequest
|
||||
from django.http import HttpResponse, HttpResponseBadRequest
|
||||
from django.shortcuts import render
|
||||
from django.views import View
|
||||
from rest_framework.parsers import FormParser
|
||||
from rest_framework.parsers import FormParser, JSONParser
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from core.forms import HookForm
|
||||
from core.models import Hook
|
||||
from core.models import Callback, Hook
|
||||
|
||||
|
||||
def get_hooks(user):
|
||||
@@ -16,6 +17,28 @@ def get_hooks(user):
|
||||
return hooks
|
||||
|
||||
|
||||
class HookAPI(APIView):
|
||||
parser_classes = [JSONParser]
|
||||
|
||||
def post(self, request, hook_name):
|
||||
hook = Hook.objects.get(name=hook_name)
|
||||
print("DATA FREOM POST", request.data)
|
||||
callback = Callback.objects.create(
|
||||
hook=hook,
|
||||
data=request.data,
|
||||
)
|
||||
callback.save()
|
||||
print("SAVED")
|
||||
|
||||
return HttpResponse("OK")
|
||||
|
||||
def get(self, request, hook_name):
|
||||
hook = Hook.objects.get(name=hook_name)
|
||||
|
||||
return_data = {"name": hook.name, "hook": hook.hook, "hook_id": hook.id}
|
||||
return HttpResponse(orjson.dumps(return_data), content_type="application/json")
|
||||
|
||||
|
||||
class Hooks(LoginRequiredMixin, View):
|
||||
allowed_types = ["modal", "widget", "window", "page"]
|
||||
window_content = "window-content/hooks.html"
|
||||
@@ -27,10 +50,10 @@ class Hooks(LoginRequiredMixin, View):
|
||||
unique = str(uuid.uuid4())[:8]
|
||||
hooks = get_hooks(request.user)
|
||||
context = {
|
||||
"title": f"{type} Demo",
|
||||
"title": f"Hooks ({type})",
|
||||
"unique": unique,
|
||||
"window_content": self.window_content,
|
||||
"hooks": hooks,
|
||||
"items": hooks,
|
||||
}
|
||||
return render(request, template_name, context)
|
||||
|
||||
@@ -98,7 +121,7 @@ class HookAction(LoginRequiredMixin, APIView):
|
||||
hooks = get_hooks(request.user)
|
||||
|
||||
context = {
|
||||
"hooks": hooks,
|
||||
"items": hooks,
|
||||
}
|
||||
if message:
|
||||
context["message"] = message
|
||||
@@ -124,7 +147,7 @@ class HookAction(LoginRequiredMixin, APIView):
|
||||
hooks = get_hooks(request.user)
|
||||
|
||||
context = {
|
||||
"hooks": hooks,
|
||||
"items": hooks,
|
||||
}
|
||||
if message:
|
||||
context["message"] = message
|
||||
|
||||
104
core/views/stripe_callbacks.py
Normal file
104
core/views/stripe_callbacks.py
Normal file
@@ -0,0 +1,104 @@
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
import stripe
|
||||
from django.conf import settings
|
||||
from django.http import HttpResponse, JsonResponse
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from rest_framework.parsers import JSONParser
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from core.models import Plan, Session, User
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Callback(APIView):
|
||||
parser_classes = [JSONParser]
|
||||
|
||||
# TODO: make async
|
||||
@csrf_exempt
|
||||
def post(self, request):
|
||||
payload = request.body
|
||||
sig_header = request.META["HTTP_STRIPE_SIGNATURE"]
|
||||
try:
|
||||
stripe.Webhook.construct_event(
|
||||
payload, sig_header, settings.STRIPE_ENDPOINT_SECRET
|
||||
)
|
||||
except ValueError:
|
||||
# Invalid payload
|
||||
logger.error("Invalid payload")
|
||||
return HttpResponse(status=400)
|
||||
except stripe.error.SignatureVerificationError:
|
||||
# Invalid signature
|
||||
logger.error("Invalid signature")
|
||||
return HttpResponse(status=400)
|
||||
|
||||
if request.data is None:
|
||||
return JsonResponse({"success": False}, status=500)
|
||||
if "type" in request.data.keys():
|
||||
rtype = request.data["type"]
|
||||
if rtype == "checkout.session.completed":
|
||||
session = request.data["data"]["object"]["id"]
|
||||
subscription_id = request.data["data"]["object"]["subscription"]
|
||||
session_map = Session.objects.get(session=session)
|
||||
if not session_map:
|
||||
return JsonResponse({"success": False}, status=500)
|
||||
user = session_map.user
|
||||
session_map.subscription_id = subscription_id
|
||||
session_map.save()
|
||||
|
||||
if rtype == "customer.subscription.updated":
|
||||
stripe_id = request.data["data"]["object"]["customer"]
|
||||
if not stripe_id:
|
||||
logging.error("No stripe id")
|
||||
return JsonResponse({"success": False}, status=500)
|
||||
user = User.objects.get(stripe_id=stripe_id)
|
||||
# ssubscription_active
|
||||
subscription_id = request.data["data"]["object"]["id"]
|
||||
sessions = Session.objects.filter(user=user)
|
||||
session = None
|
||||
for session_iter in sessions:
|
||||
if session_iter.subscription_id == subscription_id:
|
||||
session = session_iter
|
||||
if not session:
|
||||
logging.error(
|
||||
f"No session found for subscription id {subscription_id}"
|
||||
)
|
||||
return JsonResponse({"success": False}, status=500)
|
||||
# query Session objects
|
||||
# iterate and check against product_id
|
||||
session.request = request.data["request"]["id"]
|
||||
product_id = request.data["data"]["object"]["plan"]["id"]
|
||||
plan = Plan.objects.get(product_id=product_id)
|
||||
if not plan:
|
||||
logging.error(f"Plan not found: {product_id}")
|
||||
return JsonResponse({"success": False}, status=500)
|
||||
session.plan = plan
|
||||
session.save()
|
||||
|
||||
elif rtype == "payment_intent.succeeded":
|
||||
customer = request.data["data"]["object"]["customer"]
|
||||
user = User.objects.get(stripe_id=customer)
|
||||
if not user:
|
||||
logging.error(f"No user found for customer: {customer}")
|
||||
return JsonResponse({"success": False}, status=500)
|
||||
session = Session.objects.get(request=request.data["request"]["id"])
|
||||
|
||||
user.plans.add(session.plan)
|
||||
user.last_payment = datetime.utcnow()
|
||||
user.save()
|
||||
|
||||
elif rtype == "customer.subscription.deleted":
|
||||
customer = request.data["data"]["object"]["customer"]
|
||||
user = User.objects.get(stripe_id=customer)
|
||||
if not user:
|
||||
logging.error(f"No user found for customer {customer}")
|
||||
return JsonResponse({"success": False}, status=500)
|
||||
product_id = request.data["data"]["object"]["plan"]["id"]
|
||||
plan = Plan.objects.get(product_id=product_id)
|
||||
user.plans.remove(plan)
|
||||
user.save()
|
||||
else:
|
||||
return JsonResponse({"success": False}, status=500)
|
||||
return JsonResponse({"success": True})
|
||||
Reference in New Issue
Block a user