Skip to content

Instantly share code, notes, and snippets.

@zetas
Created February 16, 2014 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zetas/9036196 to your computer and use it in GitHub Desktop.
Save zetas/9036196 to your computer and use it in GitHub Desktop.
Biggest view ever.
class UpgradeView(View):
form_class = CheckoutForm
template = 'account/checkout.html'
def create_sub(self, user, customer, plan, quantity):
subscription = customer.subscriptions.create(plan=plan, quantity=quantity)
user.stripe_subscription_id = subscription.id
user.save()
def get(self, request, *args, **kwargs):
return render(request, self.template, {'form': self.form_class(), 'stripe_key': settings.STRIPE_PUBLISHABLE})
def post(self, request, *args, **kwargs):
form = CheckoutForm(request.POST)
if form.is_valid():
user = request.user
stripe.api_key = settings.STRIPE_SECRET
token = form.cleaned_data['stripe_token']
quantity = form.cleaned_data.get('quantity', 1)
customer = stripe.Customer.retrieve(user.stripe_customer_id)
customer.card = token
customer.save()
if form.cleaned_data['sub_type'] == 'monthly':
license_range = 30
else:
license_range = 365
if user.stripe_subscription_id is None:
self.create_sub(user, customer, form.cleaned_data['sub_type'], quantity)
if user.account_type == 'personal':
license = License.objects.create_license(user, license_range, user)
license.save()
else:
License.objects.create_multiple_licenses(quantity, user, license_range)
else:
subscription = customer.subscriptions.retrieve(user.stripe_subscription_id)
original_plan = subscription.plan.id
selected_plan = form.cleaned_data['sub_type']
if original_plan == selected_plan:
original_quantity = subscription.quantity
subscription.quantity = original_quantity + quantity
subscription.save()
License.objects.create_multiple_licenses(quantity, user, license_range)
else:
License.objects.delete_user_licenses(user)
subscription.delete()
self.create_sub(user, customer, form.cleaned_data['sub_type'], quantity)
License.objects.create_multiple_licenses(quantity, user, license_range)
# Update User Data
for key in form.cleaned_data.keys():
if hasattr(user, key):
setattr(user, key, form.cleaned_data[key])
user.save()
return redirect('account:checkout_success')
return render(request, self.template, {'form': form, 'stripe_key': settings.STRIPE_PUBLISHABLE})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment