Skip to content

Fixes an issue with duplicate gold subscriptions #4597

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 5, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 12 additions & 8 deletions readthedocs/gold/forms.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
"""Gold subscription forms."""

from __future__ import absolute_import

from builtins import object
from django import forms

from stripe.error import InvalidRequestError
from readthedocs.payments.forms import StripeModelForm, StripeResourceMixin

from .models import LEVEL_CHOICES, GoldUser
Expand Down Expand Up @@ -57,21 +57,25 @@ def get_customer_kwargs(self):

def get_subscription(self):
customer = self.get_customer()
try:
# TODO get the first sub more intelligently
subscriptions = customer.subscriptions.all(limit=5)

# TODO get the first subscription more intelligently
subscriptions = customer.subscriptions.all(limit=5)
if subscriptions.data:
# Update an existing subscription - Stripe prorates by default
subscription = subscriptions.data[0]
subscription.plan = self.cleaned_data['level']
if 'stripe_token' in self.cleaned_data:
if 'stripe_token' in self.cleaned_data and self.cleaned_data['stripe_token']:
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The error was on this line specifically. In the case where the user is swapping their credit card, the stripe_token is present and the API call succeeds and everything is good. In the case where the user is just changing plans, stripe_token is None, the API call fails and the except clause is taken which adds a new subscription.

Because of that possibility of just having a failed API call result in more subscriptions, I rewrote that part of this function.

# Optionally update the card
subscription.source = self.cleaned_data['stripe_token']
subscription.save()
return subscription
except (InvalidRequestError, AttributeError, IndexError):
else:
# Add a new subscription
subscription = customer.subscriptions.create(
plan=self.cleaned_data['level'],
source=self.cleaned_data['stripe_token']
)
return subscription

return subscription

def clear_card_data(self):
super(GoldSubscriptionForm, self).clear_card_data()
Expand Down