Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(backend): bill Pro→Max upgrades immediately with payment failure rollback (#13003)

Zamil Majdye56ed9161a92
diff --git a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py b/autogpt_platform/backend/backend/api/features/subscription_routes_test.py
index 681d53023f..aad1bbab5c 100644
--- a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/subscription_routes_test.py
@@ -445,7 +445,7 @@ def test_update_subscription_tier_currency_mismatch_returns_422(
side_effect=stripe.InvalidRequestError(
"The price specified only supports `usd`. This doesn't match the"
" expected currency: `gbp`.",
- param="phases",
+ param="currency",
),
)
@@ -1207,6 +1207,145 @@ def test_update_subscription_tier_target_without_ld_price_returns_422(
modify_mock.assert_not_awaited()
+def test_update_subscription_tier_pro_to_max_card_declined_returns_402(
+ client: fastapi.testclient.TestClient,
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """Pro→Max upgrade where Stripe raises CardError must return HTTP 402.
+
+ The "tier stays on Pro after CardError" invariant is verified at the
+ credit.py layer (see test_modify_stripe_subscription_for_tier_pro_to_max
+ _card_decline_does_not_flip_tier); this test covers the route's HTTP
+ surface only.
+ """
+ mock_user = Mock()
+ mock_user.subscription_tier = SubscriptionTier.PRO
+
+ mocker.patch(
+ "backend.api.features.v1.get_user_by_id",
+ new_callable=AsyncMock,
+ return_value=mock_user,
+ )
+ mocker.patch(
+ "backend.api.features.v1.is_feature_enabled",
+ new_callable=AsyncMock,
+ return_value=True,
+ )
+ modify_mock = mocker.patch(
+ "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ new_callable=AsyncMock,
+ side_effect=stripe.CardError(
+ "Your card was declined.", param="card", code="card_declined"
+ ),
+ )
+
+ response = client.post(
+ "/credits/subscription",
+ json={
+ "tier": "MAX",
+ "success_url": f"{TEST_FRONTEND_ORIGIN}/success",
+ "cancel_url": f"{TEST_FRONTEND_ORIGIN}/cancel",
+ },
+ )
+
+ assert response.status_code == 402
+ assert "card was declined" in response.json()["detail"].lower()
+ modify_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.MAX)
+
+
+def test_update_subscription_tier_pro_to_max_authentication_required_returns_402(
+ client: fastapi.testclient.TestClient,
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """SCA-required cards raise CardError(code='authentication_required'). The
+ handler must surface a different message than the plain decline path so EU
+ users don't try a different card when their existing one only needs 3DS."""
+ mock_user = Mock()
+ mock_user.subscription_tier = SubscriptionTier.PRO
+
+ mocker.patch(
+ "backend.api.features.v1.get_user_by_id",
+ new_callable=AsyncMock,
+ return_value=mock_user,
+ )
+ mocker.patch(
+ "backend.api.features.v1.is_feature_enabled",
+ new_callable=AsyncMock,
+ return_value=True,
+ )
+ mocker.patch(
+ "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ new_callable=AsyncMock,
+ side_effect=stripe.CardError(
+ "Your card was declined.",
+ param="card",
+ code="authentication_required",
+ ),
+ )
+
+ response = client.post(
+ "/credits/subscription",
+ json={
+ "tier": "MAX",
+ "success_url": f"{TEST_FRONTEND_ORIGIN}/success",
+ "cancel_url": f"{TEST_FRONTEND_ORIGIN}/cancel",
+ },
+ )
+
+ assert response.status_code == 402
+ detail = response.json()["detail"].lower()
+ assert "authentication" in detail
+ # Must NOT use the generic decline copy — that would tell the user to
+ # change cards when the card itself is fine.
+ assert "card was declined" not in detail
+
+
+def test_update_subscription_tier_pro_to_max_no_payment_method_returns_402(
+ client: fastapi.testclient.TestClient,
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """Customer with no default payment method: error_if_incomplete makes Stripe
+ raise InvalidRequestError (not CardError). The handler must map that to 402
+ so the UI prompts to add a card instead of the generic 502 outage copy."""
+ mock_user = Mock()
+ mock_user.subscription_tier = SubscriptionTier.PRO
+
+ mocker.patch(
+ "backend.api.features.v1.get_user_by_id",
+ new_callable=AsyncMock,
+ return_value=mock_user,
+ )
+ mocker.patch(
+ "backend.api.features.v1.is_feature_enabled",
+ new_callable=AsyncMock,
+ return_value=True,
+ )
+ mocker.patch(
+ "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ new_callable=AsyncMock,
+ side_effect=stripe.InvalidRequestError(
+ "This customer has no attached payment source or default payment"
+ " method. Please consider adding a default payment method.",
+ param="default_payment_method",
+ code="resource_missing",
+ ),
+ )
+
+ response = client.post(
+ "/credits/subscription",
+ json={
+ "tier": "MAX",
+ "success_url": f"{TEST_FRONTEND_ORIGIN}/success",
+ "cancel_url": f"{TEST_FRONTEND_ORIGIN}/cancel",
+ },
+ )
+
+ assert response.status_code == 402
+ detail = response.json()["detail"].lower()
+ assert "no payment method" in detail
+ assert "add a payment method" in detail
+
+
def test_update_subscription_tier_paid_to_paid_stripe_error_returns_502(
client: fastapi.testclient.TestClient,
mocker: pytest_mock.MockFixture,
diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.py
index c48c6f1d45..03e835d8c5 100644
--- a/autogpt_platform/backend/backend/api/features/v1.py
+++ b/autogpt_platform/backend/backend/api/features/v1.py
@@ -1003,15 +1003,74 @@ async def update_subscription_tier(
return await get_subscription_status(user_id)
except ValueError as e:
raise HTTPException(status_code=422, detail=str(e))
+ except stripe.CardError as e:
+ # Auto-charge failed under payment_behavior=error_if_incomplete: the
+ # modify was rolled back, so 402 lets the UI prompt for a new card or
+ # surface SCA. authentication_required means the card is fine but the
+ # bank wants 3DS — different message so the user doesn't try a new card.
+ if e.code == "authentication_required":
+ logger.warning(
+ "SCA required on subscription upgrade for user %s: %s", user_id, e
+ )
+ raise HTTPException(
+ status_code=402,
+ detail=(
+ "Your bank requires extra authentication for this charge."
+ " The plan was not changed; please retry from the billing"
+ " portal so you can complete authentication, or contact"
+ " support."
+ ),
+ )
+ logger.warning(
+ "Card declined on subscription upgrade for user %s: %s", user_id, e
+ )
+ raise HTTPException(
+ status_code=402,
+ detail=(
+ "Your card was declined. The plan was not changed; please"
+ " update your payment method and try again."
+ ),
+ )
except stripe.InvalidRequestError as e:
+ # Stripe's e.param is documented as nullable, so we match by typed
+ # field first and fall back to substring when param is absent.
+ msg_lower = (e.user_message or str(e)).lower()
+ # "No payment method" presents as InvalidRequestError (not CardError)
+ # when error_if_incomplete fires with no default PM. Stripe signals
+ # this with code=resource_missing/missing — sometimes with a typed
+ # param, sometimes without (the raw "no attached payment source"
+ # message has empty param). Map it to 402 either way.
+ if e.code in {"resource_missing", "missing"} and (
+ e.param
+ in {
+ "default_payment_method",
+ "payment_method",
+ "invoice_settings.default_payment_method",
+ }
+ or "no attached payment source" in msg_lower
+ or "default payment method" in msg_lower
+ or "no payment method" in msg_lower
+ ):
+ logger.warning(
+ "No payment method on subscription upgrade for user %s: %s",
+ user_id,
+ e,
+ )
+ raise HTTPException(
+ status_code=402,
+ detail=(
+ "No payment method on file. The plan was not changed;"
+ " please add a payment method and try again."
+ ),
+ )
# Stripe rejects schedule modify when phases mix currencies, e.g. the
# active sub was checked out in GBP but the target tier's Price is
- # USD-only. 502 reads as outage; surface a 422 with a specific message
- # so the user/admin can see what to fix in Stripe.
- msg = str(e)
- if "currency" in msg.lower():
+ # USD-only. e.param is "currency" on the schedule API but may be
+ # "phases" or absent on older error shapes — substring fallback keeps
+ # the 422 firing instead of dropping to the generic 502.
+ if e.param == "currency" or "currency" in msg_lower:
logger.warning(
- "Currency mismatch on tier change for user %s: %s", user_id, msg
+ "Currency mismatch on tier change for user %s: %s", user_id, e
)
raise HTTPException(
status_code=422,
diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.py
index 43608642b5..86635b6753 100644
--- a/autogpt_platform/backend/backend/data/credit.py
+++ b/autogpt_platform/backend/backend/data/credit.py
@@ -1842,9 +1842,12 @@ async def modify_stripe_subscription_for_tier(
# as part of the upgrade — the user is explicitly choosing to stay on a
# paid tier. Without this, the sub would be upgraded AND still cancelled
# at period end, leaving a confusing dual state.
+ # always_invoice + error_if_incomplete bill the prorated upgrade now and
+ # roll the modify back if the auto-charge fails (instead of deferring).
modify_kwargs: dict = {
"items": [{"id": items[0].id, "price": price_id}],
- "proration_behavior": "create_prorations",
+ "proration_behavior": "always_invoice",
+ "payment_behavior": "error_if_incomplete",
}
if sub.cancel_at_period_end:
modify_kwargs["cancel_at_period_end"] = False
diff --git a/autogpt_platform/backend/backend/data/credit_subscription_test.py b/autogpt_platform/backend/backend/data/credit_subscription_test.py
index 69d59e15f4..fb7e204474 100644
--- a/autogpt_platform/backend/backend/data/credit_subscription_test.py
+++ b/autogpt_platform/backend/backend/data/credit_subscription_test.py
@@ -1836,7 +1836,8 @@ async def test_modify_stripe_subscription_for_tier_modifies_existing_sub():
mock_modify.assert_called_once_with(
"sub_abc",
items=[{"id": "si_abc", "price": "price_pro_monthly"}],
- proration_behavior="create_prorations",
+ proration_behavior="always_invoice",
+ payment_behavior="error_if_incomplete",
)
mock_set_tier.assert_awaited_once_with("user-1", SubscriptionTier.PRO)
@@ -1894,7 +1895,8 @@ async def test_modify_stripe_subscription_for_tier_clears_cancel_at_period_end_o
mock_modify.assert_called_once_with(
"sub_upgrading",
items=[{"id": "si_abc", "price": "price_biz_monthly"}],
- proration_behavior="create_prorations",
+ proration_behavior="always_invoice",
+ payment_behavior="error_if_incomplete",
cancel_at_period_end=False,
)
mock_set_tier.assert_awaited_once_with("user-1", SubscriptionTier.BUSINESS)
@@ -2118,11 +2120,127 @@ async def test_modify_stripe_subscription_for_tier_upgrade_immediate_proration()
mock_modify.assert_called_once_with(
"sub_pro",
items=[{"id": "si_pro", "price": "price_biz_monthly"}],
- proration_behavior="create_prorations",
+ proration_behavior="always_invoice",
+ payment_behavior="error_if_incomplete",
)
mock_schedule_create.assert_not_called()
+async def test_modify_stripe_subscription_for_tier_pro_to_max_bills_immediately():
+ """Pro→Max upgrade calls Stripe with always_invoice + error_if_incomplete so the
+ user is charged the prorated amount immediately rather than at next cycle, and
+ the DB tier flip lands once Stripe confirms payment success."""
+ mock_sub = stripe.Subscription.construct_from(
+ {
+ "id": "sub_pro",
+ "items": {"data": [{"id": "si_pro", "price": {"id": "price_pro_monthly"}}]},
+ "schedule": None,
+ "cancel_at_period_end": False,
+ },
+ "k",
+ )
+ mock_list = MagicMock()
+ mock_list.data = [mock_sub]
+
+ mock_user = MagicMock(spec=User)
+ mock_user.stripe_customer_id = "cus_abc"
+ mock_user.subscription_tier = SubscriptionTier.PRO
+
+ with (
+ patch(
+ "backend.data.credit.get_subscription_price_id",
+ new_callable=AsyncMock,
+ return_value="price_max_monthly",
+ ),
+ patch(
+ "backend.data.credit.get_user_by_id",
+ new_callable=AsyncMock,
+ return_value=mock_user,
+ ),
+ patch(
+ "backend.data.credit.stripe.Subscription.list_async",
+ new_callable=AsyncMock,
+ return_value=mock_list,
+ ),
+ patch(
+ "backend.data.credit.stripe.Subscription.modify_async",
+ new_callable=AsyncMock,
+ ) as mock_modify,
+ patch(
+ "backend.data.credit.set_subscription_tier",
+ new_callable=AsyncMock,
+ ) as mock_set_tier,
+ ):
+ result = await modify_stripe_subscription_for_tier(
+ "user-1", SubscriptionTier.MAX
+ )
+
+ assert result is True
+ mock_modify.assert_called_once_with(
+ "sub_pro",
+ items=[{"id": "si_pro", "price": "price_max_monthly"}],
+ proration_behavior="always_invoice",
+ payment_behavior="error_if_incomplete",
+ )
+ mock_set_tier.assert_awaited_once_with("user-1", SubscriptionTier.MAX)
+
+
+async def test_modify_stripe_subscription_for_tier_pro_to_max_card_decline_does_not_flip_tier():
+ """Pro→Max upgrade where Stripe raises CardError (auto-charge declined under
+ payment_behavior=error_if_incomplete): the function must propagate the error
+ AND must not call set_subscription_tier — the user stays on Pro."""
+ mock_sub = stripe.Subscription.construct_from(
+ {
+ "id": "sub_pro",
+ "items": {"data": [{"id": "si_pro", "price": {"id": "price_pro_monthly"}}]},
+ "schedule": None,
+ "cancel_at_period_end": False,
+ },
+ "k",
+ )
+ mock_list = MagicMock()
+ mock_list.data = [mock_sub]
+
+ mock_user = MagicMock(spec=User)
+ mock_user.stripe_customer_id = "cus_abc"
+ mock_user.subscription_tier = SubscriptionTier.PRO
+
+ with (
+ patch(
+ "backend.data.credit.get_subscription_price_id",
+ new_callable=AsyncMock,
+ return_value="price_max_monthly",
+ ),
+ patch(
+ "backend.data.credit.get_user_by_id",
+ new_callable=AsyncMock,
+ return_value=mock_user,
+ ),
+ patch(
+ "backend.data.credit.stripe.Subscription.list_async",
+ new_callable=AsyncMock,
+ return_value=mock_list,
+ ),
+ patch(
+ "backend.data.credit.stripe.Subscription.modify_async",
+ new_callable=AsyncMock,
+ side_effect=stripe.CardError(
+ "Your card was declined.", param="card", code="card_declined"
+ ),
+ ),
+ patch(
+ "backend.data.credit.set_subscription_tier",
+ new_callable=AsyncMock,
+ ) as mock_set_tier,
+ ):
+ with pytest.raises(stripe.CardError):
+ await modify_stripe_subscription_for_tier("user-1", SubscriptionTier.MAX)
+
+ mock_set_tier.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_release_pending_subscription_schedule_releases_downgrade_schedule():
"""release_pending_subscription_schedule releases the Stripe schedule if one is attached."""
@@ -3015,7 +3133,8 @@ async def test_upgrade_releases_pending_schedule():
mock_modify.assert_called_once_with(
"sub_pro",
items=[{"id": "si_pro", "price": "price_biz_monthly"}],
- proration_behavior="create_prorations",
+ proration_behavior="always_invoice",
+ payment_behavior="error_if_incomplete",
)