forked from uncloud/uncloud
- Added PricingPlan Model
- Implement a complete cycle for buying a Matrix Chat Host - Refactor the Payement cycle and stripe related methods
This commit is contained in:
parent
e205d8d07c
commit
b7aa1c6971
81 changed files with 5079 additions and 810 deletions
|
|
@ -1,7 +1,5 @@
|
|||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.views.generic.base import TemplateView
|
||||
|
||||
|
||||
from django.shortcuts import render
|
||||
from django.db import transaction
|
||||
from django.contrib.auth import get_user_model
|
||||
|
|
@ -29,27 +27,31 @@ from .selectors import *
|
|||
from datetime import datetime
|
||||
from vat_validator import sanitize_vat
|
||||
import uncloud_pay.stripe as uncloud_stripe
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.http import JsonResponse
|
||||
import stripe
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
###
|
||||
# 2020-12 checked code
|
||||
|
||||
class RegisterCard(LoginRequiredMixin, TemplateView):
|
||||
login_url = '/login/'
|
||||
|
||||
class RegisterCard(TemplateView):
|
||||
template_name = "uncloud_pay/register_stripe.html"
|
||||
|
||||
@method_decorator(login_required)
|
||||
def dispatch(self, *args, **kwargs):
|
||||
return super().dispatch(*args, **kwargs)
|
||||
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
|
||||
customer_id = uncloud_stripe.get_customer_id_for(self.request.user)
|
||||
|
||||
setup_intent = uncloud_stripe.create_setup_intent(customer_id)
|
||||
|
||||
context = super().get_context_data(**kwargs)
|
||||
context['client_secret'] = setup_intent.client_secret
|
||||
context['username'] = self.request.user
|
||||
context['username'] = self.request.user.username
|
||||
context['stripe_pk'] = uncloud_stripe.public_api_key
|
||||
return context
|
||||
|
||||
|
|
@ -70,7 +72,6 @@ class CreditCardViewSet(mixins.RetrieveModelMixin,
|
|||
def get_queryset(self):
|
||||
return StripeCreditCard.objects.filter(owner=self.request.user)
|
||||
|
||||
|
||||
class PaymentViewSet(viewsets.ModelViewSet):
|
||||
serializer_class = PaymentSerializer
|
||||
permission_classes = [permissions.IsAuthenticated]
|
||||
|
|
@ -89,24 +90,13 @@ class BalanceViewSet(viewsets.ViewSet):
|
|||
return Response(serializer.data)
|
||||
|
||||
|
||||
###
|
||||
# Payments and Payment Methods.
|
||||
|
||||
|
||||
class OrderViewSet(viewsets.ReadOnlyModelViewSet):
|
||||
serializer_class = OrderSerializer
|
||||
permission_classes = [permissions.IsAuthenticated]
|
||||
|
||||
def get_queryset(self):
|
||||
return Order.objects.filter(owner=self.request.user)
|
||||
|
||||
|
||||
|
||||
class ListCards(LoginRequiredMixin, TemplateView):
|
||||
login_url = '/login/'
|
||||
|
||||
class ListCards(TemplateView):
|
||||
template_name = "uncloud_pay/list_stripe.html"
|
||||
|
||||
@method_decorator(login_required)
|
||||
def dispatch(self, *args, **kwargs):
|
||||
return super().dispatch(*args, **kwargs)
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
customer_id = uncloud_stripe.get_customer_id_for(self.request.user)
|
||||
cards = uncloud_stripe.get_customer_cards(customer_id)
|
||||
|
|
@ -117,140 +107,6 @@ class ListCards(LoginRequiredMixin, TemplateView):
|
|||
|
||||
return context
|
||||
|
||||
class PaymentMethodViewSet(viewsets.ModelViewSet):
|
||||
permission_classes = [permissions.IsAuthenticated]
|
||||
|
||||
def get_serializer_class(self):
|
||||
if self.action == 'create':
|
||||
return CreatePaymentMethodSerializer
|
||||
elif self.action == 'update':
|
||||
return UpdatePaymentMethodSerializer
|
||||
elif self.action == 'charge':
|
||||
return ChargePaymentMethodSerializer
|
||||
else:
|
||||
return PaymentMethodSerializer
|
||||
|
||||
def get_queryset(self):
|
||||
return PaymentMethod.objects.filter(owner=self.request.user)
|
||||
|
||||
# XXX: Handling of errors is far from great down there.
|
||||
@transaction.atomic
|
||||
def create(self, request):
|
||||
serializer = self.get_serializer(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
|
||||
# Set newly created method as primary if no other method is.
|
||||
if PaymentMethod.get_primary_for(request.user) == None:
|
||||
serializer.validated_data['primary'] = True
|
||||
|
||||
if serializer.validated_data['source'] == "stripe":
|
||||
# Retrieve Stripe customer ID for user.
|
||||
customer_id = uncloud_stripe.get_customer_id_for(request.user)
|
||||
if customer_id == None:
|
||||
return Response(
|
||||
{'error': 'Could not resolve customer stripe ID.'},
|
||||
status=status.HTTP_500_INTERNAL_SERVER_ERROR)
|
||||
|
||||
try:
|
||||
setup_intent = uncloud_stripe.create_setup_intent(customer_id)
|
||||
except Exception as e:
|
||||
return Response({'error': str(e)},
|
||||
status=status.HTTP_500_INTERNAL_SERVER_ERROR)
|
||||
|
||||
payment_method = PaymentMethod.objects.create(
|
||||
owner=request.user,
|
||||
stripe_setup_intent_id=setup_intent.id,
|
||||
**serializer.validated_data)
|
||||
|
||||
# TODO: find a way to use reverse properly:
|
||||
# https://www.django-rest-framework.org/api-guide/reverse/
|
||||
path = "payment-method/{}/register-stripe-cc".format(
|
||||
payment_method.uuid)
|
||||
stripe_registration_url = reverse('api-root', request=request) + path
|
||||
return Response({'please_visit': stripe_registration_url})
|
||||
else:
|
||||
serializer.save(owner=request.user, **serializer.validated_data)
|
||||
return Response(serializer.data)
|
||||
|
||||
@action(detail=True, methods=['post'])
|
||||
def charge(self, request, pk=None):
|
||||
payment_method = self.get_object()
|
||||
serializer = self.get_serializer(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
amount = serializer.validated_data['amount']
|
||||
try:
|
||||
payment = payment_method.charge(amount)
|
||||
output_serializer = PaymentSerializer(payment)
|
||||
return Response(output_serializer.data)
|
||||
except Exception as e:
|
||||
return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
|
||||
|
||||
@action(detail=True, methods=['get'], url_path='register-stripe-cc', renderer_classes=[TemplateHTMLRenderer])
|
||||
def register_stripe_cc(self, request, pk=None):
|
||||
payment_method = self.get_object()
|
||||
|
||||
if payment_method.source != 'stripe':
|
||||
return Response(
|
||||
{'error': 'This is not a Stripe-based payment method.'},
|
||||
template_name='error.html.j2')
|
||||
|
||||
if payment_method.active:
|
||||
return Response(
|
||||
{'error': 'This payment method is already active'},
|
||||
template_name='error.html.j2')
|
||||
|
||||
try:
|
||||
setup_intent = uncloud_stripe.get_setup_intent(
|
||||
payment_method.stripe_setup_intent_id)
|
||||
except Exception as e:
|
||||
return Response(
|
||||
{'error': str(e)},
|
||||
template_name='error.html.j2')
|
||||
|
||||
# TODO: find a way to use reverse properly:
|
||||
# https://www.django-rest-framework.org/api-guide/reverse/
|
||||
callback_path= "payment-method/{}/activate-stripe-cc/".format(
|
||||
payment_method.id)
|
||||
callback = reverse('api-root', request=request) + callback_path
|
||||
|
||||
# Render stripe card registration form.
|
||||
template_args = {
|
||||
'client_secret': setup_intent.client_secret,
|
||||
'stripe_pk': uncloud_stripe.public_api_key,
|
||||
'callback': callback
|
||||
}
|
||||
return Response(template_args, template_name='stripe-payment.html.j2')
|
||||
|
||||
@action(detail=True, methods=['post'], url_path='activate-stripe-cc')
|
||||
def activate_stripe_cc(self, request, pk=None):
|
||||
payment_method = self.get_object()
|
||||
try:
|
||||
setup_intent = uncloud_stripe.get_setup_intent(
|
||||
payment_method.stripe_setup_intent_id)
|
||||
except Exception as e:
|
||||
return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
|
||||
|
||||
# Card had been registered, fetching payment method.
|
||||
print(setup_intent)
|
||||
if setup_intent.payment_method:
|
||||
payment_method.stripe_payment_method_id = setup_intent.payment_method
|
||||
payment_method.save()
|
||||
|
||||
return Response({
|
||||
'uuid': payment_method.uuid,
|
||||
'activated': payment_method.active})
|
||||
else:
|
||||
error = 'Could not fetch payment method from stripe. Please try again.'
|
||||
return Response({'error': error})
|
||||
|
||||
@action(detail=True, methods=['post'], url_path='set-as-primary')
|
||||
def set_as_primary(self, request, pk=None):
|
||||
payment_method = self.get_object()
|
||||
payment_method.set_as_primary_for(request.user)
|
||||
|
||||
serializer = self.get_serializer(payment_method)
|
||||
return Response(serializer.data)
|
||||
|
||||
###
|
||||
# Bills and Orders.
|
||||
|
||||
|
|
@ -314,7 +170,7 @@ class BillingAddressViewSet(mixins.CreateModelMixin,
|
|||
return BillingAddressSerializer
|
||||
|
||||
def get_queryset(self):
|
||||
return self.request.user.billingaddress_set.all()
|
||||
return self.request.user.billing_addresses.all()
|
||||
|
||||
def create(self, request):
|
||||
serializer = self.get_serializer(data=request.data)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue