Skip to content

Instantly share code, notes, and snippets.

@zetas
Created February 16, 2014 02:20
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/9028337 to your computer and use it in GitHub Desktop.
Save zetas/9028337 to your computer and use it in GitHub Desktop.
Too much logic in a post method? You're probably right.
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 user.stripe_subscription_id is None:
subscription = customer.subscriptions.create(plan=form.cleaned_data['sub_type'], quantity=quantity)
user.stripe_subscription_id = subscription.id
user.save()
else:
subscription = customer.subscriptions.retrieve(user.stripe_subscription_id)
original_plan = subscription.plan
selected_plan = form.cleaned_data['sub_type']
if original_plan == selected_plan:
original_quantity = subscription.quantity
subscription.quantity = original_quantity + quantity
subscription.save()
else:
subscription.delete()
newsub = customer.subscriptions.create(plan=selected_plan, quantity=quantity)
user.stripe_subscription_id = newsub.id
user.save()
# Update User Data
user.first_name = form.cleaned_data['first_name']
user.last_name = form.cleaned_data['last_name']
user.company_name = form.cleaned_data.get('company_name', '')
user.address = form.cleaned_data['address']
user.city = form.cleaned_data['city']
user.state = form.cleaned_data['state']
user.zip = form.cleaned_data['zipcode']
user.country = form.cleaned_data['country']
user.cc_type = form.cleaned_data['cc_type']
user.last_4 = form.cleaned_data['last_4']
user.save()
return redirect('account:index')
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