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(warehouse-sources): surface Shopify's real token error (#83007)

posthog[bot]4e77fb6dd686
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/shopify.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/shopify.py
index 66d7c15e478b..548641d58a33 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/shopify.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/shopify.py
@@ -5,10 +5,13 @@ from collections.abc import Iterator
from typing import Any
import requests
+import structlog
from requests.exceptions import ChunkedEncodingError
from structlog.types import FilteringBoundLogger
from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -32,18 +35,37 @@ from .constants import (
SHOPIFY_PAGE_SIZE_OVERRIDES,
)
+logger = structlog.get_logger(__name__)
+
# Resume phases for the shopify source. "all" is the non-incremental branch;
# "earliest" and "latest" are the two incremental sweeps in shopify_source.get_rows.
PHASE_ALL = "all"
PHASE_EARLIEST = "earliest"
PHASE_LATEST = "latest"
-# Raised when Shopify's OAuth token endpoint returns a 4xx — the app credentials are
-# invalid or the app was uninstalled, so re-auth is the only fix. `ShopifySource.
-# get_non_retryable_errors` matches on this exact text to fail the job fast.
+# Raised when Shopify's OAuth token endpoint returns a 4xx that we can't attribute to a more
+# specific cause below. The app credentials are invalid or revoked, so re-entering them is the
+# only fix. `ShopifySource.get_non_retryable_errors` matches on this exact text to fail the job
+# fast. The raised message also carries Shopify's own `error`/`error_description` (see
+# `_oauth_error_detail`) so support can see what Shopify objected to.
SHOPIFY_ACCESS_TOKEN_AUTH_ERROR = (
- "Failed to retrieve Shopify access token: the app credentials are invalid or the "
- "app was uninstalled. Please reconnect your Shopify integration."
+ "Shopify rejected your app credentials. Check the client ID and secret in your Shopify app and re-enter them here."
+)
+
+# Raised on a 4xx whose body reports `error: invalid_client` — the client ID or secret does not
+# match a Shopify app. Surfaced separately so the message names the field to fix.
+SHOPIFY_ACCESS_TOKEN_INVALID_CLIENT_ERROR = (
+ "Shopify rejected your app credentials (invalid_client). Check that the client ID and "
+ "secret both come from the same Shopify app, then re-enter them here."
+)
+
+# Raised on a 4xx whose body reports `error: unsupported_grant_type` — the app can't use the
+# client_credentials grant PostHog mints tokens with. This is the legacy store-admin custom app
+# type; PostHog needs a Dev Dashboard app. Surfaced separately so the message points at the fix.
+SHOPIFY_ACCESS_TOKEN_UNSUPPORTED_GRANT_ERROR = (
+ "This Shopify app does not support the sign-in method PostHog uses "
+ "(unsupported_grant_type). Create a Dev Dashboard app by following the PostHog Shopify "
+ "docs, then enter its client ID and secret."
)
# Raised when the OAuth token endpoint returns 404 — there is no store at
@@ -325,6 +347,48 @@ def normalize_store_id(raw: str) -> str:
return store_id
+@frozen
+class _OAuthError:
+ code: str | None
+ description: str | None
+
+
+def _parse_oauth_error(response: requests.Response) -> _OAuthError:
+ """Shopify's OAuth token endpoint returns `{"error": ..., "error_description": ...}` on a 4xx.
+ An edge or proxy can return non-JSON (e.g. an HTML error page) instead, so parse defensively
+ and leave the fields None when the body has no usable error code."""
+ try:
+ body = response.json()
+ except ValueError:
+ return _OAuthError(code=None, description=None)
+ if not isinstance(body, dict):
+ return _OAuthError(code=None, description=None)
+ error = body.get("error")
+ description = body.get("error_description")
+ return _OAuthError(
+ code=error if isinstance(error, str) else None,
+ description=description if isinstance(description, str) else None,
+ )
+
+
+def _access_token_auth_error_message(error_code: str | None) -> str:
+ """The user-facing message for a token-endpoint 4xx, chosen from Shopify's `error` code."""
+ if error_code == "invalid_client":
+ return SHOPIFY_ACCESS_TOKEN_INVALID_CLIENT_ERROR
+ if error_code == "unsupported_grant_type":
+ return SHOPIFY_ACCESS_TOKEN_UNSUPPORTED_GRANT_ERROR
+ return SHOPIFY_ACCESS_TOKEN_AUTH_ERROR
+
+
+def _oauth_error_detail(error: _OAuthError, status_code: int) -> str:
+ """Shopify's raw error appended to the raised message so support can see what Shopify said."""
+ if error.code and error.description:
+ return f"Shopify {error.code}: {error.description}, HTTP {status_code}"
+ if error.code:
+ return f"Shopify {error.code}, HTTP {status_code}"
+ return f"HTTP {status_code}"
+
+
@retry(
# A transient TLS/connection drop on the token endpoint (e.g. SSL EOF, proxy/egress hiccup,
# connect/read timeout) surfaces from `post` as requests ConnectionError/Timeout — SSLError
@@ -362,10 +426,21 @@ def _get_shopify_access_token(shopify_store_id: str, shopify_client_id: str, sho
# instead of telling them their credentials are bad.
if access_res.status_code == 404:
raise Exception(f"{SHOPIFY_STORE_NOT_FOUND_ERROR} (HTTP 404)")
- # Any other 4xx means the app credentials are invalid/revoked (e.g. the app was
- # uninstalled) — re-auth is the only fix, so surface a non-retryable message.
+ # Any other 4xx means the app credentials are invalid/revoked — re-auth is the only fix,
+ # so surface a non-retryable message. Read Shopify's own `error`/`error_description` so
+ # the user gets the specific cause and support can see what Shopify rejected.
if 400 <= access_res.status_code < 500 and access_res.status_code != 429:
- raise Exception(f"{SHOPIFY_ACCESS_TOKEN_AUTH_ERROR} (HTTP {access_res.status_code})")
+ oauth_error = _parse_oauth_error(access_res)
+ logger.warning(
+ "Shopify OAuth token request failed",
+ store_id=shopify_store_id,
+ status_code=access_res.status_code,
+ shopify_error=oauth_error.code,
+ shopify_error_description=oauth_error.description,
+ )
+ message = _access_token_auth_error_message(oauth_error.code)
+ detail = _oauth_error_detail(oauth_error, access_res.status_code)
+ raise Exception(f"{message} ({detail})")
# 429 (rate limit) and 5xx (e.g. a 502 Bad Gateway from Shopify's edge) are transient —
# retry locally with backoff instead of failing the import, mirroring the GraphQL path.
raise ShopifyRetryableError(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/source.py
index 3b7a25e9a2d8..8c22da93435c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/source.py
@@ -28,6 +28,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.shopify.co
from products.warehouse_sources.backend.temporal.data_imports.sources.shopify.settings import ENDPOINT_CONFIGS
from products.warehouse_sources.backend.temporal.data_imports.sources.shopify.shopify import (
SHOPIFY_ACCESS_TOKEN_AUTH_ERROR,
+ SHOPIFY_ACCESS_TOKEN_INVALID_CLIENT_ERROR,
+ SHOPIFY_ACCESS_TOKEN_UNSUPPORTED_GRANT_ERROR,
SHOPIFY_GRAPHQL_ACCESS_DENIED_ERROR,
SHOPIFY_GRAPHQL_UNAUTHORIZED_ERROR_MATCH,
SHOPIFY_GRAPHQL_UNAUTHORIZED_ERROR_MESSAGE,
@@ -66,8 +68,13 @@ class ShopifySource(ResumableSource[ShopifySourceConfig, ShopifyResumeConfig]):
def get_non_retryable_errors(self) -> dict[str, str | None]:
return {
# 4xx from Shopify's OAuth token endpoint — invalid/revoked app credentials.
- # Retrying cannot recover; the user must reconnect the integration.
+ # Retrying cannot recover; the user must re-enter valid credentials.
SHOPIFY_ACCESS_TOKEN_AUTH_ERROR: SHOPIFY_ACCESS_TOKEN_AUTH_ERROR,
+ # 4xx `invalid_client` — the client ID or secret does not match a Shopify app.
+ SHOPIFY_ACCESS_TOKEN_INVALID_CLIENT_ERROR: SHOPIFY_ACCESS_TOKEN_INVALID_CLIENT_ERROR,
+ # 4xx `unsupported_grant_type` — the app can't use the client_credentials grant, so
+ # the user needs a Dev Dashboard app instead of a legacy custom app.
+ SHOPIFY_ACCESS_TOKEN_UNSUPPORTED_GRANT_ERROR: SHOPIFY_ACCESS_TOKEN_UNSUPPORTED_GRANT_ERROR,
# 404 from the same endpoint — no store at this subdomain. Retrying cannot
# recover; the user must correct the store id.
SHOPIFY_STORE_NOT_FOUND_ERROR: SHOPIFY_STORE_NOT_FOUND_ERROR,
@@ -106,7 +113,11 @@ class ShopifySource(ResumableSource[ShopifySourceConfig, ShopifyResumeConfig]):
name=SchemaExternalDataSourceType.SHOPIFY,
category=DataWarehouseSourceCategory.E_COMMERCE,
iconPath="/static/services/shopify.png",
- caption="""Enter your Shopify credentials to automatically pull your Shopify data into the PostHog Data warehouse.""",
+ caption=(
+ "Create a Shopify Dev Dashboard app, then enter its client ID and secret here to "
+ "pull your Shopify data into the PostHog Data warehouse. The docs walk through the "
+ "app setup steps."
+ ),
docsUrl="https://posthog.com/docs/data-warehouse/sources/shopify",
fields=cast(
list[FieldType],
@@ -136,7 +147,7 @@ class ShopifySource(ResumableSource[ShopifySourceConfig, ShopifyResumeConfig]):
label="Secret",
type=SourceFieldInputConfigType.PASSWORD,
required=True,
- placeholder="shpss_...",
+ placeholder="client-secret",
secret=True,
),
],
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/tests/test_access_token.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/tests/test_access_token.py
index 67f4bc2cfc31..9b3ed4106113 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/tests/test_access_token.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/tests/test_access_token.py
@@ -5,6 +5,8 @@ from requests.exceptions import ChunkedEncodingError, SSLError
from products.warehouse_sources.backend.temporal.data_imports.sources.shopify.shopify import (
SHOPIFY_ACCESS_TOKEN_AUTH_ERROR,
+ SHOPIFY_ACCESS_TOKEN_INVALID_CLIENT_ERROR,
+ SHOPIFY_ACCESS_TOKEN_UNSUPPORTED_GRANT_ERROR,
SHOPIFY_STORE_NOT_FOUND_ERROR,
ShopifyRetryableError,
_get_shopify_access_token,
@@ -46,6 +48,31 @@ def test_get_access_token_4xx_is_non_retryable(status_code):
)
+ "error_code,expected_message",
+ [
+ ("invalid_client", SHOPIFY_ACCESS_TOKEN_INVALID_CLIENT_ERROR),
+ ("unsupported_grant_type", SHOPIFY_ACCESS_TOKEN_UNSUPPORTED_GRANT_ERROR),
+ ],
+)
+def test_get_access_token_4xx_maps_shopify_error_code(error_code, expected_message):
+ # Shopify names the cause in the 4xx body. Each recognized code must surface its own
+ # message and carry Shopify's raw error/description so support can read what Shopify said.
+ body = {"error": error_code, "error_description": "Shopify says so"}
+ with _patched_token_call(_mock_response(400, ok=False, json_data=body)):
+ with pytest.raises(Exception) as exc_info:
+ _get_shopify_access_token("store", "client-id", "client-secret")
+
+ error_message = str(exc_info.value)
+ assert expected_message in error_message
+ assert error_code in error_message
+ assert "Shopify says so" in error_message
+ patterns = ShopifySource().get_non_retryable_errors()
+ assert any(pattern in error_message for pattern in patterns), (
+ f"4xx token error '{error_message}' should match a non-retryable pattern"
+ )
+
+
def test_get_access_token_404_reports_missing_store():
# A 404 means the store subdomain doesn't resolve to a real store — a distinct,
# non-retryable failure that reconnecting the app can't fix, so it must surface the