Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(integrations): explain a stripe test-mode oauth code instead of a retry (#125132)

Tom Owersddb559440720
diff --git a/posthog/models/integration/oauth.py b/posthog/models/integration/oauth.py
index b1ae89f7f884..144016df4a3f 100644
--- a/posthog/models/integration/oauth.py
+++ b/posthog/models/integration/oauth.py
@@ -70,14 +70,33 @@ _INVALID_GRANT_MESSAGE = (
"This authorization is no longer valid. Start the connection again and approve access without waiting in between."
)
+_STRIPE_MODE_MISMATCH_MESSAGE = (
+ "Stripe approved this connection in test mode or a sandbox, but PostHog can only connect live mode Stripe accounts. "
+ "Starting the connection again won't fix this. To sync your live data, change Authentication type to "
+ "Restricted API key and use a key you create in live mode."
+)
-def _oauth_error_code(res: requests.Response) -> str | None:
+
+def _oauth_error_field(res: requests.Response, field: str) -> str | None:
try:
body = res.json()
except Exception:
return None
- code = body.get("error") if isinstance(body, dict) else None
- return code if isinstance(code, str) else None
+ value = body.get(field) if isinstance(body, dict) else None
+ return value if isinstance(value, str) else None
+
+
+def _oauth_error_code(res: requests.Response) -> str | None:
+ return _oauth_error_field(res, "error")
+
+
+def _is_stripe_mode_mismatch(kind: str, res: requests.Response) -> bool:
+ # The install link that issued the code fixes its mode, and Stripe redeems it only with the secret
+ # key of that mode. A retry gets a code from the same link, so it fails the same way.
+ if kind != "stripe":
+ return False
+ description = _oauth_error_field(res, "error_description") or ""
+ return "authorization code only supports returning" in description
def _raise_oauth_validation_error(kind: str, res: requests.Response) -> NoReturn:
@@ -88,7 +107,9 @@ def _raise_oauth_validation_error(kind: str, res: requests.Response) -> NoReturn
bare Exception (which surfaces as a 500 with no detail).
"""
if _oauth_error_code(res) == "invalid_grant":
- # The code expired, was already exchanged, or was issued for another account or mode. The
+ if _is_stripe_mode_mismatch(kind, res):
+ raise ValidationError(_STRIPE_MODE_MISMATCH_MESSAGE)
+ # The code expired, was already exchanged, or was issued for another account. The
# provider's description can echo the code itself, so it stays in the logs.
raise ValidationError(_INVALID_GRANT_MESSAGE)
provider_error = _extract_oauth_error_message(res)
diff --git a/posthog/models/test/integration/test_oauth.py b/posthog/models/test/integration/test_oauth.py
index f208107f45cb..81de778adcd6 100644
--- a/posthog/models/test/integration/test_oauth.py
+++ b/posthog/models/test/integration/test_oauth.py
@@ -76,6 +76,8 @@ class TestOauthIntegrationModel(BaseTest):
"LINEAR_APP_CLIENT_SECRET": "linear-client-secret",
"HELPSCOUT_APP_CLIENT_ID": "helpscout-client-id",
"HELPSCOUT_APP_CLIENT_SECRET": "helpscout-client-secret",
+ "STRIPE_APP_CLIENT_ID": "stripe-client-id",
+ "STRIPE_APP_SECRET_KEY": "stripe-secret-key",
}
def create_integration(
@@ -260,6 +262,7 @@ class TestOauthIntegrationModel(BaseTest):
[
(
"json_error_body",
+ "salesforce",
400,
{
"error": "invalid_grant",
@@ -272,6 +275,7 @@ class TestOauthIntegrationModel(BaseTest):
),
(
"json_error_body_other_code",
+ "salesforce",
400,
{"error": "invalid_client", "error_description": "Client authentication failed."},
None,
@@ -281,6 +285,7 @@ class TestOauthIntegrationModel(BaseTest):
),
(
"non_json_error_body",
+ "salesforce",
502,
None,
ValueError("not json"),
@@ -288,12 +293,36 @@ class TestOauthIntegrationModel(BaseTest):
["salesforce"],
[],
),
+ (
+ "stripe_expired_code",
+ "stripe",
+ 400,
+ {"error": "invalid_grant", "error_description": "Authorization code expired: ac_fake_code"},
+ None,
+ '{"error":"invalid_grant","error_description":"Authorization code expired: ac_fake_code"}',
+ ["Start the connection again"],
+ ["ac_fake_code", "Restricted API key"],
+ ),
+ (
+ "stripe_test_mode_code_with_live_key",
+ "stripe",
+ 400,
+ {
+ "error": "invalid_grant",
+ "error_description": "Passed in livemode API key but authorization code only supports returning test keys",
+ },
+ None,
+ '{"error":"invalid_grant","error_description":"Passed in livemode API key but authorization code only supports returning test keys"}',
+ ["test mode", "Restricted API key"],
+ ["Start the connection again", "livemode API key"],
+ ),
]
)
@patch("posthog.models.integration.oauth.requests.post")
def test_oauth_token_exchange_failure_raises_validation_error(
self,
_name,
+ kind,
status_code,
json_return,
json_side_effect,
@@ -316,7 +345,7 @@ class TestOauthIntegrationModel(BaseTest):
with pytest.raises(ValidationError) as e:
OauthIntegration.integration_from_oauth_response(
- "salesforce",
+ kind,
self.team.id,
self.user,
{"code": "code", "state": "next=/projects/test"},