: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): call correct RevenueCat webhook integration API (#70049)
Luke Beltonc5e838cfec82
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/constants.py b/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/constants.pyindex cdec1a938b7d..5c0a31539354 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/constants.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/constants.py@@ -14,30 +14,6 @@ RESOURCE_TO_REVENUECAT_EVENT_TYPE: dict[str, str] = {EVENT_RESOURCE_NAME: "*",}-# Every documented RevenueCat webhook event type. Used when auto-registering the-# webhook integration so we subscribe to all known events the customer might care-# about. List is from:-# https://www.revenuecat.com/docs/integrations/webhooks/event-types-and-fields-REVENUECAT_WEBHOOK_EVENT_TYPES: tuple[str, ...] = (- "TEST",- "INITIAL_PURCHASE",- "RENEWAL",- "CANCELLATION",- "UNCANCELLATION",- "NON_RENEWING_PURCHASE",- "SUBSCRIPTION_PAUSED",- "EXPIRATION",- "BILLING_ISSUE",- "PRODUCT_CHANGE",- "TRANSFER",- "SUBSCRIPTION_EXTENDED",- "TEMPORARY_ENTITLEMENT_GRANT",- "REFUND_REVERSED",- "INVOICE_ISSUANCE",- "VIRTUAL_CURRENCY_TRANSACTION",- "EXPERIMENT_ENROLLMENT",-)-REVENUECAT_API_BASE_URL = "https://api.revenuecat.com/v2"# Default name applied when auto-creating the webhook integration in RevenueCat.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/revenuecat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/revenuecat.pyindex 040292953733..f04dc4f0a798 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/revenuecat.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/revenuecat.py@@ -23,7 +23,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.httfrom products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.constants import (REVENUECAT_API_BASE_URL,REVENUECAT_AUTO_WEBHOOK_NAME,- REVENUECAT_WEBHOOK_EVENT_TYPES,)LOGGER = structlog.get_logger(__name__)@@ -309,53 +308,82 @@ def iterate_list_endpoint(params = {}+def _update_webhook_integration(api_key: str, project_id: str, webhook_id: str, updates: dict[str, Any]) -> None:+ """Update fields on an existing webhook integration in place.++ RevenueCat models updates as a POST to the integration's own path+ (``POST /v2/projects/{project_id}/integrations/webhooks/{id}``); only the+ fields present in the body change.+ """+ url = f"{REVENUECAT_API_BASE_URL}{_project_path(project_id, f'/integrations/webhooks/{webhook_id}')}"+ response = _session(api_key).post(url, json=updates, timeout=REQUEST_TIMEOUT_SECONDS)+ response.raise_for_status()++def create_webhook(api_key: str,project_id: str,webhook_url: str,authorization_header_value: str | None = None,) -> WebhookCreationResult:- """Auto-register a webhook integration in RevenueCat pointing at ``webhook_url``.-- Auth-header note: RevenueCat does not HMAC-sign its webhook deliveries —- instead, the integration ships an ``Authorization`` header whose value the- user sets at creation time. We let callers pass that value through so we- can later verify it in the Hog template. If not supplied, the integration- is created without an auth header and the user finishes setup by adding one+ """Register a webhook integration in RevenueCat pointing at ``webhook_url``.++ ``POST /v2/projects/{project_id}/integrations/webhooks`` — note the plural+ ``webhooks``; the singular path is a 404 ("Resource not found") that our+ error formatter would misreport as a bad project id. ``event_types`` is+ deliberately omitted from the body: a null filter subscribes the+ integration to every event type, including ones RevenueCat adds later,+ which is exactly what the single ``events`` warehouse table wants.++ Auth-header note: the integration ships an ``Authorization`` header on+ every delivery whose value the user sets (the API field is+ ``authorization_header``). We let callers pass that value through so we can+ later verify it in the Hog template. If not supplied, the integration is+ created without an auth header and the user finishes setup by adding onevia the webhook fields (handled by the surrounding warehouse-source flow).+ When a webhook for this URL already exists, a supplied header is bound to+ it in place via the update endpoint."""project_id = _normalize_project_id(project_id)logger = LOGGER.bind(project_id=project_id)body: dict[str, Any] = {- "url": webhook_url,- "events": list(REVENUECAT_WEBHOOK_EVENT_TYPES),"name": REVENUECAT_AUTO_WEBHOOK_NAME,+ "url": webhook_url,}if authorization_header_value:- # RevenueCat names this field `signing_secret` in their API even though- # the upstream behavior is just "send this verbatim as Authorization".- body["signing_secret"] = authorization_header_value+ body["authorization_header"] = authorization_header_value- url = f"{REVENUECAT_API_BASE_URL}{_project_path(project_id, '/integrations/webhook')}"+ url = f"{REVENUECAT_API_BASE_URL}{_project_path(project_id, '/integrations/webhooks')}"try:existing = _find_webhook_integration(api_key, project_id, webhook_url)if existing is not None:if authorization_header_value:- # We were asked to bind a new authorization header but a webhook- # already exists. RevenueCat has no in-place update for the- # auth header — surface a failure so the caller (typically- # `webhook_inputs_updated`) can drive an explicit delete +- # recreate instead of silently leaving the existing webhook- # bound to a stale header.- return WebhookCreationResult(- success=False,- error=(- "A RevenueCat webhook integration already exists for this URL. "- "Delete it and reconnect to bind a new authorization header."- ),+ webhook_id = existing.get("id")+ if not webhook_id:+ return WebhookCreationResult(+ success=False,+ error="RevenueCat returned a webhook without an id; please recreate it manually.",+ )+ # Resend name and url alongside the header. The update input's+ # fields are all optional (patch semantics), but echoing the+ # delivery-critical fields costs nothing and keeps the webhook+ # pointed at us even if the endpoint ever replaces instead of+ # patches. `event_types` is deliberately not echoed: the list+ # response may contain event types newer than the update+ # enum, which would fail validation.+ _update_webhook_integration(+ api_key,+ project_id,+ str(webhook_id),+ {+ "name": str(existing.get("name") or REVENUECAT_AUTO_WEBHOOK_NAME),+ "url": webhook_url,+ "authorization_header": authorization_header_value,+ },)+ return WebhookCreationResult(success=True)# No auth header supplied yet — treat the existing webhook as# success so the user can finish setup by entering the header# value. RevenueCat omits the configured header from list@@ -365,10 +393,10 @@ def create_webhook(response = _session(api_key).post(url, json=body, timeout=REQUEST_TIMEOUT_SECONDS)response.raise_for_status()except requests.HTTPError as e:- logger.warning("Failed to create RevenueCat webhook integration", error=str(e))+ logger.warning("Failed to register RevenueCat webhook integration", error=str(e))return WebhookCreationResult(success=False, error=_format_http_error(e))except requests.RequestException as e:- logger.warning("Could not reach RevenueCat to create webhook", error=str(e))+ logger.warning("Could not reach RevenueCat to register webhook", error=str(e))return WebhookCreationResult(success=False, error=f"Could not reach RevenueCat: {e}")pending: list[str] = []@@ -382,7 +410,7 @@ def _list_webhook_integrations(api_key: str, project_id: str) -> list[dict[str,items: list[dict[str, Any]] = []session = _session(api_key)params: dict[str, Any] = {"limit": DEFAULT_PAGE_SIZE}- url = f"{REVENUECAT_API_BASE_URL}{_project_path(project_id, '/integrations/webhook')}"+ url = f"{REVENUECAT_API_BASE_URL}{_project_path(project_id, '/integrations/webhooks')}"while True:# Build the URL with explicit query encoding so the call signature stays@@ -441,7 +469,7 @@ def delete_webhook(api_key: str, project_id: str, webhook_url: str) -> WebhookDeerror="RevenueCat returned a webhook without an id; please delete it manually.",)- url = f"{REVENUECAT_API_BASE_URL}{_project_path(project_id, f'/integrations/webhook/{webhook_id}')}"+ url = f"{REVENUECAT_API_BASE_URL}{_project_path(project_id, f'/integrations/webhooks/{webhook_id}')}"try:response = _session(api_key).delete(url, timeout=REQUEST_TIMEOUT_SECONDS)if response.status_code == 404:@@ -470,7 +498,9 @@ def get_external_webhook_info(api_key: str, project_id: str, webhook_url: str) -if target is None:return ExternalWebhookInfo(exists=False)- events_value = target.get("events")+ # `event_types` is null when the integration subscribes to every event type+ # (the default for integrations we create).+ events_value = target.get("event_types")enabled_events = events_value if isinstance(events_value, list) else Nonecreated_at_raw = target.get("created_at")created_at = str(created_at_raw) if created_at_raw is not None else Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/source.pyindex 730f98deb6e9..c1f8291a4709 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/source.py@@ -166,9 +166,9 @@ class RevenueCatSource(releaseStatus=ReleaseStatus.GA,webhookSetupCaption=("PostHog tries to register a webhook integration in RevenueCat using your "- "secret API key. RevenueCat does not HMAC-sign deliveries — instead, the "- "integration sends a custom **Authorization** header on every request, whose "- "value you set below. PostHog rejects deliveries whose header does not match.\n\n"+ "secret API key. The integration authenticates itself by sending a custom "+ "**Authorization** header on every request, whose value you set below. "+ "PostHog rejects deliveries whose header does not match.\n\n""**Manual setup** (only needed if auto-registration failed):\n\n""1. Go to your **RevenueCat project** > **Integrations** > **+ New** > **Webhook**\n""2. Paste the webhook URL shown below into the **Webhook URL** field\n"@@ -270,10 +270,9 @@ class RevenueCatSource(return WebhookSourceManager(inputs, inputs.logger)def create_webhook(self, config: RevenueCatSourceConfig, webhook_url: str, team_id: int) -> WebhookCreationResult:- # RevenueCat requires the auth-header value at integration creation- # time, but the user hasn't entered it yet on the warehouse side. Skip- # passing one and the surrounding flow will collect it via- # `webhookFields`, then re-create the integration to bind it.+ # The user hasn't entered the auth-header value yet on the warehouse+ # side. Skip passing one and the surrounding flow will collect it via+ # `webhookFields`, then bind it to the integration in place.return api_client.create_webhook(api_key=config.secret_api_key,project_id=config.project_id,@@ -283,19 +282,14 @@ class RevenueCatSource(def webhook_inputs_updated(self, config: RevenueCatSourceConfig, webhook_url: str, team_id: int, inputs: dict[str, Any]) -> tuple[bool, str | None]:- # Once the user provides the authorization header value, re-register- # the integration so RevenueCat starts sending the header on every- # delivery. RevenueCat's API doesn't let you update the auth header on- # an existing integration in-place — delete + recreate is the- # supported path.+ # Once the user provides the authorization header value, bind it to the+ # integration so RevenueCat starts sending the header on every+ # delivery. `create_webhook` updates the existing integration in place+ # (or creates it fresh if auto-registration failed earlier).header_value = inputs.get("authorization_header")if not header_value:return True, None- deletion = api_client.delete_webhook(config.secret_api_key, config.project_id, webhook_url)- if not deletion.success:- return False, deletion.error or "Failed to refresh RevenueCat webhook integration."-creation = api_client.create_webhook(api_key=config.secret_api_key,project_id=config.project_id,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/tests/test_revenuecat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/tests/test_revenuecat.pyindex e88007af718b..3583fd9bcf40 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/tests/test_revenuecat.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/tests/test_revenuecat.py@@ -7,7 +7,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.revenuecatfrom products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.constants import (REVENUECAT_API_BASE_URL,REVENUECAT_AUTO_WEBHOOK_NAME,- REVENUECAT_WEBHOOK_EVENT_TYPES,)@@ -310,7 +309,7 @@ class TestCreateWebhook:"products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.revenuecat._find_webhook_integration")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.revenuecat._session")- def test_creates_webhook_with_all_known_event_types(self, mock_session, mock_find):+ def test_creates_webhook_with_authorization_header(self, mock_session, mock_find):mock_find.return_value = Nonemock_session.return_value.post.return_value = _ok_json_response({"id": "wh_1"})@@ -327,12 +326,20 @@ class TestCreateWebhook:# upfront.assert result.pending_inputs == []- post_kwargs = mock_session.return_value.post.call_args.kwargs- body = post_kwargs["json"]- assert body["url"] == "https://example.com/h"- assert body["name"] == REVENUECAT_AUTO_WEBHOOK_NAME- assert set(body["events"]) == set(REVENUECAT_WEBHOOK_EVENT_TYPES)- assert body["signing_secret"] == "Bearer my-secret"+ post_args = mock_session.return_value.post.call_args+ # `/integrations/webhooks` — plural. The singular path 404s ("Resource+ # not found"), which used to surface as a bogus "could not find the+ # project" error on every webhook setup attempt.+ assert post_args.args[0] == f"{REVENUECAT_API_BASE_URL}/projects/proj_test/integrations/webhooks"+ # Exact body match: `authorization_header` is the API's field name (a+ # `signing_secret` key means something else and gets rejected), and+ # `event_types` is omitted so the integration receives every event+ # type, current and future.+ assert post_args.kwargs["json"] == {+ "name": REVENUECAT_AUTO_WEBHOOK_NAME,+ "url": "https://example.com/h",+ "authorization_header": "Bearer my-secret",+ }@patch("products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.revenuecat._find_webhook_integration"@@ -351,12 +358,15 @@ class TestCreateWebhook:"products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.revenuecat._find_webhook_integration")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.revenuecat._session")- def test_fails_when_existing_webhook_and_new_authorization_header_supplied(self, mock_session, mock_find):- # RevenueCat has no in-place update for the auth header. If a webhook- # already exists and we're asked to bind a new header, fail loudly so- # the caller knows to delete + recreate explicitly — silently keeping- # the existing webhook would leave it bound to a stale header value.- mock_find.return_value = {"id": "wh_existing", "url": "https://example.com/h"}+ def test_updates_existing_webhook_in_place_when_authorization_header_supplied(self, mock_session, mock_find):+ # Binding the header must not delete + recreate the integration —+ # RevenueCat supports in-place updates via a POST to the integration's+ # own path, and recreating would drop deliveries in the gap. The update+ # body must carry the delivery-critical fields (existing name, our url)+ # next to the header so a replace-semantics update can't strand the+ # integration.+ mock_find.return_value = {"id": "wh_existing", "url": "https://example.com/h", "name": "My custom hook"}+ mock_session.return_value.post.return_value = _ok_json_response({"id": "wh_existing"})result = api_client.create_webhook("sk_test",@@ -365,10 +375,15 @@ class TestCreateWebhook:authorization_header_value="Bearer my-secret",)- assert result.success is False- assert result.error is not None- assert "already exists" in result.error.lower()- mock_session.return_value.post.assert_not_called()+ assert result.success is True+ assert result.pending_inputs == []+ post_args = mock_session.return_value.post.call_args+ assert post_args.args[0] == f"{REVENUECAT_API_BASE_URL}/projects/proj_test/integrations/webhooks/wh_existing"+ assert post_args.kwargs["json"] == {+ "name": "My custom hook",+ "url": "https://example.com/h",+ "authorization_header": "Bearer my-secret",+ }@patch("products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.revenuecat._find_webhook_integration"@@ -382,6 +397,8 @@ class TestCreateWebhook:assert result.success is Trueassert result.pending_inputs == ["authorization_header"]+ body = mock_session.return_value.post.call_args.kwargs["json"]+ assert "authorization_header" not in body@patch("products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.revenuecat._find_webhook_integration"@@ -411,7 +428,7 @@ class TestDeleteWebhook:assert result.success is Truecalled_url = mock_session.return_value.delete.call_args.args[0]- assert called_url == f"{REVENUECAT_API_BASE_URL}/projects/proj_test/integrations/webhook/wh_1"+ assert called_url == f"{REVENUECAT_API_BASE_URL}/projects/proj_test/integrations/webhooks/wh_1"@patch("products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.revenuecat._list_webhook_integrations"@@ -445,11 +462,14 @@ class TestGetExternalWebhookInfo:"products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.revenuecat._list_webhook_integrations")def test_returns_info_for_matching_webhook(self, mock_list):+ # The integration object names its subscription field `event_types`+ # (lowercase values) — reading the webhook-delivery-payload spelling+ # (`events`) would report no subscribed events for every integration.mock_list.return_value = [{"id": "wh_1","url": "https://example.com/h",- "events": ["INITIAL_PURCHASE", "RENEWAL"],+ "event_types": ["initial_purchase", "renewal"],"name": "PostHog data warehouse","created_at": 1658399423658,}@@ -461,7 +481,7 @@ class TestGetExternalWebhookInfo:assert info.exists is Trueassert info.url == "https://example.com/h"- assert info.enabled_events == ["INITIAL_PURCHASE", "RENEWAL"]+ assert info.enabled_events == ["initial_purchase", "renewal"]assert info.status == "enabled"assert info.description == "PostHog data warehouse"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/tests/test_revenuecat_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/tests/test_revenuecat_source.pyindex d6f831bf1573..fe46c5fd1745 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/tests/test_revenuecat_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/tests/test_revenuecat_source.py@@ -131,17 +131,16 @@ class TestRevenueCatSourceCreateWebhook:class TestRevenueCatSourceWebhookInputsUpdated:@patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.source.api_client.create_webhook"+ "products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.source.api_client.delete_webhook")@patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.source.api_client.delete_webhook"+ "products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.source.api_client.create_webhook")- def test_recreates_integration_when_authorization_header_provided(self, mock_delete, mock_create):- # RevenueCat's API doesn't let you update the auth header on an existing- # integration in-place, so the source must delete + recreate to bind a- # new header value. Guard against regressions where we accidentally- # short-circuit one of the two calls.- mock_delete.return_value = WebhookDeletionResult(success=True)+ def test_binds_authorization_header_without_deleting_integration(self, mock_create, mock_delete):+ # Binding the header goes through `create_webhook`, which updates the+ # existing integration in place (or creates it fresh if+ # auto-registration failed earlier). A delete + recreate here would+ # drop deliveries in the gap.mock_create.return_value = WebhookCreationResult(success=True)source = RevenueCatSource()@@ -154,7 +153,7 @@ class TestRevenueCatSourceWebhookInputsUpdated:assert success is Trueassert error is None- mock_delete.assert_called_once_with("k", "p", "https://example.com/h")+ mock_delete.assert_not_called()mock_create.assert_called_once()kwargs = mock_create.call_args.kwargsassert kwargs["authorization_header_value"] == "Bearer my-secret"@@ -162,27 +161,20 @@ class TestRevenueCatSourceWebhookInputsUpdated:@patch("products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.source.api_client.create_webhook")- @patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.source.api_client.delete_webhook"- )- def test_skips_recreate_when_authorization_header_missing(self, mock_delete, mock_create):+ def test_skips_api_call_when_authorization_header_missing(self, mock_create):source = RevenueCatSource()success, error = source.webhook_inputs_updated(_config(), "https://example.com/h", team_id=1, inputs={})assert success is Trueassert error is None- mock_delete.assert_not_called()mock_create.assert_not_called()@patch("products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.source.api_client.create_webhook")- @patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.source.api_client.delete_webhook"- )- def test_propagates_delete_failure(self, mock_delete, mock_create):- mock_delete.return_value = WebhookDeletionResult(success=False, error="boom")+ def test_propagates_bind_failure(self, mock_create):+ mock_create.return_value = WebhookCreationResult(success=False, error="boom")source = RevenueCatSource()success, error = source.webhook_inputs_updated(@@ -191,7 +183,6 @@ class TestRevenueCatSourceWebhookInputsUpdated:assert success is Falseassert error == "boom"- mock_create.assert_not_called()class TestRevenueCatSourceDeleteWebhook: