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(data-warehouse): normalize Shopify store id to reduce connection errors (#62418)

Tom Owers5688538b1cf4
diff --git a/posthog/temporal/data_imports/sources/shopify/shopify.py b/posthog/temporal/data_imports/sources/shopify/shopify.py
index 13bd9ca558f0..8baf9ab81837 100644
--- a/posthog/temporal/data_imports/sources/shopify/shopify.py
+++ b/posthog/temporal/data_imports/sources/shopify/shopify.py
@@ -1,4 +1,5 @@
import os
+import re
import json
import dataclasses
from collections.abc import Iterator
@@ -155,7 +156,43 @@ def _make_paginated_shopify_request(
resumable_source_manager.save_state(ShopifyResumeConfig(phase=phase, cursor=next_cursor))
+# A Shopify store subdomain is lowercase alphanumerics and hyphens.
+_SHOPIFY_SUBDOMAIN_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$")
+
+
+def normalize_store_id(raw: str) -> str:
+ """Reduce whatever the user pasted to the bare Shopify store subdomain.
+
+ The store id is interpolated into ``https://{}.myshopify.com/...``, so a value
+ that already carries a scheme, a path, or the ``.myshopify.com`` suffix builds a
+ broken host (e.g. ``store.myshopify.com.myshopify.com`` or a host of ``https``) —
+ the single biggest cause of Shopify connection failures. Accepts ``my-store``,
+ ``my-store.myshopify.com``, ``https://my-store.myshopify.com`` and the admin
+ deep-link ``https://admin.shopify.com/store/my-store``, all returning ``my-store``.
+
+ Raises ``ValueError`` if the result isn't a plain subdomain, which also pins
+ outbound traffic to ``*.myshopify.com`` (no breaking out to another host).
+ """
+ store_id = (raw or "").strip().lower()
+ store_id = store_id.removeprefix("https://").removeprefix("http://")
+ # Admin deep-link: admin.shopify.com/store/<store-id>[/...]
+ if store_id.startswith("admin.shopify.com/store/"):
+ store_id = store_id.removeprefix("admin.shopify.com/store/")
+ # Drop any path/query/fragment that rode along with a pasted URL.
+ store_id = store_id.split("/", 1)[0].split("?", 1)[0].split("#", 1)[0]
+ # Strip the domain suffix, looping to collapse an accidental double suffix.
+ while store_id.endswith(".myshopify.com"):
+ store_id = store_id.removesuffix(".myshopify.com")
+ if not _SHOPIFY_SUBDOMAIN_RE.match(store_id):
+ raise ValueError(
+ f"Invalid Shopify store id {raw!r}. Enter just your store subdomain — the 'my-store' "
+ "in 'my-store.myshopify.com'."
+ )
+ return store_id
+
+
def _get_shopify_access_token(shopify_store_id: str, shopify_client_id: str, shopify_client_secret: str) -> str:
+ # Callers pass an already-normalized store id (see normalize_store_id).
access_token_url = SHOPIFY_ACCESS_TOKEN_URL.format(shopify_store_id)
access_data = {
"client_id": shopify_client_id,
@@ -184,8 +221,9 @@ def shopify_source(
resumable_source_manager: ResumableSourceManager[ShopifyResumeConfig],
should_use_incremental_field: bool = False,
):
- api_url = SHOPIFY_API_URL.format(shopify_store_id, SHOPIFY_API_VERSION)
- shopify_access_token = _get_shopify_access_token(shopify_store_id, shopify_client_id, shopify_client_secret)
+ store_id = normalize_store_id(shopify_store_id)
+ api_url = SHOPIFY_API_URL.format(store_id, SHOPIFY_API_VERSION)
+ shopify_access_token = _get_shopify_access_token(store_id, shopify_client_id, shopify_client_secret)
schema_name = resolve_schema_name(graphql_object_name)
def get_rows():
@@ -289,8 +327,9 @@ def validate_credentials(shopify_store_id: str, shopify_client_id: str, shopify_
- Raise ShopifyPermissionError if the access token is valid but lacks permissions for specific resources
- Raise Exception if the access token is invalid or there's any other error
"""
- api_url = SHOPIFY_API_URL.format(shopify_store_id, SHOPIFY_API_VERSION)
- shopify_access_token = _get_shopify_access_token(shopify_store_id, shopify_client_id, shopify_client_secret)
+ store_id = normalize_store_id(shopify_store_id)
+ api_url = SHOPIFY_API_URL.format(store_id, SHOPIFY_API_VERSION)
+ shopify_access_token = _get_shopify_access_token(store_id, shopify_client_id, shopify_client_secret)
sess = make_tracked_session(
headers={
"Content-Type": "application/json",
diff --git a/posthog/temporal/data_imports/sources/shopify/source.py b/posthog/temporal/data_imports/sources/shopify/source.py
index 167d73dfed5e..2967b67920c5 100644
--- a/posthog/temporal/data_imports/sources/shopify/source.py
+++ b/posthog/temporal/data_imports/sources/shopify/source.py
@@ -54,7 +54,11 @@ class ShopifySource(ResumableSource[ShopifySourceConfig, ShopifyResumeConfig]):
label="Store id",
type=SourceFieldInputConfigType.TEXT,
required=True,
- placeholder="my-store-id",
+ placeholder="my-store",
+ caption=(
+ "Your store subdomain — the `my-store` in `my-store.myshopify.com`. "
+ "Pasting the full store URL works too."
+ ),
secret=False,
),
SourceFieldInputConfig(
diff --git a/posthog/temporal/data_imports/sources/shopify/tests/test_store_id.py b/posthog/temporal/data_imports/sources/shopify/tests/test_store_id.py
new file mode 100644
index 000000000000..6afa1e204b14
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/shopify/tests/test_store_id.py
@@ -0,0 +1,59 @@
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.shopify.shopify import _get_shopify_access_token, normalize_store_id
+
+
+ "raw, expected",
+ [
+ ("my-store", "my-store"),
+ ("MY-STORE", "my-store"),
+ (" my-store ", "my-store"),
+ ("my-store.myshopify.com", "my-store"),
+ ("https://my-store.myshopify.com", "my-store"),
+ ("http://my-store.myshopify.com/", "my-store"),
+ ("my-store.myshopify.com/admin/api", "my-store"),
+ ("https://admin.shopify.com/store/my-store", "my-store"),
+ ("https://admin.shopify.com/store/my-store/products", "my-store"),
+ # Accidental double suffix collapses back to the bare subdomain.
+ ("my-store.myshopify.com.myshopify.com", "my-store"),
+ ("store123", "store123"),
+ ],
+)
+def test_normalize_store_id_accepts_common_paste_forms(raw, expected):
+ assert normalize_store_id(raw) == expected
+
+
+ "raw",
+ [
+ "",
+ " ",
+ "https://evil.com",
+ "my_store",
+ "store with spaces",
+ "-leading-hyphen",
+ ],
+)
+def test_normalize_store_id_rejects_invalid(raw):
+ with pytest.raises(ValueError):
+ normalize_store_id(raw)
+
+
+def test_access_token_url_has_no_doubled_suffix_for_messy_input():
+ response = mock.MagicMock()
+ response.ok = True
+ response.json.return_value = {"access_token": "shpat_x"}
+ session = mock.MagicMock(post=mock.MagicMock(return_value=response))
+
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.shopify.shopify.make_tracked_session",
+ return_value=session,
+ ):
+ # Callers normalize before threading the store id through, so messy input has
+ # already collapsed to the bare subdomain by the time it reaches this function.
+ _get_shopify_access_token(normalize_store_id("https://my-store.myshopify.com"), "client-id", "client-secret")
+
+ called_url = session.post.call_args.args[0]
+ assert called_url == "https://my-store.myshopify.com/admin/oauth/access_token"