Skip to content
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

Fix stripe subscription upgrade failures #831

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
68 changes: 68 additions & 0 deletions api/internal/tests/views/test_account_viewset.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ def __init__(self, subscription_params):
if customer_coupon:
self.customer["discount"] = {"coupon": customer_coupon}

pending_update = subscription_params.get("pending_update")
if pending_update:
self.pending_update = pending_update

def __getitem__(self, key):
return getattr(self, key)

Expand Down Expand Up @@ -755,6 +759,7 @@ def test_update_can_upgrade_to_paid_plan_for_existing_customer_and_set_plan_info
}

retrieve_subscription_mock.return_value = MockSubscription(subscription_params)
modify_subscription_mock.return_value = MockSubscription(subscription_params)

response = self._update(
kwargs={
Expand All @@ -774,6 +779,69 @@ def test_update_can_upgrade_to_paid_plan_for_existing_customer_and_set_plan_info
assert self.current_owner.plan == desired_plan["value"]
assert self.current_owner.plan_user_count == desired_plan["quantity"]

@patch("services.billing.stripe.Subscription.retrieve")
@patch("services.billing.stripe.Subscription.modify")
def test_upgrade_payment_failure(
self, modify_subscription_mock, retrieve_subscription_mock
):
desired_plan = {"value": PlanName.CODECOV_PRO_MONTHLY.value, "quantity": 12}
self.current_owner.stripe_customer_id = "flsoe"
self.current_owner.stripe_subscription_id = "djfos"
self.current_owner.plan = PlanName.CODECOV_PRO_MONTHLY.value
self.current_owner.plan_user_count = 8
self.current_owner.delinquent = False
self.current_owner.save()

f = open("./services/tests/samples/stripe_invoice.json")

default_payment_method = {
"card": {
"brand": "visa",
"exp_month": 12,
"exp_year": 2024,
"last4": "abcd",
"should be": "removed",
}
}
subscription_params = {
"default_payment_method": default_payment_method,
"latest_invoice": json.load(f)["data"][0],
"schedule_id": None,
"collection_method": "charge_automatically",
"tax_ids": None,
"pending_update": {
"expires_at": 1571194285,
"subscription_items": [
{
"id": "si_09IkI4u3ZypJUk5onGUZpe8O",
"price": "price_CBb6IXqvTLXp3f",
}
],
},
}

retrieve_subscription_mock.return_value = MockSubscription(subscription_params)
modify_subscription_mock.return_value = MockSubscription(subscription_params)

response = self._update(
kwargs={
"service": self.current_owner.service,
"owner_username": self.current_owner.username,
},
data={"plan": desired_plan},
)

modify_subscription_mock.assert_called_once()

assert response.status_code == status.HTTP_200_OK
assert response.data["plan"]["value"] == desired_plan["value"]
assert response.data["plan"]["quantity"] == 8

self.current_owner.refresh_from_db()
assert self.current_owner.plan == desired_plan["value"]
assert self.current_owner.plan_user_count == 8
assert self.current_owner.delinquent == True

def test_update_requires_quantity_if_updating_to_paid_plan(self):
desired_plan = {"value": PlanName.CODECOV_PRO_YEARLY.value}
response = self._update(
Expand Down
34 changes: 34 additions & 0 deletions billing/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,40 @@ def test_customer_subscription_updated_sets_free_and_deactivates_all_repos_if_in
invoice_settings={"default_payment_method": "pm_1LhiRsGlVGuVgOrkQguJXdeV"},
)

def test_customer_subscription_updated_payment_failed(self):
self.owner.delinquent = False
self.owner.save()

self._send_event(
payload={
"type": "customer.subscription.updated",
"data": {
"object": {
"id": self.owner.stripe_subscription_id,
"customer": self.owner.stripe_customer_id,
"plan": {"id": "?"},
"metadata": {"obo_organization": self.owner.ownerid},
"quantity": 20,
"status": "active",
"schedule": None,
"default_payment_method": "pm_1LhiRsGlVGuVgOrkQguJXdeV",
"pending_update": {
"expires_at": 1571194285,
"subscription_items": [
{
"id": "si_09IkI4u3ZypJUk5onGUZpe8O",
"price": "price_CBb6IXqvTLXp3f",
}
],
},
}
},
}
)

self.owner.refresh_from_db()
assert self.owner.delinquent == True

@patch("services.billing.stripe.PaymentMethod.attach")
@patch("services.billing.stripe.Customer.modify")
def test_customer_subscription_updated_sets_fields_on_success(
Expand Down
23 changes: 15 additions & 8 deletions billing/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,9 +222,20 @@ def customer_subscription_updated(self, subscription: stripe.Subscription) -> No
stripe_customer_id=subscription.customer,
)

indication_of_payment_failure = getattr(subscription, "pending_update", None)
if indication_of_payment_failure:
# payment failed, raise this to user by setting as delinquent
owner.delinquent = True
owner.save()
log.info(
f"Stripe subscription upgrade failed for owner {owner.ownerid}",
extra=dict(pending_update=indication_of_payment_failure),
)
return

# Properly attach the payment method on the customer
# This hook will be called after a checkout session completes, updating the subscription created
# with it
# This hook will be called after a checkout session completes,
# updating the subscription created with it
default_payment_method = subscription.default_payment_method
if default_payment_method and owner.stripe_customer_id is not None:
stripe.PaymentMethod.attach(
Expand All @@ -235,11 +246,9 @@ def customer_subscription_updated(self, subscription: stripe.Subscription) -> No
invoice_settings={"default_payment_method": default_payment_method},
)

subscription_schedule_id = subscription.schedule
plan_service = PlanService(current_org=owner)

# Only update if there isn't a scheduled subscription
if not subscription_schedule_id:
if not subscription.schedule:
plan_service = PlanService(current_org=owner)
if subscription.status == "incomplete_expired":
log.info(
"Subscription status updated to incomplete_expired, cancelling to free",
Expand Down Expand Up @@ -267,9 +276,7 @@ def customer_subscription_updated(self, subscription: stripe.Subscription) -> No
return

plan_name = settings.STRIPE_PLAN_VALS[sub_item_plan_id]

plan_service.update_plan(name=plan_name, user_count=subscription.quantity)

log.info(
"Successfully updated customer subscription",
extra=dict(
Expand Down
33 changes: 24 additions & 9 deletions services/billing.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ def modify_subscription(self, owner, desired_plan):
log.info(
f"Updating Stripe subscription for owner {owner.ownerid} to {desired_plan['value']} by user #{self.requesting_user.ownerid}"
)
stripe.Subscription.modify(
subscription = stripe.Subscription.modify(
owner.stripe_subscription_id,
cancel_at_period_end=False,
items=[
Expand All @@ -237,16 +237,31 @@ def modify_subscription(self, owner, desired_plan):
],
metadata=self._get_checkout_session_and_subscription_metadata(owner),
proration_behavior=proration_behavior,
payment_behavior="pending_if_incomplete",
)

plan_service = PlanService(current_org=owner)
plan_service.update_plan(
name=desired_plan["value"], user_count=desired_plan["quantity"]
)

log.info(
f"Stripe subscription modified successfully for owner {owner.ownerid} by user #{self.requesting_user.ownerid}"
f"Stripe subscription upgrade attempted for owner {owner.ownerid} by user #{self.requesting_user.ownerid}"
)
indication_of_payment_failure = getattr(
subscription, "pending_update", None
)
if indication_of_payment_failure:
# payment failed, raise this to user by setting as delinquent
owner.delinquent = True
owner.save()
log.info(
f"Stripe subscription upgrade failed for owner {owner.ownerid} by user #{self.requesting_user.ownerid}",
extra=dict(pending_update=indication_of_payment_failure),
)
else:
# payment successful
plan_service = PlanService(current_org=owner)
plan_service.update_plan(
name=desired_plan["value"], user_count=desired_plan["quantity"]
)
log.info(
f"Stripe subscription upgraded successfully for owner {owner.ownerid} by user #{self.requesting_user.ownerid}"
)
else:
if not subscription_schedule_id:
schedule = stripe.SubscriptionSchedule.create(
Expand Down Expand Up @@ -431,7 +446,7 @@ def update_payment_method(self, owner: Owner, payment_method):
owner.stripe_subscription_id, default_payment_method=payment_method
)
log.info(
"Successfully updated payment method for owner {owner.ownerid} by user #{self.requesting_user.ownerid}",
f"Successfully updated payment method for owner {owner.ownerid} by user #{self.requesting_user.ownerid}",
extra=dict(
owner_id=owner.ownerid,
user_id=self.requesting_user.ownerid,
Expand Down
Loading
Loading