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): pin whop api versions per source (#117247)

Daniel RC2a588e294352
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index b4a8bc61215a..73bd59bf0618 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -1212,7 +1212,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/webflow/webflow.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/weights_and_biases/weights_and_biases.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/whop/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/whop/whop.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/wikipedia_pageviews.py
diff --git a/products/warehouse_sources/backend/migrations/0186_pin_whop_api_version_2025_01_01.py b/products/warehouse_sources/backend/migrations/0186_pin_whop_api_version_2025_01_01.py
new file mode 100644
index 000000000000..16d6480c250f
--- /dev/null
+++ b/products/warehouse_sources/backend/migrations/0186_pin_whop_api_version_2025_01_01.py
@@ -0,0 +1,38 @@
+from django.db import migrations
+
+# Whop sources were created before the source declared versions, so every row carries the
+# unversioned "v1" label and the source sent no `Api-Version-Date` header. Whop then answered with
+# the version pinned to each customer's API key, which is "2025-01-01" for older keys and the latest
+# version for newer ones. The source now sends the pinned version as the header, and new sources
+# default to the latest version. This pins every existing source to "2025-01-01", the contract the
+# source was written against, so each one keeps the request and response shapes it already syncs.
+#
+# NULL pins are included because they resolve to the new default, which would silently move those
+# sources to the latest version.
+WHOP_SOURCE_TYPE = "Whop"
+UNVERSIONED_API_VERSION = "v1"
+WHOP_API_VERSION_2025_01_01 = "2025-01-01"
+
+
+def pin_whop_sources_to_2025_01_01(apps, schema_editor):
+ ExternalDataSource = apps.get_model("warehouse_sources", "ExternalDataSource")
+
+ # Source-level pin only. Schema-level `ExternalDataSchema.api_version` overrides are
+ # user-managed and stay as they are. Matching only the unversioned and NULL pins keeps this
+ # idempotent: a second run matches nothing.
+ ExternalDataSource.objects.filter(source_type=WHOP_SOURCE_TYPE, api_version=UNVERSIONED_API_VERSION).update(
+ api_version=WHOP_API_VERSION_2025_01_01
+ )
+ ExternalDataSource.objects.filter(source_type=WHOP_SOURCE_TYPE, api_version__isnull=True).update(
+ api_version=WHOP_API_VERSION_2025_01_01
+ )
+
+
+class Migration(migrations.Migration):
+ dependencies = [("warehouse_sources", "0185_externaldatadestination_health")]
+
+ operations = [
+ # Reverse is a no-op: pinned rows are indistinguishable from sources created on
+ # "2025-01-01", so a blanket downgrade would clobber legitimate pins.
+ migrations.RunPython(pin_whop_sources_to_2025_01_01, migrations.RunPython.noop, elidable=True),
+ ]
diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txt
index edb24947558d..6b0c0cff4164 100644
--- a/products/warehouse_sources/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0185_externaldatadestination_health
+0186_pin_whop_api_version_2025_01_01
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/whop/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/settings.py
index ba33fcb30b76..84c46f848adc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/whop/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/settings.py
@@ -1,4 +1,4 @@
-from dataclasses import dataclass
+from posthog.dataclasses import frozen
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode
@@ -6,6 +6,22 @@ from products.warehouse_sources.backend.types import IncrementalField
BASE_URL = "https://api.whop.com/api/v1"
+# Whop versions its API by date, sent as the `Api-Version-Date` header. A request without the header
+# gets the version pinned to the API key, and newly created keys pin the latest version, so the
+# source always sends the version pinned on the source instead of letting the key decide.
+WHOP_API_VERSION_2025_01_01 = "2025-01-01"
+WHOP_API_VERSION_2026_10_13_1 = "2026-10-13-1"
+WHOP_API_VERSIONS = (WHOP_API_VERSION_2025_01_01, WHOP_API_VERSION_2026_10_13_1)
+API_VERSION_HEADER = "Api-Version-Date"
+
+# The query param that narrows a list to the connected company. Later versions renamed it, and
+# `/products` ignores an unknown param and lists the whole Whop marketplace, so the wrong name is
+# not always an error.
+COMPANY_FILTER_PARAM: dict[str, str] = {
+ WHOP_API_VERSION_2025_01_01: "company_id",
+ WHOP_API_VERSION_2026_10_13_1: "account_id",
+}
+
WHOP_API_KEYS_URL = "https://whop.com/dashboard/developer"
# Whop pages with Relay-style cursors (`first` + `after`). The docs publish no maximum page size,
@@ -13,10 +29,10 @@ WHOP_API_KEYS_URL = "https://whop.com/dashboard/developer"
PAGE_SIZE = 100
-@dataclass
+@frozen
class WhopEndpointConfig:
path: str
- # Whether `company_id` is a required query param. The rest accept it as an optional narrowing
+ # Whether the company filter is a required query param. The rest accept it as an optional narrowing
# filter, which we always send so a key reaching several companies stays pinned to the one the
# user connected.
company_id_required: bool = False
@@ -30,6 +46,12 @@ class WhopEndpointConfig:
# resource carries a `created_at` column for the pipeline to track.
supports_created_after: bool = False
partition_key: str | None = "created_at"
+ latest_path: str | None = None
+
+ def path_for(self, api_version: str) -> str:
+ if api_version == WHOP_API_VERSION_2025_01_01:
+ return self.path
+ return self.latest_path or self.path
WHOP_ENDPOINTS: dict[str, WhopEndpointConfig] = {
@@ -60,6 +82,7 @@ WHOP_ENDPOINTS: dict[str, WhopEndpointConfig] = {
),
"entries": WhopEndpointConfig(
path="/entries",
+ latest_path="/waitlist_entries",
company_id_required=True,
supports_created_at_order=True,
supports_direction=True,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/whop/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/source.py
index 0b11037cd664..b9ef3971d840 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/whop/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/source.py
@@ -9,6 +9,7 @@ from products.warehouse_sources.backend.facade.source_config import (
SourceFieldInputConfigType,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ UNVERSIONED_API_VERSION,
ExternalWebhookInfo,
FieldType,
ResumableSource,
@@ -38,6 +39,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.whop.setti
SCHEMA_TO_WEBHOOK_EVENTS,
WEBHOOK_SCHEMA_NAMES,
WHOP_API_KEYS_URL,
+ WHOP_API_VERSION_2025_01_01,
+ WHOP_API_VERSION_2026_10_13_1,
+ WHOP_API_VERSIONS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.whop.whop import WhopResumeConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -74,15 +78,20 @@ class WhopSource(
)
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
- # Whop's dated `Api-Version-Date` header pins the Experimental API. The stable `/api/v1`
- # endpoints this source calls are served on the unversioned contract when the header is omitted,
- # so no version is sent and none is declared.
+ supported_versions = WHOP_API_VERSIONS
+ default_version = WHOP_API_VERSION_2026_10_13_1
api_docs_url = "https://docs.whop.com/developer/api/versioning"
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.WHOP
+ def _api_version_date(self, api_version: str | None) -> str:
+ pinned = self.resolve_api_version(api_version)
+ # Rows created before the source declared versions carry the unversioned label until the
+ # pinning migration moves them. They always ran on Whop's original contract.
+ return WHOP_API_VERSION_2025_01_01 if pinned == UNVERSIONED_API_VERSION else pinned
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
@@ -133,7 +142,9 @@ class WhopSource(
"**Manual setup** (only needed if automatic registration failed):\n\n"
f"1. Go to the [Developer tab]({WHOP_API_KEYS_URL}) in your Whop dashboard\n"
"2. Click **Create Webhook** and paste the webhook URL shown below\n"
- "3. Set the API version to **v1**\n"
+ "3. Set the API version date to the version this source syncs with. It is shown as the source "
+ "default under **Vendor API version** on any table's **Configuration** tab. For "
+ f"{WHOP_API_VERSION_2025_01_01}, leave the API version date empty\n"
"4. Select the payment, membership, member, product, entry, invoice, refund, dispute, "
"setup intent, and shipment events matching the tables you sync\n"
"5. Copy the webhook secret into the field below so PostHog can verify deliveries"
@@ -213,7 +224,9 @@ class WhopSource(
if not config.company_id.startswith("biz_"):
return False, "Whop company IDs start with `biz_`. Copy the ID from your Whop dashboard URL."
- is_valid, status = api_client.validate_credentials(config.api_key, config.company_id)
+ is_valid, status = api_client.validate_credentials(
+ config.api_key, config.company_id, self._api_version_date(api_version)
+ )
if is_valid:
return True, None
if status == 403:
@@ -252,7 +265,9 @@ class WhopSource(
def create_webhook(
self, config: WhopSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
) -> WebhookCreationResult:
- return api_client.create_webhook(config.api_key, config.company_id, webhook_url)
+ return api_client.create_webhook(
+ config.api_key, config.company_id, webhook_url, self._api_version_date(api_version)
+ )
def get_desired_webhook_events(
self, config: WhopSourceConfig, eligible_schema_names: list[str]
@@ -268,17 +283,23 @@ class WhopSource(
api_version: str | None = None,
) -> WebhookSyncResult:
desired_events = self.get_desired_webhook_events(config, eligible_schema_names) or []
- return api_client.sync_webhook_events(config.api_key, config.company_id, webhook_url, desired_events)
+ return api_client.sync_webhook_events(
+ config.api_key, config.company_id, webhook_url, desired_events, self._api_version_date(api_version)
+ )
def get_external_webhook_info(
self, config: WhopSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
) -> ExternalWebhookInfo | None:
- return api_client.get_external_webhook_info(config.api_key, config.company_id, webhook_url)
+ return api_client.get_external_webhook_info(
+ config.api_key, config.company_id, webhook_url, self._api_version_date(api_version)
+ )
def delete_webhook(
self, config: WhopSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
) -> WebhookDeletionResult:
- return api_client.delete_webhook(config.api_key, config.company_id, webhook_url)
+ return api_client.delete_webhook(
+ config.api_key, config.company_id, webhook_url, self._api_version_date(api_version)
+ )
def source_for_pipeline(
self,
@@ -289,6 +310,7 @@ class WhopSource(
return api_client.whop_source(
api_key=config.api_key,
company_id=config.company_id,
+ api_version=self._api_version_date(inputs.api_version),
endpoint=inputs.schema_name,
team_id=inputs.team_id,
job_id=inputs.job_id,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/whop/tests/test_whop.py b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/tests/test_whop.py
index 71ecea39cc67..0d7d67132fdf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/whop/tests/test_whop.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/tests/test_whop.py
@@ -38,6 +38,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.whop.whop
COMPANY_ID = "biz_test"
+LEGACY = "2025-01-01"
+LATEST = "2026-10-13-1"
+
SYNC_ENDPOINT = "payments"
@@ -78,9 +81,14 @@ class TestParseDatetime:
class TestListParams:
@pytest.mark.parametrize("endpoint", list(ENDPOINTS))
- def test_company_and_page_size_always_sent(self, endpoint):
- params = _list_params(endpoint, COMPANY_ID, None)
- assert params["company_id"] == COMPANY_ID
+ @pytest.mark.parametrize(
+ "api_version, filter_param, other_param",
+ [(LEGACY, "company_id", "account_id"), (LATEST, "account_id", "company_id")],
+ )
+ def test_company_and_page_size_always_sent(self, endpoint, api_version, filter_param, other_param):
+ params = _list_params(endpoint, COMPANY_ID, None, api_version)
+ assert params[filter_param] == COMPANY_ID
+ assert other_param not in params
assert params["first"] == PAGE_SIZE
@pytest.mark.parametrize(
@@ -90,7 +98,27 @@ class TestListParams:
def test_endpoints_without_the_filter_never_send_created_after(self, endpoint):
# These resources carry no trackable `created_at`; sending the filter would silently drop
# rows the pipeline would then never backfill.
- assert "created_after" not in _list_params(endpoint, COMPANY_ID, datetime(2024, 5, 1, tzinfo=UTC))
+ assert "created_after" not in _list_params(endpoint, COMPANY_ID, datetime(2024, 5, 1, tzinfo=UTC), LEGACY)
+
+
+class TestApiVersion:
+ @pytest.mark.parametrize(
+ "pinned, sent_version, filter_param, endpoint, path",
+ [
+ (LEGACY, LEGACY, "company_id", "entries", "/api/v1/entries"),
+ (LATEST, LATEST, "account_id", "entries", "/api/v1/waitlist_entries"),
+ # A row created by a pod still on the unversioned code during the deploy.
+ ("v1", LEGACY, "company_id", "products", "/api/v1/products"),
+ (None, LATEST, "account_id", "products", "/api/v1/products"),
+ ],
+ )
+ def test_sync_sends_the_pinned_version(self, pinned, sent_version, filter_param, endpoint, path):
+ result = _driver().run(endpoint, [_page([], end_cursor=None, has_next_page=False)], api_version=pinned)
+
+ request = result.requests[0]
+ assert request.headers["api-version-date"] == sent_version
+ assert request.path == path
+ assert request.param(filter_param) == COMPANY_ID
class TestPagination:
@@ -142,7 +170,7 @@ class TestSourceResponseMetadata:
)
assert result.requests[0].param("created_after") == "2024-05-01T10:00:00.000Z"
- assert set(result.requests[0].query) == {"first", "company_id", "created_after", "order", "direction"}
+ assert set(result.requests[0].query) == {"first", "account_id", "created_after", "order", "direction"}
class TestWebhookTableTransformer:
@@ -163,42 +191,56 @@ class TestWebhookTableTransformer:
class TestValidateCredentials:
- def test_probes_the_connected_company_with_a_bearer_token(self):
+ @pytest.mark.parametrize("api_version, resource", [(LEGACY, "companies"), (LATEST, "accounts")])
+ def test_probes_the_connected_company_with_a_bearer_token(self, api_version, resource):
with scripted_network([ScriptedResponse(json={})]) as network:
- validate_credentials("key", COMPANY_ID)
+ validate_credentials("key", COMPANY_ID, api_version)
request = network.requests_log[0]
- assert request.url == f"{BASE_URL}/companies/{COMPANY_ID}"
+ assert request.url == f"{BASE_URL}/{resource}/{COMPANY_ID}"
assert request.headers["authorization"] == "Bearer key"
+ assert request.headers["api-version-date"] == api_version
def test_transport_failure_never_raises(self):
with scripted_network(always(ConnectionError("boom"))):
- assert validate_credentials("key", COMPANY_ID) == (False, None)
+ assert validate_credentials("key", COMPANY_ID, LEGACY) == (False, None)
WEBHOOK_URL = "https://ph.example/webhook"
class TestCreateWebhook:
- def test_returns_the_generated_signing_secret(self):
+ @pytest.mark.parametrize(
+ "api_version, version_fields",
+ [
+ # An unpinned v1 webhook delivers the "2025-01-01" shape the legacy pulls return.
+ (LEGACY, {"api_version": "v1"}),
+ # Later versions reject `api_version` with a 400, and the pin keeps deliveries in the
+ # shape the latest pulls return.
+ (LATEST, {"api_version_date": LATEST}),
+ ],
+ )
+ def test_returns_the_generated_signing_secret(self, api_version, version_fields):
with scripted_network(
[ScriptedResponse(status=201, json={"id": "hook_1", "webhook_secret": "whsec_abc"})]
) as network:
- result = create_webhook("key", COMPANY_ID, WEBHOOK_URL)
+ result = create_webhook("key", COMPANY_ID, WEBHOOK_URL, api_version)
assert result.success is True
assert result.extra_inputs == {"signing_secret": "whsec_abc"}
payload = network.requests_log[0].json()
- assert payload["url"] == WEBHOOK_URL
- assert payload["resource_id"] == COMPANY_ID
- # Deliveries must use the v1 payload envelope the transformer unwraps.
- assert payload["api_version"] == "v1"
- assert payload["events"] == ALL_WEBHOOK_EVENTS
+ assert payload == {
+ "url": WEBHOOK_URL,
+ "events": ALL_WEBHOOK_EVENTS,
+ "resource_id": COMPANY_ID,
+ "enabled": True,
+ **version_fields,
+ }
@pytest.mark.parametrize("status_code", [401, 403, 422, 500])
def test_non_success_falls_back_to_manual_setup(self, status_code):
with scripted_network(always(ScriptedResponse(status=status_code, json={}))):
- result = create_webhook("key", COMPANY_ID, WEBHOOK_URL)
+ result = create_webhook("key", COMPANY_ID, WEBHOOK_URL, LEGACY)
assert result.success is False
assert result.error is not None
@@ -209,13 +251,13 @@ class TestCreateWebhook:
# Without a secret the hog function cannot verify deliveries, so reporting success would
# silently leave the webhook rejecting every payload.
with scripted_network([ScriptedResponse(status=201, json={"id": "hook_1"})]):
- result = create_webhook("key", COMPANY_ID, WEBHOOK_URL)
+ result = create_webhook("key", COMPANY_ID, WEBHOOK_URL, LEGACY)
assert result.success is False
def test_transport_failure_is_reported_not_raised(self):
with scripted_network(always(ConnectionError("boom"))):
- assert create_webhook("key", COMPANY_ID, WEBHOOK_URL).success is False
+ assert create_webhook("key", COMPANY_ID, WEBHOOK_URL, LEGACY).success is False
def _webhook_list_page(items: list[dict[str, Any]], end_cursor: str | None, has_next_page: bool) -> ScriptedResponse:
@@ -241,7 +283,8 @@ def _writes(requests_log: list[RecordedRequest], method: str) -> list[RecordedRe
class TestWebhookManagement:
- def test_lookup_pages_through_every_webhook(self):
+ @pytest.mark.parametrize("api_version, filter_param", [(LEGACY, "company_id"), (LATEST, "account_id")])
+ def test_lookup_pages_through_every_webhook(self, api_version, filter_param):
with scripted_network(
[
_webhook_list_page([{"id": "hook_1", "url": "https://other.example"}], "cursor-1", True),
@@ -252,22 +295,23 @@ class TestWebhookManagement:
),
]
) as network:
- info = get_external_webhook_info("key", COMPANY_ID, WEBHOOK_URL)
+ info = get_external_webhook_info("key", COMPANY_ID, WEBHOOK_URL, api_version)
assert info.exists is True
assert info.enabled_events == ["payment.succeeded"]
assert info.status == "enabled"
assert network.requests_log[1].param("after") == "cursor-1"
+ assert network.requests_log[0].param(filter_param) == COMPANY_ID
def test_lookup_reports_absence(self):
with scripted_network([_webhook_list_page([], None, False)]):
- assert get_external_webhook_info("key", COMPANY_ID, WEBHOOK_URL).exists is False
+ assert get_external_webhook_info("key", COMPANY_ID, WEBHOOK_URL, LEGACY).exists is False
def test_sync_merges_missing_events_and_keeps_existing_ones(self):
webhooks = [{"id": "hook_1", "url": WEBHOOK_URL, "events": ["payment.created", "custom.event"]}]
with scripted_network(_webhook_api(webhooks, always(ScriptedResponse(json={})))) as network:
- result = sync_webhook_events("key", COMPANY_ID, WEBHOOK_URL, ["payment.succeeded"])
+ result = sync_webhook_events("key", COMPANY_ID, WEBHOOK_URL, ["payment.succeeded"], LEGACY)
assert result.success is True
assert _writes(network.requests_log, "PATCH")[0].json() == {
@@ -278,7 +322,7 @@ class TestWebhookManagement:
webhooks = [{"id": "hook_1", "url": WEBHOOK_URL, "events": ["payment.succeeded"]}]
with scripted_network(_webhook_api(webhooks)) as network:
- assert sync_webhook_events("key", COMPANY_ID, WEBHOOK_URL, ["payment.succeeded"]).success
+ assert sync_webhook_events("key", COMPANY_ID, WEBHOOK_URL, ["payment.succeeded"], LEGACY).success
assert _writes(network.requests_log, "PATCH") == []
@@ -289,7 +333,7 @@ class TestWebhookManagement:
]
with scripted_network(_webhook_api(webhooks, always(ScriptedResponse(status=204)))) as network:
- result = delete_webhook("key", COMPANY_ID, WEBHOOK_URL)
+ result = delete_webhook("key", COMPANY_ID, WEBHOOK_URL, LEGACY)
assert result.success is True
deletes = _writes(network.requests_log, "DELETE")
@@ -299,4 +343,4 @@ class TestWebhookManagement:
webhooks = [{"id": "hook_2", "url": WEBHOOK_URL}]
with scripted_network(_webhook_api(webhooks, always(ScriptedResponse(status=403)))):
- assert delete_webhook("key", COMPANY_ID, WEBHOOK_URL).success is False
+ assert delete_webhook("key", COMPANY_ID, WEBHOOK_URL, LEGACY).success is False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/whop/tests/test_whop_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/tests/test_whop_source.py
index b71addef720c..55dec776fe57 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/whop/tests/test_whop_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/tests/test_whop_source.py
@@ -79,20 +79,23 @@ class TestWhopSource:
else:
assert expected_message in (message or "")
+ @pytest.mark.parametrize("method_name", ["create_webhook", "delete_webhook", "get_external_webhook_info"])
@pytest.mark.parametrize(
- "method_name, client_method",
- [
- ("create_webhook", "create_webhook"),
- ("delete_webhook", "delete_webhook"),
- ("get_external_webhook_info", "get_external_webhook_info"),
- ],
+ "pinned, sent_version",
+ [("2025-01-01", "2025-01-01"), ("v1", "2025-01-01"), (None, "2026-10-13-1")],
)
- def test_webhook_management_passes_the_connected_company(self, method_name, client_method):
- # The webhook endpoints require company_id; dropping it would 400 every registration.
+ def test_webhook_management_passes_the_connected_company(self, method_name, pinned, sent_version):
+ # The webhook endpoints require the company, and a webhook created under the wrong version
+ # delivers payloads in a different shape from the rows the pulls write.
with mock.patch(API_CLIENT_PATCH) as api_client:
- getattr(self.source, method_name)(self.config, WEBHOOK_URL, self.team_id)
+ getattr(self.source, method_name)(self.config, WEBHOOK_URL, self.team_id, api_version=pinned)
- assert getattr(api_client, client_method).call_args.args == ("test-api-key", "biz_test", WEBHOOK_URL)
+ assert getattr(api_client, method_name).call_args.args == (
+ "test-api-key",
+ "biz_test",
+ WEBHOOK_URL,
+ sent_version,
+ )
def test_sync_webhook_events_forwards_the_events_for_the_selected_schemas(self):
with mock.patch(API_CLIENT_PATCH) as api_client:
@@ -103,6 +106,7 @@ class TestWhopSource:
"biz_test",
WEBHOOK_URL,
sorted(SCHEMA_TO_WEBHOOK_EVENTS["refunds"]),
+ "2026-10-13-1",
)
def test_source_for_pipeline_plumbs_the_sync_inputs(self):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/whop/whop.py b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/whop.py
index 09c21633294a..84aaf03890f3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/whop/whop.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/whop.py
@@ -30,9 +30,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.whop.settings import (
ALL_WEBHOOK_EVENTS,
+ API_VERSION_HEADER,
BASE_URL,
+ COMPANY_FILTER_PARAM,
PAGE_SIZE,
WEBHOOK_SCHEMA_NAMES,
+ WHOP_API_VERSION_2025_01_01,
WHOP_ENDPOINTS,
sort_mode_for,
)
@@ -105,9 +108,10 @@ def _list_params(
endpoint: str,
company_id: str,
watermark: Optional[datetime],
+ api_version: str,
) -> dict[str, Any]:
config = WHOP_ENDPOINTS[endpoint]
- params: dict[str, Any] = {"first": PAGE_SIZE, "company_id": company_id}
+ params: dict[str, Any] = {"first": PAGE_SIZE, COMPANY_FILTER_PARAM[api_version]: company_id}
if config.supports_created_at_order:
# Forcing the sort column makes the arrival order knowable, which is what lets this endpoint
@@ -126,6 +130,7 @@ def _list_params(
def whop_source(
api_key: str,
company_id: str,
+ api_version: str,
endpoint: str,
team_id: int,
job_id: str,
@@ -141,6 +146,7 @@ def whop_source(
"client": {
"base_url": BASE_URL,
"auth": {"type": "bearer", "token": api_key},
+ "headers": {API_VERSION_HEADER: api_version},
"paginator": WhopCursorPaginator(),
# capture=False: Whop list responses carry buyer PII (emails, phone numbers, billing and
# shipping addresses) and signed invoice tokens the name-based scrubbers can't
@@ -158,8 +164,8 @@ def whop_source(
else "replace",
"table_format": "delta",
"endpoint": {
- "path": config.path,
- "params": _list_params(endpoint, company_id, watermark),
+ "path": config.path_for(api_version),
+ "params": _list_params(endpoint, company_id, watermark, api_version),
"data_selector": "data",
},
}
@@ -246,34 +252,39 @@ def webhook_table_transformer(table: pa.Table) -> pa.Table:
return table_from_py_list([row for _, row in latest_by_id.values()])
-def _make_session(api_key: str) -> Session:
+def _headers(api_key: str, api_version: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json", API_VERSION_HEADER: api_version}
+
+
+def _make_session(api_key: str, api_version: str) -> Session:
return make_tracked_session(
- headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
+ headers=_headers(api_key, api_version),
redact_values=(api_key,),
# Webhook responses carry the signing secret, so keep them out of HTTP sample capture.
capture=False,
)
-def validate_credentials(api_key: str, company_id: str) -> tuple[bool, Optional[int]]:
+def validate_credentials(api_key: str, company_id: str, api_version: str) -> tuple[bool, Optional[int]]:
"""Probe the credential against the connected company, returning `(is_valid, status_code)`.
- `GET /companies/{id}` is the cheapest call that proves both the key and the company id. A 403
+ Retrieving the company is the cheapest call that proves both the key and the company id. A 403
means the key is genuine but lacks `company:basic:read`, which the caller accepts at
source-create time.
"""
+ resource = "companies" if api_version == WHOP_API_VERSION_2025_01_01 else "accounts"
return validate_via_probe(
lambda: make_tracked_session(capture=False, redact_values=(api_key,)),
- f"{BASE_URL}/companies/{company_id}",
- headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
+ f"{BASE_URL}/{resource}/{company_id}",
+ headers=_headers(api_key, api_version),
)
-def _iterate_webhooks(session: Session, company_id: str) -> Iterator[dict[str, Any]]:
+def _iterate_webhooks(session: Session, company_id: str, api_version: str) -> Iterator[dict[str, Any]]:
"""Walk `GET /webhooks` with Whop's cursor pagination, yielding each webhook object."""
cursor: Optional[str] = None
while True:
- params: dict[str, Any] = {"company_id": company_id, "first": PAGE_SIZE}
+ params: dict[str, Any] = {COMPANY_FILTER_PARAM[api_version]: company_id, "first": PAGE_SIZE}
if cursor:
params["after"] = cursor
response = session.get(f"{BASE_URL}/webhooks?{urlencode(params)}", timeout=REQUEST_TIMEOUT)
@@ -289,30 +300,30 @@ def _iterate_webhooks(session: Session, company_id: str) -> Iterator[dict[str, A
return
-def _webhooks_matching(session: Session, company_id: str, webhook_url: str) -> list[dict[str, Any]]:
- return [item for item in _iterate_webhooks(session, company_id) if item.get("url") == webhook_url]
+def _webhooks_matching(session: Session, company_id: str, webhook_url: str, api_version: str) -> list[dict[str, Any]]:
+ return [item for item in _iterate_webhooks(session, company_id, api_version) if item.get("url") == webhook_url]
-def create_webhook(api_key: str, company_id: str, webhook_url: str) -> WebhookCreationResult:
+def create_webhook(api_key: str, company_id: str, webhook_url: str, api_version: str) -> WebhookCreationResult:
"""Register a v1 webhook on the company, returning Whop's generated signing secret.
- `api_version_date` is deliberately left unset: unpinned v1 deliveries use the payload shape this
- source's transformer expects, and pinning would opt the webhook into the dated Experimental
- contract instead.
+ Deliveries must carry resources in the same shape the list endpoints return, so the webhook
+ follows the source's version. An unpinned webhook delivers the "2025-01-01" shape. Later versions
+ reject the `api_version` input with a 400 and pin the payload with `api_version_date` instead.
"""
+ body: dict[str, Any] = {
+ "url": webhook_url,
+ "events": ALL_WEBHOOK_EVENTS,
+ "resource_id": company_id,
+ "enabled": True,
+ }
+ if api_version == WHOP_API_VERSION_2025_01_01:
+ body["api_version"] = "v1"
+ else:
+ body["api_version_date"] = api_version
try:
- session = _make_session(api_key)
- response = session.post(
- f"{BASE_URL}/webhooks",
- json={
- "url": webhook_url,
- "events": ALL_WEBHOOK_EVENTS,
- "resource_id": company_id,
- "api_version": "v1",
- "enabled": True,
- },
- timeout=REQUEST_TIMEOUT,
- )
+ session = _make_session(api_key, api_version)
+ response = session.post(f"{BASE_URL}/webhooks", json=body, timeout=REQUEST_TIMEOUT)
if response.status_code not in (200, 201):
return WebhookCreationResult(
success=False,
@@ -337,15 +348,15 @@ def create_webhook(api_key: str, company_id: str, webhook_url: str) -> WebhookCr
def sync_webhook_events(
- api_key: str, company_id: str, webhook_url: str, desired_events: list[str]
+ api_key: str, company_id: str, webhook_url: str, desired_events: list[str], api_version: str
) -> WebhookSyncResult:
"""Add any missing `desired_events` to the company's webhooks pointing at `webhook_url`.
Events are merged, never removed, so a manually broadened webhook keeps its extra events.
"""
try:
- session = _make_session(api_key)
- for webhook in _webhooks_matching(session, company_id, webhook_url):
+ session = _make_session(api_key, api_version)
+ for webhook in _webhooks_matching(session, company_id, webhook_url, api_version):
current = webhook.get("events") or []
merged = sorted(set(current) | set(desired_events))
if merged == sorted(current):
@@ -361,10 +372,10 @@ def sync_webhook_events(
return WebhookSyncResult(success=False, error=f"Failed to update Whop webhook events: {e}")
-def get_external_webhook_info(api_key: str, company_id: str, webhook_url: str) -> ExternalWebhookInfo:
+def get_external_webhook_info(api_key: str, company_id: str, webhook_url: str, api_version: str) -> ExternalWebhookInfo:
try:
- session = _make_session(api_key)
- matching = _webhooks_matching(session, company_id, webhook_url)
+ session = _make_session(api_key, api_version)
+ matching = _webhooks_matching(session, company_id, webhook_url, api_version)
if not matching:
return ExternalWebhookInfo(exists=False)
@@ -380,11 +391,11 @@ def get_external_webhook_info(api_key: str, company_id: str, webhook_url: str) -
return ExternalWebhookInfo(exists=False, error=str(e))
-def delete_webhook(api_key: str, company_id: str, webhook_url: str) -> WebhookDeletionResult:
+def delete_webhook(api_key: str, company_id: str, webhook_url: str, api_version: str) -> WebhookDeletionResult:
try:
- session = _make_session(api_key)
+ session = _make_session(api_key, api_version)
errors: list[str] = []
- for webhook in _webhooks_matching(session, company_id, webhook_url):
+ for webhook in _webhooks_matching(session, company_id, webhook_url, api_version):
response = session.delete(f"{BASE_URL}/webhooks/{webhook.get('id')}", timeout=REQUEST_TIMEOUT)
if response.status_code not in (200, 202, 204):
errors.append(f"webhook {webhook.get('id')}: HTTP {response.status_code}")