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.

feat(data-warehouse): implement RevenueCat source with webhook support (#59457)

Tom Owers27eccb57f346
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index e2ae5432b1b8..5152e24f6ef2 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -74,6 +74,7 @@ the row lists both.
| reddit_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
| redshift | DB protocol | psycopg (Postgres-compatible) | ➖ |
| resend | HTTP | requests | ✅ |
+| revenuecat | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| salesforce | HTTP | requests + `rest_source.RESTClient` | ✅ |
| sentry | HTTP | requests + `rest_source.RESTClient` | ✅ |
| shopify | HTTP | requests | ✅ |
@@ -113,7 +114,7 @@ fullstory, gitlab, gong, google_analytics, google_drive, gorgias, granola, green
instagram, intercom, iterable, jira, kafka, launchdarkly, lever, mailerlite, mailjet, marketo,
microsoft_teams, mixpanel, monday, netsuite, notion, okta, omnisend, onedrive, oracle, outreach,
pagerduty, pardot, paypal, pendo, pipedrive, plaid, postmark, productboard, quickbooks, recharge,
-recurly, revenuecat, ringcentral, salesloft, sendgrid, servicenow, sftp, sharepoint, shortcut, smartsheet,
+recurly, ringcentral, salesloft, sendgrid, servicenow, sftp, sharepoint, shortcut, smartsheet,
square, surveymonkey, temporalio, trello, twilio, twitter_ads, webflow, woocommerce, workday, wrike, xero,
youtube_analytics, zoho_crm, zoom, zuora.
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 44486490f336..70c8523e264a 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -696,7 +696,8 @@ class ResendSourceConfig(config.Config):
@config.config
class RevenueCatSourceConfig(config.Config):
- pass
+ secret_api_key: str
+ project_id: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/revenuecat/constants.py b/posthog/temporal/data_imports/sources/revenuecat/constants.py
new file mode 100644
index 000000000000..cdec1a938b7d
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/revenuecat/constants.py
@@ -0,0 +1,44 @@
+CUSTOMER_RESOURCE_NAME = "customers"
+PRODUCT_RESOURCE_NAME = "products"
+ENTITLEMENT_RESOURCE_NAME = "entitlements"
+OFFERING_RESOURCE_NAME = "offerings"
+APP_RESOURCE_NAME = "apps"
+EVENT_RESOURCE_NAME = "events"
+
+# Maps PostHog schema name -> the value RevenueCat emits in `event.type` (webhook payload).
+# The webhook handler uses the schema-level `webhook_resource_map` to route events into
+# the corresponding warehouse table. We expose a single "events" table that captures
+# every webhook event type rather than per-type tables — RevenueCat events share a flat
+# schema and querying them in one table is more ergonomic.
+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.
+REVENUECAT_AUTO_WEBHOOK_NAME = "PostHog data warehouse"
diff --git a/posthog/temporal/data_imports/sources/revenuecat/revenuecat.py b/posthog/temporal/data_imports/sources/revenuecat/revenuecat.py
new file mode 100644
index 000000000000..45f0feb007eb
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/revenuecat/revenuecat.py
@@ -0,0 +1,375 @@
+"""Thin RevenueCat API v2 client used by the data warehouse source.
+
+Spec: https://www.revenuecat.com/docs/api-v2
+
+Everything in this module routes through ``make_tracked_session`` so outbound
+calls show up in our HTTP logs, OTel metrics, and sample-capture pipeline.
+"""
+
+import dataclasses
+from collections.abc import Callable, Iterator
+from typing import Any
+from urllib.parse import urlencode, urljoin
+
+import requests
+import structlog
+
+from posthog.temporal.data_imports.sources.common.base import (
+ ExternalWebhookInfo,
+ WebhookCreationResult,
+ WebhookDeletionResult,
+)
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.revenuecat.constants import (
+ REVENUECAT_API_BASE_URL,
+ REVENUECAT_AUTO_WEBHOOK_NAME,
+ REVENUECAT_WEBHOOK_EVENT_TYPES,
+)
+
+LOGGER = structlog.get_logger(__name__)
+
+DEFAULT_PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 30
+
+
+class RevenueCatResumeConfig:
+ """Cursor state for resumable list iteration.
+
+ ``starting_after`` is the RevenueCat-issued cursor value (the id of the last
+ item from the previous page). ``endpoint`` scopes the cursor to a single
+ endpoint so we never replay a customers cursor against products.
+ """
+
+ endpoint: str
+ starting_after: str
+
+
+def _auth_headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_key}",
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ }
+
+
+def _session(api_key: str) -> requests.Session:
+ return make_tracked_session(headers=_auth_headers(api_key))
+
+
+def _project_path(project_id: str, suffix: str) -> str:
+ return f"/projects/{project_id}{suffix}"
+
+
+def _format_http_error(error: requests.HTTPError) -> str:
+ response = error.response
+ status_code = response.status_code if response is not None else None
+ if status_code == 401:
+ return (
+ "RevenueCat rejected the API key (401). Generate a v2 secret API key "
+ "from Project settings > API keys and check that it has not been revoked."
+ )
+ if status_code == 403:
+ return (
+ "RevenueCat denied the request (403). Make sure the v2 secret API key "
+ "has the permissions required for this resource."
+ )
+ if status_code == 404:
+ return "RevenueCat could not find the project (404). Double-check the project id."
+ if status_code == 429:
+ return "RevenueCat rate-limited the request (429). Try again in a few seconds."
+ return f"RevenueCat API error ({status_code})."
+
+
+def validate_credentials(api_key: str, project_id: str | None) -> tuple[bool, str | None]:
+ """Probe the cheapest endpoint that confirms the key + project.
+
+ GET /v2/projects lists every project the key can see — that's enough to
+ confirm the key is genuine. If a ``project_id`` is set, we additionally
+ fetch that project to catch typos and revoked-project access.
+ """
+ session = _session(api_key)
+ try:
+ response = session.get(f"{REVENUECAT_API_BASE_URL}/projects", timeout=REQUEST_TIMEOUT_SECONDS)
+ response.raise_for_status()
+ except requests.HTTPError as e:
+ return False, _format_http_error(e)
+ except requests.RequestException as e:
+ return False, f"Could not reach RevenueCat: {e}"
+
+ if project_id:
+ try:
+ response = session.get(
+ f"{REVENUECAT_API_BASE_URL}/projects/{project_id}",
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ response.raise_for_status()
+ except requests.HTTPError as e:
+ return False, _format_http_error(e)
+ except requests.RequestException as e:
+ return False, f"Could not reach RevenueCat: {e}"
+
+ return True, None
+
+
+def _ms_to_seconds(value: Any) -> Any:
+ """Convert a millisecond epoch int to a Unix-seconds int.
+
+ RevenueCat returns timestamps as millisecond epochs (e.g. ``1658399423658``),
+ but the warehouse partition layer interprets bare ints as Unix *seconds*
+ (``datetime.datetime.fromtimestamp(date)``). Normalize to seconds so a
+ datetime partition on ``created_at`` produces sane bucket dates, matching
+ the convention used by other sources (Stripe's ``created`` is already in
+ seconds).
+ """
+ if isinstance(value, int) and not isinstance(value, bool):
+ return value // 1000
+ return value
+
+
+def iterate_list_endpoint(
+ api_key: str,
+ project_id: str,
+ path_suffix: str,
+ *,
+ endpoint_name: str,
+ timestamp_fields: tuple[str, ...] = ("created_at",),
+ starting_after: str | None = None,
+ on_cursor_advance: Callable[[str, str], None] | None = None,
+) -> Iterator[dict[str, Any]]:
+ """Yield rows from a RevenueCat v2 list endpoint, transparently following the cursor.
+
+ RevenueCat returns ``{"items": [...], "next_page": "/v2/path?starting_after=ID"}``.
+ When ``next_page`` is null/absent, the list is exhausted.
+
+ Rows are normalized in flight: any ms-epoch field named in ``timestamp_fields``
+ is divided by 1000 so it lands in the warehouse as a Unix-seconds int the
+ partition layer can interpret directly. This must cover the endpoint's
+ partition key — which is ``created_at`` for most endpoints but ``first_seen_at``
+ for customers (the customer object has no ``created_at``). See ``_ms_to_seconds``.
+
+ ``on_cursor_advance`` is invoked with the last item's id every time we finish
+ yielding a page so callers (e.g. the resumable manager) can checkpoint. We
+ save state *after* yielding so a crash re-yields the last page rather than
+ skipping it — merge dedupes on primary key.
+ """
+ session = _session(api_key)
+ params: dict[str, Any] = {"limit": DEFAULT_PAGE_SIZE}
+ if starting_after:
+ params["starting_after"] = starting_after
+
+ url = f"{REVENUECAT_API_BASE_URL}{_project_path(project_id, path_suffix)}"
+
+ while True:
+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+ response.raise_for_status()
+ payload = response.json() or {}
+
+ rows = payload.get("items") or []
+ if not isinstance(rows, list):
+ return
+
+ last_id: str | None = None
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ for field in timestamp_fields:
+ if field in row:
+ row[field] = _ms_to_seconds(row[field])
+ yield row
+ # `id` is the declared primary key for every RevenueCat list
+ # endpoint (see settings.py). Access it directly so a malformed
+ # response missing `id` raises `KeyError` here rather than
+ # silently advancing the cursor to a stale value — which would
+ # corrupt the merge/dedupe step downstream.
+ last_id = row["id"]
+
+ next_page = payload.get("next_page")
+ if last_id is not None and on_cursor_advance is not None:
+ on_cursor_advance(endpoint_name, last_id)
+
+ if not next_page:
+ return
+
+ # next_page is a relative path including its own query string (e.g.
+ # `/v2/projects/{id}/customers?starting_after=cus_abc&limit=20`). The
+ # path already encodes the next cursor, so re-send it as-is with no
+ # extra params — passing both `params=` and a query-bearing url would
+ # produce duplicate `limit=` values.
+ url = next_page if next_page.startswith("http") else urljoin(REVENUECAT_API_BASE_URL, next_page)
+ params = {}
+
+
+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
+ via the webhook fields (handled by the surrounding warehouse-source flow).
+ """
+ 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,
+ }
+ 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
+
+ url = f"{REVENUECAT_API_BASE_URL}{_project_path(project_id, '/integrations/webhook')}"
+
+ 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."
+ ),
+ )
+ # 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
+ # responses, so we can't tell whether one is already set.
+ return WebhookCreationResult(success=True, pending_inputs=["authorization_header"])
+
+ 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))
+ 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))
+ return WebhookCreationResult(success=False, error=f"Could not reach RevenueCat: {e}")
+
+ pending: list[str] = []
+ if not authorization_header_value:
+ pending.append("authorization_header")
+ return WebhookCreationResult(success=True, pending_inputs=pending)
+
+
+def _list_webhook_integrations(api_key: str, project_id: str) -> list[dict[str, Any]]:
+ """Iterate the webhook integrations under a project, following cursor pages."""
+ 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')}"
+
+ while True:
+ # Build the URL with explicit query encoding so the call signature stays
+ # stable across pages and we never accidentally pass duplicate `limit`s.
+ request_url = f"{url}?{urlencode(params)}" if params else url
+ response = session.get(request_url, timeout=REQUEST_TIMEOUT_SECONDS)
+ response.raise_for_status()
+ payload = response.json() or {}
+
+ page = payload.get("items") or []
+ if isinstance(page, list):
+ for hook in page:
+ if isinstance(hook, dict):
+ items.append(hook)
+
+ next_page = payload.get("next_page")
+ if not next_page:
+ return items
+ url = next_page if next_page.startswith("http") else urljoin(REVENUECAT_API_BASE_URL, next_page)
+ params = {}
+
+
+def _find_webhook_integration(api_key: str, project_id: str, webhook_url: str) -> dict[str, Any] | None:
+ try:
+ integrations = _list_webhook_integrations(api_key, project_id)
+ except requests.RequestException:
+ return None
+ for hook in integrations:
+ if hook.get("url") == webhook_url:
+ return hook
+ return None
+
+
+def delete_webhook(api_key: str, project_id: str, webhook_url: str) -> WebhookDeletionResult:
+ logger = LOGGER.bind(project_id=project_id)
+
+ try:
+ integrations = _list_webhook_integrations(api_key, project_id)
+ except requests.HTTPError as e:
+ logger.warning("Failed to list RevenueCat webhook integrations", error=str(e))
+ return WebhookDeletionResult(success=False, error=_format_http_error(e))
+ except requests.RequestException as e:
+ logger.warning("Could not reach RevenueCat to list webhooks", error=str(e))
+ return WebhookDeletionResult(success=False, error=f"Could not reach RevenueCat: {e}")
+
+ target = next((hook for hook in integrations if hook.get("url") == webhook_url), None)
+ if target is None:
+ # Nothing to delete is a success — keep delete idempotent.
+ return WebhookDeletionResult(success=True)
+
+ webhook_id = target.get("id")
+ if not webhook_id:
+ return WebhookDeletionResult(
+ success=False,
+ error="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}')}"
+ try:
+ response = _session(api_key).delete(url, timeout=REQUEST_TIMEOUT_SECONDS)
+ if response.status_code == 404:
+ return WebhookDeletionResult(success=True)
+ response.raise_for_status()
+ except requests.HTTPError as e:
+ logger.warning("Failed to delete RevenueCat webhook integration", error=str(e))
+ return WebhookDeletionResult(success=False, error=_format_http_error(e))
+ except requests.RequestException as e:
+ logger.warning("Could not reach RevenueCat to delete webhook", error=str(e))
+ return WebhookDeletionResult(success=False, error=f"Could not reach RevenueCat: {e}")
+
+ return WebhookDeletionResult(success=True)
+
+
+def get_external_webhook_info(api_key: str, project_id: str, webhook_url: str) -> ExternalWebhookInfo:
+ try:
+ integrations = _list_webhook_integrations(api_key, project_id)
+ except requests.HTTPError as e:
+ return ExternalWebhookInfo(exists=False, error=_format_http_error(e))
+ except requests.RequestException as e:
+ return ExternalWebhookInfo(exists=False, error=f"Could not reach RevenueCat: {e}")
+
+ target = next((hook for hook in integrations if hook.get("url") == webhook_url), None)
+ if target is None:
+ return ExternalWebhookInfo(exists=False)
+
+ events_value = target.get("events")
+ enabled_events = events_value if isinstance(events_value, list) else None
+ created_at_raw = target.get("created_at")
+ created_at = str(created_at_raw) if created_at_raw is not None else None
+
+ return ExternalWebhookInfo(
+ exists=True,
+ url=target.get("url"),
+ enabled_events=enabled_events,
+ # RevenueCat doesn't expose an enabled/disabled state on the integration
+ # object — once created, it's active. Report "enabled" to surface that.
+ status="enabled",
+ description=target.get("name"),
+ created_at=created_at,
+ )
diff --git a/posthog/temporal/data_imports/sources/revenuecat/settings.py b/posthog/temporal/data_imports/sources/revenuecat/settings.py
new file mode 100644
index 000000000000..6543a2d8f8c0
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/revenuecat/settings.py
@@ -0,0 +1,85 @@
+"""RevenueCat API v2 endpoint catalog.
+
+Reference: https://www.revenuecat.com/docs/api-v2
+
+Every list endpoint here uses cursor pagination (`starting_after` / `next_page`),
+defaulted to `limit=100`. Field names match the RevenueCat response payloads
+verbatim, except each endpoint's partition timestamp field which is normalized
+from milliseconds to Unix seconds during iteration (see ``_ms_to_seconds`` in
+``revenuecat.py``). The partition key pins to that normalized field — it's stable
+per row and never rewritten, so partitioning by it never re-shuffles data.
+
+Note the partition field is not uniform across endpoints: the customer object
+has no ``created_at`` — it exposes ``first_seen_at`` (the stable first-seen
+timestamp) instead — while the dashboard-configured resources (products,
+entitlements, offerings, apps) carry ``created_at``.
+"""
+
+from typing import NamedTuple
+
+from posthog.temporal.data_imports.sources.revenuecat.constants import (
+ APP_RESOURCE_NAME,
+ CUSTOMER_RESOURCE_NAME,
+ ENTITLEMENT_RESOURCE_NAME,
+ EVENT_RESOURCE_NAME,
+ OFFERING_RESOURCE_NAME,
+ PRODUCT_RESOURCE_NAME,
+)
+
+
+class RevenueCatEndpoint(NamedTuple):
+ """Single RevenueCat API v2 list endpoint.
+
+ `path_suffix` is appended to `/projects/{project_id}` — every list endpoint we
+ sync from is project-scoped. `partition_keys` must be stable for the lifetime
+ of a row (never `updated_at` / `last_seen_at`); ``created_at`` (or
+ ``first_seen_at`` for customers), normalized from RevenueCat's ms representation
+ to Unix seconds, satisfies that requirement.
+ """
+
+ path_suffix: str
+ primary_keys: list[str]
+ partition_keys: list[str]
+
+
+# All endpoints we expose as warehouse tables from the REST API. RevenueCat's
+# customer subscriptions/purchases live under per-customer paths (which would
+# require a fan-out) — those are intentionally omitted here in favor of the
+# realtime webhook events table, which captures the same activity per-purchase
+# without needing to iterate every customer on every sync.
+REVENUECAT_API_ENDPOINTS: dict[str, RevenueCatEndpoint] = {
+ CUSTOMER_RESOURCE_NAME: RevenueCatEndpoint(
+ path_suffix="/customers",
+ primary_keys=["id"],
+ # The customer object has no `created_at`; `first_seen_at` is its stable
+ # creation-time timestamp (`last_seen_at` is rewritten, so unsuitable).
+ partition_keys=["first_seen_at"],
+ ),
+ PRODUCT_RESOURCE_NAME: RevenueCatEndpoint(
+ path_suffix="/products",
+ primary_keys=["id"],
+ partition_keys=["created_at"],
+ ),
+ ENTITLEMENT_RESOURCE_NAME: RevenueCatEndpoint(
+ path_suffix="/entitlements",
+ primary_keys=["id"],
+ partition_keys=["created_at"],
+ ),
+ OFFERING_RESOURCE_NAME: RevenueCatEndpoint(
+ path_suffix="/offerings",
+ primary_keys=["id"],
+ partition_keys=["created_at"],
+ ),
+ APP_RESOURCE_NAME: RevenueCatEndpoint(
+ path_suffix="/apps",
+ primary_keys=["id"],
+ partition_keys=["created_at"],
+ ),
+}
+
+REVENUECAT_API_SCHEMA_NAMES: tuple[str, ...] = tuple(REVENUECAT_API_ENDPOINTS.keys())
+
+# Webhook-only schemas. We expose a single `events` table that captures every
+# RevenueCat webhook event regardless of type — events share a flat shape and
+# querying them in one table is more ergonomic than fanning out per-type tables.
+REVENUECAT_WEBHOOK_SCHEMA_NAMES: tuple[str, ...] = (EVENT_RESOURCE_NAME,)
diff --git a/posthog/temporal/data_imports/sources/revenuecat/source.py b/posthog/temporal/data_imports/sources/revenuecat/source.py
index 532a7834508c..2d7b18268da6 100644
--- a/posthog/temporal/data_imports/sources/revenuecat/source.py
+++ b/posthog/temporal/data_imports/sources/revenuecat/source.py
@@ -1,29 +1,373 @@
-from typing import cast
+from collections.abc import AsyncIterable, Iterable
+from typing import TYPE_CHECKING, Any, Optional, cast
+
+import orjson
+import pyarrow as pa
+from asgiref.sync import async_to_sync
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.pipelines.pipeline.utils import table_from_py_list
+from posthog.temporal.data_imports.sources.common.base import (
+ ExternalWebhookInfo,
+ FieldType,
+ ResumableSource,
+ WebhookCreationResult,
+ WebhookDeletionResult,
+ WebhookSource,
+)
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
+from posthog.temporal.data_imports.sources.common.webhook_s3 import (
+ WebhookSourceManager,
+ is_webhook_feature_flag_enabled,
+)
from posthog.temporal.data_imports.sources.generated_configs import RevenueCatSourceConfig
+from posthog.temporal.data_imports.sources.revenuecat import revenuecat as api_client
+from posthog.temporal.data_imports.sources.revenuecat.constants import (
+ EVENT_RESOURCE_NAME,
+ RESOURCE_TO_REVENUECAT_EVENT_TYPE,
+)
+from posthog.temporal.data_imports.sources.revenuecat.revenuecat import RevenueCatResumeConfig
+from posthog.temporal.data_imports.sources.revenuecat.settings import (
+ REVENUECAT_API_ENDPOINTS,
+ REVENUECAT_API_SCHEMA_NAMES,
+ REVENUECAT_WEBHOOK_SCHEMA_NAMES,
+)
from products.data_warehouse.backend.types import ExternalDataSourceType
+if TYPE_CHECKING:
+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
+
+
+REVENUECAT_API_KEYS_URL = "https://app.revenuecat.com/projects/_/api-keys"
+
+
+def _webhook_table_transformer(table: pa.Table) -> pa.Table:
+ """Unwrap RevenueCat's ``{"event": {...}, "api_version": "1.0"}`` envelope.
+
+ Webhook deliveries land in S3 as raw POST bodies. RevenueCat nests the
+ interesting payload under ``event`` — we hoist it so the warehouse table
+ columns match the documented event field names directly. ``api_version`` is
+ kept as a sibling column so consumers can detect upstream schema changes.
+
+ We also derive a ``created_at`` field (Unix seconds) from RevenueCat's
+ ``event_timestamp_ms`` so this table can share the same datetime partition
+ convention as the API endpoints. The original ``event_timestamp_ms`` is
+ preserved unchanged for callers that need sub-second precision.
+ """
+ if "event" not in table.column_names:
+ return table_from_py_list([])
+
+ event_col = table.column("event").to_pylist()
+ api_version_col = (
+ table.column("api_version").to_pylist() if "api_version" in table.column_names else [None] * table.num_rows
+ )
+
+ rows: list[dict[str, Any]] = []
+ for event, api_version in zip(event_col, api_version_col):
+ if event is None:
+ continue
+ # Defensive: `event` typically arrives as a nested dict (pyarrow struct),
+ # but we accept a JSON-serialized string too in case the upstream
+ # buffering layer flattens nested structures.
+ row = orjson.loads(event) if isinstance(event, (str, bytes)) else dict(event)
+ row["api_version"] = api_version
+ event_ts_ms = row.get("event_timestamp_ms")
+ if isinstance(event_ts_ms, int) and not isinstance(event_ts_ms, bool):
+ row["created_at"] = event_ts_ms // 1000
+ rows.append(row)
+
+ return table_from_py_list(rows)
+
@SourceRegistry.register
-class RevenueCatSource(SimpleSource[RevenueCatSourceConfig]):
+class RevenueCatSource(
+ ResumableSource[RevenueCatSourceConfig, RevenueCatResumeConfig],
+ WebhookSource[RevenueCatSourceConfig],
+):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.REVENUECAT
+ @property
+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:
+ from posthog.temporal.data_imports.sources.revenuecat.webhook_template import template
+
+ return template
+
+ @property
+ def webhook_resource_map(self) -> dict[str, str]:
+ return RESOURCE_TO_REVENUECAT_EVENT_TYPE
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.REVENUE_CAT,
label="RevenueCat",
+ caption=(
+ "Connect your RevenueCat project using a "
+ f"[v2 secret API key]({REVENUECAT_API_KEYS_URL}). PostHog uses the key to pull "
+ "customers, products, entitlements, offerings, and apps, and to register a webhook "
+ "integration for realtime subscription and purchase events."
+ ),
iconPath="/static/services/revenuecat.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/revenuecat",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="secret_api_key",
+ label="Secret API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="sk_...",
+ caption=(
+ f"Generate a [v2 secret API key]({REVENUECAT_API_KEYS_URL}) "
+ "with read access to customers, products, entitlements, offerings, "
+ "apps, and integrations (read/write for automatic webhook setup)."
+ ),
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="project_id",
+ label="Project ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="proj1a2b3c4d5e",
+ caption=(
+ "Find this in your RevenueCat dashboard URL: `app.revenuecat.com/projects/<project_id>`."
+ ),
+ secret=False,
+ ),
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
+ featureFlag="dwh-revenuecat",
+ 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"
+ "**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"
+ "3. Set the **Authorization header** to a secret value you generate locally — "
+ "paste the same value into the field below so PostHog can verify deliveries\n"
+ "4. Select **All events** under **Send events**\n"
+ "5. Click **Save**"
+ ),
+ webhookFields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="authorization_header",
+ label="Authorization header value",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="Bearer my-secret",
+ caption=(
+ "The exact value RevenueCat will send in the Authorization header. "
+ "Must match what's configured in the RevenueCat webhook integration."
+ ),
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized": (
+ "RevenueCat rejected the API key. Generate a new v2 secret API key and reconnect."
+ ),
+ "403 Client Error: Forbidden": (
+ "The API key doesn't have permission for this endpoint. Check that the key has "
+ "read access to the resources you're syncing."
+ ),
+ "404 Client Error: Not Found": (
+ "RevenueCat could not find the project. Double-check the project id and that the API key belongs to it."
+ ),
+ }
+
+ def validate_credentials(
+ self, config: RevenueCatSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return api_client.validate_credentials(config.secret_api_key, config.project_id)
+
+ def get_schemas(
+ self,
+ config: RevenueCatSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ webhook_supported = is_webhook_feature_flag_enabled(team_id)
+ # `events` is webhook-only — the v2 API doesn't expose a historical
+ # backfill endpoint for webhook events, so the only way to populate
+ # this table is via realtime webhook deliveries.
+ webhook_schemas = [
+ SourceSchema(
+ name=name,
+ supports_incremental=False,
+ supports_append=False,
+ supports_webhooks=webhook_supported,
+ incremental_fields=[],
+ )
+ for name in REVENUECAT_WEBHOOK_SCHEMA_NAMES
+ ]
+ # API endpoints don't expose a server-side `created_at >= X` filter, so
+ # "incremental" syncs would still scan every page. Default to full
+ # refresh and let the partitioning column (`created_at`) keep delta
+ # writes cheap.
+ api_schemas = [
+ SourceSchema(
+ name=name,
+ supports_incremental=False,
+ supports_append=False,
+ supports_webhooks=False,
+ incremental_fields=[],
+ )
+ for name in REVENUECAT_API_SCHEMA_NAMES
+ ]
+ schemas = [*webhook_schemas, *api_schemas]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RevenueCatResumeConfig]:
+ return ResumableSourceManager[RevenueCatResumeConfig](inputs, RevenueCatResumeConfig)
+
+ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:
+ 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.
+ return api_client.create_webhook(
+ api_key=config.secret_api_key,
+ project_id=config.project_id,
+ webhook_url=webhook_url,
+ )
+
+ 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.
+ 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,
+ webhook_url=webhook_url,
+ authorization_header_value=header_value,
+ )
+ if not creation.success:
+ return False, creation.error or "Failed to bind the new authorization header."
+ return True, None
+
+ def get_external_webhook_info(
+ self, config: RevenueCatSourceConfig, webhook_url: str, team_id: int
+ ) -> ExternalWebhookInfo | None:
+ return api_client.get_external_webhook_info(config.secret_api_key, config.project_id, webhook_url)
+
+ def delete_webhook(self, config: RevenueCatSourceConfig, webhook_url: str, team_id: int) -> WebhookDeletionResult:
+ return api_client.delete_webhook(config.secret_api_key, config.project_id, webhook_url)
+
+ def source_for_pipeline(
+ self,
+ config: RevenueCatSourceConfig,
+ resumable_source_manager: ResumableSourceManager[RevenueCatResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name == EVENT_RESOURCE_NAME:
+ return self._webhook_source_response(inputs)
+ return self._api_source_response(config, resumable_source_manager, inputs)
+
+ def _webhook_source_response(self, inputs: SourceInputs) -> SourceResponse:
+ webhook_source_manager = self.get_webhook_source_manager(inputs)
+ webhook_enabled = async_to_sync(webhook_source_manager.webhook_enabled)(True)
+
+ def items() -> Iterable[Any] | AsyncIterable[Any]:
+ if webhook_enabled:
+ return webhook_source_manager.get_items(table_transformer=_webhook_table_transformer)
+ return iter([])
+
+ return SourceResponse(
+ items=items,
+ primary_keys=["id"],
+ name=inputs.schema_name,
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="week",
+ # `created_at` is derived in the webhook transformer from
+ # `event_timestamp_ms / 1000` so it lands here as Unix seconds —
+ # the partition layer treats bare ints as seconds, so this gives
+ # us correctly-bucketed weekly partitions.
+ partition_keys=["created_at"],
+ )
+
+ def _api_source_response(
+ self,
+ config: RevenueCatSourceConfig,
+ resumable_source_manager: ResumableSourceManager[RevenueCatResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ endpoint = REVENUECAT_API_ENDPOINTS[inputs.schema_name]
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ starting_after = resume.starting_after if resume is not None and resume.endpoint == inputs.schema_name else None
+
+ def on_cursor_advance(endpoint_name: str, last_id: str) -> None:
+ resumable_source_manager.save_state(RevenueCatResumeConfig(endpoint=endpoint_name, starting_after=last_id))
+
+ def items() -> Iterable[dict[str, Any]]:
+ yield from api_client.iterate_list_endpoint(
+ api_key=config.secret_api_key,
+ project_id=config.project_id,
+ path_suffix=endpoint.path_suffix,
+ endpoint_name=inputs.schema_name,
+ timestamp_fields=tuple(endpoint.partition_keys),
+ starting_after=starting_after,
+ on_cursor_advance=on_cursor_advance,
+ )
+
+ # Datetime partitioning on the endpoint's timestamp field (`created_at`,
+ # or `first_seen_at` for customers) — `iterate_list_endpoint` normalizes
+ # RevenueCat's ms-epoch value down to Unix seconds so the partition layer
+ # (which treats bare ints as seconds) produces sane bucket dates.
+ return SourceResponse(
+ items=items,
+ primary_keys=endpoint.primary_keys,
+ name=inputs.schema_name,
+ partition_keys=endpoint.partition_keys,
+ partition_mode="datetime",
+ partition_format="week",
+ partition_count=1,
+ partition_size=1,
)
diff --git a/posthog/temporal/data_imports/sources/revenuecat/tests/test_revenuecat.py b/posthog/temporal/data_imports/sources/revenuecat/tests/test_revenuecat.py
new file mode 100644
index 000000000000..745d4dc43eff
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/revenuecat/tests/test_revenuecat.py
@@ -0,0 +1,438 @@
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from posthog.temporal.data_imports.sources.revenuecat import revenuecat as api_client
+from posthog.temporal.data_imports.sources.revenuecat.constants import (
+ REVENUECAT_API_BASE_URL,
+ REVENUECAT_AUTO_WEBHOOK_NAME,
+ REVENUECAT_WEBHOOK_EVENT_TYPES,
+)
+
+
+def _ok_json_response(payload: dict | list | None = None, status_code: int = 200) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.json.return_value = payload if payload is not None else {}
+ response.raise_for_status = MagicMock()
+ return response
+
+
+def _http_error_response(status_code: int) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.raise_for_status.side_effect = requests.HTTPError(response=response)
+ return response
+
+
+class TestValidateCredentials:
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")
+ def test_returns_true_when_projects_list_succeeds(self, mock_session):
+ mock_session.return_value.get.return_value = _ok_json_response({"items": []})
+
+ success, error = api_client.validate_credentials("sk_test", project_id=None)
+
+ assert success is True
+ assert error is None
+ called_url = mock_session.return_value.get.call_args.args[0]
+ assert called_url == f"{REVENUECAT_API_BASE_URL}/projects"
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")
+ def test_also_checks_project_when_id_provided(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _ok_json_response({"items": []}),
+ _ok_json_response({"id": "proj_test"}),
+ ]
+
+ success, _ = api_client.validate_credentials("sk_test", project_id="proj_test")
+
+ assert success is True
+ # Second call hits the project-specific endpoint.
+ second_call_url = mock_session.return_value.get.call_args_list[1].args[0]
+ assert second_call_url == f"{REVENUECAT_API_BASE_URL}/projects/proj_test"
+
+ @parameterized.expand(
+ [
+ (401, "rejected the API key"),
+ (403, "denied"),
+ (404, "could not find"),
+ (429, "rate-limited"),
+ (500, "RevenueCat API error"),
+ ]
+ )
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")
+ def test_returns_false_on_http_error(self, status_code, expected_substring, mock_session):
+ mock_session.return_value.get.return_value = _http_error_response(status_code)
+
+ success, error = api_client.validate_credentials("sk_test", project_id=None)
+
+ assert success is False
+ assert error is not None
+ assert expected_substring.lower() in error.lower()
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")
+ def test_returns_false_on_network_error(self, mock_session):
+ mock_session.return_value.get.side_effect = requests.ConnectionError("dns fail")
+
+ success, error = api_client.validate_credentials("sk_test", project_id=None)
+
+ assert success is False
+ assert error is not None
+ assert "Could not reach RevenueCat" in error
+
+ @parameterized.expand(
+ [
+ (401, "rejected the API key"),
+ (403, "denied"),
+ (404, "could not find"),
+ (429, "rate-limited"),
+ (500, "RevenueCat API error"),
+ ]
+ )
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")
+ def test_returns_false_when_project_specific_call_fails(self, status_code, expected_substring, mock_session):
+ # The first call (`GET /projects`) succeeds, but the per-project follow-up
+ # (`GET /projects/{id}`) fails. `_format_http_error` is shared between
+ # both call sites, so without this branch a regression in the per-project
+ # path would go unnoticed.
+ mock_session.return_value.get.side_effect = [
+ _ok_json_response({"items": []}),
+ _http_error_response(status_code),
+ ]
+
+ success, error = api_client.validate_credentials("sk_test", project_id="proj_test")
+
+ assert success is False
+ assert error is not None
+ assert expected_substring.lower() in error.lower()
+
+
+class TestIterateListEndpoint:
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")
+ def test_follows_next_page_until_exhausted(self, mock_session):
+ # Two pages: first returns one row + a relative next_page, second
+ # returns one row with no next_page. The iterator should yield both
+ # rows in order and stop without making a third call.
+ first = _ok_json_response(
+ {
+ "items": [{"id": "cus_1", "name": "first"}],
+ "next_page": "/v2/projects/proj_test/customers?starting_after=cus_1&limit=100",
+ }
+ )
+ second = _ok_json_response({"items": [{"id": "cus_2", "name": "second"}], "next_page": None})
+ mock_session.return_value.get.side_effect = [first, second]
+
+ rows = list(
+ api_client.iterate_list_endpoint(
+ "sk_test",
+ project_id="proj_test",
+ path_suffix="/customers",
+ endpoint_name="customers",
+ )
+ )
+
+ assert rows == [{"id": "cus_1", "name": "first"}, {"id": "cus_2", "name": "second"}]
+ assert mock_session.return_value.get.call_count == 2
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")
+ def test_invokes_on_cursor_advance_with_last_row_id_per_page(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _ok_json_response(
+ {
+ "items": [{"id": "cus_1"}, {"id": "cus_2"}],
+ "next_page": "/v2/projects/proj_test/customers?starting_after=cus_2",
+ }
+ ),
+ _ok_json_response({"items": [{"id": "cus_3"}], "next_page": None}),
+ ]
+ seen: list[tuple[str, str]] = []
+
+ list(
+ api_client.iterate_list_endpoint(
+ "sk_test",
+ project_id="proj_test",
+ path_suffix="/customers",
+ endpoint_name="customers",
+ on_cursor_advance=lambda name, last_id: seen.append((name, last_id)),
+ )
+ )
+
+ # Saved after each page's last row — never before, otherwise a crash
+ # would skip the page rather than re-yield it (merge dedupes on PK).
+ assert seen == [("customers", "cus_2"), ("customers", "cus_3")]
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")
+ def test_uses_starting_after_when_resuming(self, mock_session):
+ mock_session.return_value.get.return_value = _ok_json_response({"items": [], "next_page": None})
+
+ list(
+ api_client.iterate_list_endpoint(
+ "sk_test",
+ project_id="proj_test",
+ path_suffix="/customers",
+ endpoint_name="customers",
+ starting_after="cus_42",
+ )
+ )
+
+ called_params = mock_session.return_value.get.call_args.kwargs["params"]
+ assert called_params["starting_after"] == "cus_42"
+ assert called_params["limit"] == api_client.DEFAULT_PAGE_SIZE
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")
+ def test_returns_immediately_when_items_missing(self, mock_session):
+ # Defensive: a 200 with no `items` field should be treated as an empty
+ # page rather than crashing on `None.append`.
+ mock_session.return_value.get.return_value = _ok_json_response({"next_page": None})
+
+ rows = list(
+ api_client.iterate_list_endpoint(
+ "sk_test", project_id="proj_test", path_suffix="/customers", endpoint_name="customers"
+ )
+ )
+
+ assert rows == []
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")
+ def test_skips_non_dict_rows(self, mock_session):
+ mock_session.return_value.get.return_value = _ok_json_response(
+ {"items": [{"id": "ok"}, "noise", 42], "next_page": None}
+ )
+
+ rows = list(
+ api_client.iterate_list_endpoint(
+ "sk_test", project_id="proj_test", path_suffix="/customers", endpoint_name="customers"
+ )
+ )
+
+ assert rows == [{"id": "ok"}]
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")
+ def test_normalizes_created_at_from_ms_to_seconds(self, mock_session):
+ # `created_at` comes back from RevenueCat as a millisecond epoch — we
+ # divide by 1000 so the partition layer (which treats bare ints as Unix
+ # seconds) buckets rows into the correct week.
+ mock_session.return_value.get.return_value = _ok_json_response(
+ {"items": [{"id": "cus_1", "created_at": 1658399423658}], "next_page": None}
+ )
+
+ rows = list(
+ api_client.iterate_list_endpoint(
+ "sk_test", project_id="proj_test", path_suffix="/customers", endpoint_name="customers"
+ )
+ )
+
+ assert rows == [{"id": "cus_1", "created_at": 1658399423}]
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")
+ def test_leaves_created_at_untouched_when_missing(self, mock_session):
+ mock_session.return_value.get.return_value = _ok_json_response({"items": [{"id": "cus_1"}], "next_page": None})
+
+ rows = list(
+ api_client.iterate_list_endpoint(
+ "sk_test", project_id="proj_test", path_suffix="/customers", endpoint_name="customers"
+ )
+ )
+
+ assert rows == [{"id": "cus_1"}]
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")
+ def test_normalizes_configured_timestamp_field(self, mock_session):
+ # The customer object has no `created_at` — it partitions by
+ # `first_seen_at`, so that's the field that must be normalized to seconds.
+ mock_session.return_value.get.return_value = _ok_json_response(
+ {
+ "items": [{"id": "cus_1", "first_seen_at": 1658399423658, "last_seen_at": 1700000000000}],
+ "next_page": None,
+ }
+ )
+
+ rows = list(
+ api_client.iterate_list_endpoint(
+ "sk_test",
+ project_id="proj_test",
+ path_suffix="/customers",
+ endpoint_name="customers",
+ timestamp_fields=("first_seen_at",),
+ )
+ )
+
+ # `first_seen_at` is normalized; `last_seen_at` (not the partition key) is
+ # left as the raw ms epoch.
+ assert rows == [{"id": "cus_1", "first_seen_at": 1658399423, "last_seen_at": 1700000000000}]
+
+
+class TestMsToSeconds:
+ def test_converts_int_milliseconds_to_seconds(self):
+ assert api_client._ms_to_seconds(1658399423658) == 1658399423
+
+ def test_passes_through_non_int_values(self):
+ # Defensive: don't mangle nulls, strings, or anything else the API
+ # might surprise us with — only ints get the division.
+ assert api_client._ms_to_seconds(None) is None
+ assert api_client._ms_to_seconds("1658399423658") == "1658399423658"
+
+ def test_does_not_treat_bool_as_int(self):
+ # `bool` subclasses `int` in Python, which would silently turn `True`
+ # into `0` (1 // 1000). Make sure we don't fall into that trap.
+ assert api_client._ms_to_seconds(True) is True
+ assert api_client._ms_to_seconds(False) is False
+
+
+class TestCreateWebhook:
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._find_webhook_integration")
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")
+ def test_creates_webhook_with_all_known_event_types(self, mock_session, mock_find):
+ mock_find.return_value = None
+ mock_session.return_value.post.return_value = _ok_json_response({"id": "wh_1"})
+
+ result = api_client.create_webhook(
+ "sk_test",
+ project_id="proj_test",
+ webhook_url="https://example.com/h",
+ authorization_header_value="Bearer my-secret",
+ )
+
+ assert result.success is True
+ # If we don't pass back the auth header value we asked for it as a
+ # pending input, so this list should be empty when we supplied one
+ # 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"
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._find_webhook_integration")
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")
+ def test_treats_existing_webhook_as_success_with_pending_authorization(self, mock_session, mock_find):
+ mock_find.return_value = {"id": "wh_existing", "url": "https://example.com/h"}
+
+ result = api_client.create_webhook("sk_test", project_id="proj_test", webhook_url="https://example.com/h")
+
+ assert result.success is True
+ assert result.pending_inputs == ["authorization_header"]
+ mock_session.return_value.post.assert_not_called()
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._find_webhook_integration")
+ @patch("posthog.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"}
+
+ result = api_client.create_webhook(
+ "sk_test",
+ project_id="proj_test",
+ webhook_url="https://example.com/h",
+ 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()
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._find_webhook_integration")
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")
+ def test_reports_pending_authorization_header_when_not_supplied(self, mock_session, mock_find):
+ mock_find.return_value = None
+ mock_session.return_value.post.return_value = _ok_json_response({"id": "wh_1"})
+
+ result = api_client.create_webhook("sk_test", project_id="proj_test", webhook_url="https://example.com/h")
+
+ assert result.success is True
+ assert result.pending_inputs == ["authorization_header"]
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._find_webhook_integration")
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")
+ def test_translates_403_into_permission_error(self, mock_session, mock_find):
+ mock_find.return_value = None
+ mock_session.return_value.post.return_value = _http_error_response(403)
+
+ result = api_client.create_webhook("sk_test", project_id="proj_test", webhook_url="https://example.com/h")
+
+ assert result.success is False
+ assert result.error is not None
+ assert "denied" in result.error.lower()
+
+
+class TestDeleteWebhook:
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._list_webhook_integrations")
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")
+ def test_deletes_matching_webhook(self, mock_session, mock_list):
+ mock_list.return_value = [{"id": "wh_1", "url": "https://example.com/h"}]
+ mock_session.return_value.delete.return_value = _ok_json_response()
+
+ result = api_client.delete_webhook("sk_test", project_id="proj_test", webhook_url="https://example.com/h")
+
+ assert result.success is True
+ called_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"
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._list_webhook_integrations")
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")
+ def test_returns_success_when_webhook_not_found(self, mock_session, mock_list):
+ # Idempotent delete — missing webhook is treated as already gone, not
+ # as a failure to surface to users.
+ mock_list.return_value = []
+
+ result = api_client.delete_webhook("sk_test", project_id="proj_test", webhook_url="https://example.com/h")
+
+ assert result.success is True
+ mock_session.return_value.delete.assert_not_called()
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._list_webhook_integrations")
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._session")
+ def test_404_on_delete_treated_as_success(self, mock_session, mock_list):
+ mock_list.return_value = [{"id": "wh_1", "url": "https://example.com/h"}]
+ mock_session.return_value.delete.return_value = _ok_json_response(status_code=404)
+
+ result = api_client.delete_webhook("sk_test", project_id="proj_test", webhook_url="https://example.com/h")
+
+ assert result.success is True
+
+
+class TestGetExternalWebhookInfo:
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._list_webhook_integrations")
+ def test_returns_info_for_matching_webhook(self, mock_list):
+ mock_list.return_value = [
+ {
+ "id": "wh_1",
+ "url": "https://example.com/h",
+ "events": ["INITIAL_PURCHASE", "RENEWAL"],
+ "name": "PostHog data warehouse",
+ "created_at": 1658399423658,
+ }
+ ]
+
+ info = api_client.get_external_webhook_info(
+ "sk_test", project_id="proj_test", webhook_url="https://example.com/h"
+ )
+
+ assert info.exists is True
+ assert info.url == "https://example.com/h"
+ assert info.enabled_events == ["INITIAL_PURCHASE", "RENEWAL"]
+ assert info.status == "enabled"
+ assert info.description == "PostHog data warehouse"
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.revenuecat._list_webhook_integrations")
+ def test_returns_not_found_when_no_match(self, mock_list):
+ mock_list.return_value = [{"id": "wh_1", "url": "https://other.example.com"}]
+
+ info = api_client.get_external_webhook_info(
+ "sk_test", project_id="proj_test", webhook_url="https://example.com/h"
+ )
+
+ assert info.exists is False
+
+
+class TestProjectPath:
+ def test_combines_project_id_with_suffix(self):
+ assert api_client._project_path("proj_test", "/customers") == "/projects/proj_test/customers"
diff --git a/posthog/temporal/data_imports/sources/revenuecat/tests/test_revenuecat_source.py b/posthog/temporal/data_imports/sources/revenuecat/tests/test_revenuecat_source.py
new file mode 100644
index 000000000000..93167b9962f6
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/revenuecat/tests/test_revenuecat_source.py
@@ -0,0 +1,411 @@
+from collections.abc import Iterable
+from typing import cast
+
+from unittest.mock import MagicMock, patch
+
+import pyarrow as pa
+
+from posthog.schema import SourceFieldInputConfig
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.pipelines.pipeline.utils import table_from_py_list
+from posthog.temporal.data_imports.sources.common.base import (
+ ExternalWebhookInfo,
+ WebhookCreationResult,
+ WebhookDeletionResult,
+)
+from posthog.temporal.data_imports.sources.generated_configs import RevenueCatSourceConfig
+from posthog.temporal.data_imports.sources.revenuecat.constants import (
+ CUSTOMER_RESOURCE_NAME,
+ EVENT_RESOURCE_NAME,
+ RESOURCE_TO_REVENUECAT_EVENT_TYPE,
+)
+from posthog.temporal.data_imports.sources.revenuecat.revenuecat import RevenueCatResumeConfig
+from posthog.temporal.data_imports.sources.revenuecat.settings import (
+ REVENUECAT_API_ENDPOINTS,
+ REVENUECAT_API_SCHEMA_NAMES,
+ REVENUECAT_WEBHOOK_SCHEMA_NAMES,
+)
+from posthog.temporal.data_imports.sources.revenuecat.source import RevenueCatSource, _webhook_table_transformer
+
+
+def _config(api_key: str = "sk_test", project_id: str = "proj_test") -> RevenueCatSourceConfig:
+ return RevenueCatSourceConfig(secret_api_key=api_key, project_id=project_id)
+
+
+class TestRevenueCatSourceConfigFields:
+ def test_get_source_config_exposes_required_secret_api_key_and_project_id(self):
+ source = RevenueCatSource()
+ cfg = source.get_source_config
+
+ names = {f.name for f in cfg.fields}
+ assert names == {"secret_api_key", "project_id"}
+
+ api_key_field = next(f for f in cfg.fields if f.name == "secret_api_key")
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+
+ project_field = next(f for f in cfg.fields if f.name == "project_id")
+ assert isinstance(project_field, SourceFieldInputConfig)
+ assert project_field.required is True
+ assert project_field.secret is False
+
+ def test_get_source_config_declares_authorization_header_as_webhook_field(self):
+ source = RevenueCatSource()
+ cfg = source.get_source_config
+
+ assert cfg.webhookFields is not None
+ webhook_field_names = {f.name for f in cfg.webhookFields}
+ assert "authorization_header" in webhook_field_names
+
+ auth_field = next(f for f in cfg.webhookFields if f.name == "authorization_header")
+ assert isinstance(auth_field, SourceFieldInputConfig)
+ assert auth_field.required is True
+ assert auth_field.secret is True
+
+
+class TestRevenueCatSourceWebhookResourceMap:
+ def test_wildcard_funnels_all_events_into_one_table(self):
+ source = RevenueCatSource()
+ mapping = source.webhook_resource_map
+
+ # Single events table — every webhook delivery is routed here regardless
+ # of `event.type`. The wildcard sentinel lets the Hog template skip
+ # per-type lookup.
+ assert mapping == RESOURCE_TO_REVENUECAT_EVENT_TYPE
+ assert mapping[EVENT_RESOURCE_NAME] == "*"
+
+
+class TestRevenueCatSourceGetSchemas:
+ @patch("posthog.temporal.data_imports.sources.revenuecat.source.is_webhook_feature_flag_enabled")
+ def test_includes_both_webhook_and_api_schemas(self, mock_flag):
+ mock_flag.return_value = True
+ source = RevenueCatSource()
+
+ schemas = source.get_schemas(_config(), team_id=1)
+
+ names = {s.name for s in schemas}
+ for name in REVENUECAT_WEBHOOK_SCHEMA_NAMES:
+ assert name in names, f"missing webhook schema: {name}"
+ for name in REVENUECAT_API_SCHEMA_NAMES:
+ assert name in names, f"missing api schema: {name}"
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.source.is_webhook_feature_flag_enabled")
+ def test_only_events_schema_supports_webhooks(self, mock_flag):
+ mock_flag.return_value = True
+ source = RevenueCatSource()
+
+ schemas = source.get_schemas(_config(), team_id=1)
+
+ webhook_supported = {s.name for s in schemas if s.supports_webhooks}
+ assert webhook_supported == set(REVENUECAT_WEBHOOK_SCHEMA_NAMES)
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.source.is_webhook_feature_flag_enabled")
+ def test_webhook_feature_flag_off_disables_webhook_support(self, mock_flag):
+ # When the warehouse-source-webhooks feature flag is disabled for the team,
+ # the events schema is still listed but can't actually receive webhook
+ # data. Reflect that in supports_webhooks so the frontend wizard hides
+ # the webhook UI.
+ mock_flag.return_value = False
+ source = RevenueCatSource()
+
+ schemas = source.get_schemas(_config(), team_id=1)
+
+ webhook_supported = {s.name for s in schemas if s.supports_webhooks}
+ assert webhook_supported == set()
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.source.is_webhook_feature_flag_enabled")
+ def test_filters_by_names_argument(self, mock_flag):
+ mock_flag.return_value = True
+ source = RevenueCatSource()
+
+ schemas = source.get_schemas(_config(), team_id=1, names=["customers", "events"])
+
+ assert {s.name for s in schemas} == {"customers", "events"}
+
+
+class TestRevenueCatSourceCreateWebhook:
+ @patch("posthog.temporal.data_imports.sources.revenuecat.source.api_client.create_webhook")
+ def test_delegates_to_api_client_without_authorization_header(self, mock_create):
+ mock_create.return_value = WebhookCreationResult(success=True, pending_inputs=["authorization_header"])
+ source = RevenueCatSource()
+
+ result = source.create_webhook(_config("k", "p"), "https://example.com/h", team_id=1)
+
+ assert result.success is True
+ assert result.pending_inputs == ["authorization_header"]
+ mock_create.assert_called_once()
+ kwargs = mock_create.call_args.kwargs
+ assert kwargs["api_key"] == "k"
+ assert kwargs["project_id"] == "p"
+ assert kwargs["webhook_url"] == "https://example.com/h"
+
+
+class TestRevenueCatSourceWebhookInputsUpdated:
+ @patch("posthog.temporal.data_imports.sources.revenuecat.source.api_client.create_webhook")
+ @patch("posthog.temporal.data_imports.sources.revenuecat.source.api_client.delete_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)
+ mock_create.return_value = WebhookCreationResult(success=True)
+ source = RevenueCatSource()
+
+ success, error = source.webhook_inputs_updated(
+ _config("k", "p"),
+ "https://example.com/h",
+ team_id=1,
+ inputs={"authorization_header": "Bearer my-secret"},
+ )
+
+ assert success is True
+ assert error is None
+ mock_delete.assert_called_once_with("k", "p", "https://example.com/h")
+ mock_create.assert_called_once()
+ kwargs = mock_create.call_args.kwargs
+ assert kwargs["authorization_header_value"] == "Bearer my-secret"
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.source.api_client.create_webhook")
+ @patch("posthog.temporal.data_imports.sources.revenuecat.source.api_client.delete_webhook")
+ def test_skips_recreate_when_authorization_header_missing(self, mock_delete, mock_create):
+ source = RevenueCatSource()
+
+ success, error = source.webhook_inputs_updated(_config(), "https://example.com/h", team_id=1, inputs={})
+
+ assert success is True
+ assert error is None
+ mock_delete.assert_not_called()
+ mock_create.assert_not_called()
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.source.api_client.create_webhook")
+ @patch("posthog.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")
+ source = RevenueCatSource()
+
+ success, error = source.webhook_inputs_updated(
+ _config(), "https://example.com/h", team_id=1, inputs={"authorization_header": "x"}
+ )
+
+ assert success is False
+ assert error == "boom"
+ mock_create.assert_not_called()
+
+
+class TestRevenueCatSourceDeleteWebhook:
+ @patch("posthog.temporal.data_imports.sources.revenuecat.source.api_client.delete_webhook")
+ def test_delegates_to_api_client(self, mock_delete):
+ mock_delete.return_value = WebhookDeletionResult(success=True)
+ source = RevenueCatSource()
+
+ result = source.delete_webhook(_config("k", "p"), "https://example.com/h", team_id=1)
+
+ assert result.success is True
+ mock_delete.assert_called_once_with("k", "p", "https://example.com/h")
+
+
+class TestRevenueCatSourceExternalWebhookInfo:
+ @patch("posthog.temporal.data_imports.sources.revenuecat.source.api_client.get_external_webhook_info")
+ def test_delegates_to_api_client(self, mock_info):
+ mock_info.return_value = ExternalWebhookInfo(exists=True, status="enabled")
+ source = RevenueCatSource()
+
+ info = source.get_external_webhook_info(_config("k", "p"), "https://example.com/h", team_id=1)
+
+ assert info is not None
+ assert info.exists is True
+ mock_info.assert_called_once_with("k", "p", "https://example.com/h")
+
+
+class TestRevenueCatSourceValidateCredentials:
+ @patch("posthog.temporal.data_imports.sources.revenuecat.source.api_client.validate_credentials")
+ def test_delegates_to_api_client(self, mock_validate):
+ mock_validate.return_value = (True, None)
+ source = RevenueCatSource()
+
+ success, error = source.validate_credentials(_config("k", "p"), team_id=1)
+
+ assert success is True
+ assert error is None
+ mock_validate.assert_called_once_with("k", "p")
+
+
+class TestRevenueCatSourcePipelineDispatch:
+ @patch("posthog.temporal.data_imports.sources.revenuecat.source.api_client.iterate_list_endpoint")
+ def test_api_schema_routes_to_iterate_list_endpoint(self, mock_iter):
+ mock_iter.return_value = iter([{"id": "cus_1"}, {"id": "cus_2"}])
+ source = RevenueCatSource()
+ inputs = MagicMock()
+ inputs.schema_name = "customers"
+ inputs.logger = MagicMock()
+
+ manager = MagicMock()
+ manager.can_resume.return_value = False
+ response = source.source_for_pipeline(_config("k", "p"), manager, inputs)
+
+ assert response.name == "customers"
+ assert response.primary_keys == ["id"]
+ # Customers partition by `first_seen_at` (they have no `created_at`) —
+ # `iterate_list_endpoint` normalizes that ms epoch field to Unix seconds.
+ assert response.partition_mode == "datetime"
+ assert response.partition_format == "week"
+ assert response.partition_keys == ["first_seen_at"]
+
+ rows = list(cast(Iterable[dict[str, str]], response.items()))
+ assert rows == [{"id": "cus_1"}, {"id": "cus_2"}]
+ mock_iter.assert_called_once()
+ kwargs = mock_iter.call_args.kwargs
+ assert kwargs["api_key"] == "k"
+ assert kwargs["project_id"] == "p"
+ assert kwargs["path_suffix"] == "/customers"
+ assert kwargs["endpoint_name"] == "customers"
+ # The partition field must be handed to the iterator so it gets
+ # normalized ms->seconds; for customers that's `first_seen_at`.
+ assert kwargs["timestamp_fields"] == ("first_seen_at",)
+ assert kwargs["starting_after"] is None
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.source.api_client.iterate_list_endpoint")
+ def test_resumes_from_saved_state_when_endpoint_matches(self, mock_iter):
+ # Resumable state should only be honored when the saved endpoint matches
+ # the one we're currently syncing — otherwise we'd replay a customers
+ # cursor against products and skip rows.
+ mock_iter.return_value = iter([])
+ source = RevenueCatSource()
+ inputs = MagicMock()
+ inputs.schema_name = "customers"
+ inputs.logger = MagicMock()
+
+ manager = MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = RevenueCatResumeConfig(endpoint="customers", starting_after="cus_50")
+
+ response = source.source_for_pipeline(_config("k", "p"), manager, inputs)
+ list(cast(Iterable[dict[str, str]], response.items()))
+
+ kwargs = mock_iter.call_args.kwargs
+ assert kwargs["starting_after"] == "cus_50"
+
+ @patch("posthog.temporal.data_imports.sources.revenuecat.source.api_client.iterate_list_endpoint")
+ def test_ignores_resume_state_from_different_endpoint(self, mock_iter):
+ mock_iter.return_value = iter([])
+ source = RevenueCatSource()
+ inputs = MagicMock()
+ inputs.schema_name = "customers"
+ inputs.logger = MagicMock()
+
+ manager = MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = RevenueCatResumeConfig(endpoint="products", starting_after="prod_10")
+
+ response = source.source_for_pipeline(_config("k", "p"), manager, inputs)
+ list(cast(Iterable[dict[str, str]], response.items()))
+
+ kwargs = mock_iter.call_args.kwargs
+ assert kwargs["starting_after"] is None
+
+ def test_events_schema_routes_to_webhook_source_response(self):
+ source = RevenueCatSource()
+ inputs = MagicMock()
+ inputs.schema_name = EVENT_RESOURCE_NAME
+ inputs.logger = MagicMock()
+
+ sentinel = cast(SourceResponse, "WEBHOOK_RESPONSE")
+ with patch.object(source, "_webhook_source_response", return_value=sentinel) as mock_webhook:
+ result = source.source_for_pipeline(_config(), MagicMock(), inputs)
+
+ assert result is sentinel
+ mock_webhook.assert_called_once_with(inputs)
+
+ def test_every_api_endpoint_partitions_by_stable_timestamp(self):
+ # Customers have no `created_at`; they partition by `first_seen_at`. Every
+ # other endpoint partitions by `created_at`. Both are stable per row.
+ for name, endpoint in REVENUECAT_API_ENDPOINTS.items():
+ expected = ["first_seen_at"] if name == CUSTOMER_RESOURCE_NAME else ["created_at"]
+ assert endpoint.partition_keys == expected, name
+ assert endpoint.primary_keys == ["id"], name
+
+
+class TestRevenueCatWebhookTableTransformer:
+ def test_lifts_event_fields_and_preserves_api_version(self):
+ table = table_from_py_list(
+ [
+ {
+ "api_version": "1.0",
+ "event": {
+ "id": "evt-1",
+ "type": "INITIAL_PURCHASE",
+ "app_user_id": "user-1",
+ "product_id": "com.subscription.weekly",
+ "store": "APP_STORE",
+ "event_timestamp_ms": 1658726374000,
+ "purchased_at_ms": 1658726374000,
+ },
+ }
+ ]
+ )
+
+ result = _webhook_table_transformer(table)
+ rows = result.to_pylist()
+
+ assert len(rows) == 1
+ assert rows[0]["id"] == "evt-1"
+ assert rows[0]["type"] == "INITIAL_PURCHASE"
+ assert rows[0]["app_user_id"] == "user-1"
+ assert rows[0]["store"] == "APP_STORE"
+ assert rows[0]["api_version"] == "1.0"
+ # Original ms field preserved unchanged for callers that care about
+ # sub-second precision; `created_at` is the derived seconds value used
+ # for partitioning.
+ assert rows[0]["event_timestamp_ms"] == 1658726374000
+ assert rows[0]["created_at"] == 1658726374
+
+ def test_skips_created_at_derivation_when_event_timestamp_ms_missing(self):
+ # Older RevenueCat events or test deliveries may omit the timestamp
+ # entirely. Don't synthesize a fake `created_at` value — the partition
+ # layer falls back to "1970-01" for missing keys, which is a clearer
+ # signal of the missing field than a zero value would be.
+ table = table_from_py_list([{"api_version": "1.0", "event": {"id": "evt-1", "type": "TEST"}}])
+
+ result = _webhook_table_transformer(table)
+ rows = result.to_pylist()
+
+ assert rows[0]["id"] == "evt-1"
+ assert "created_at" not in rows[0]
+
+ def test_handles_event_as_json_string(self):
+ # Defensive: if upstream serializes `event` as a JSON string, we still
+ # parse it correctly.
+ table = pa.table(
+ {
+ "api_version": ["1.0"],
+ "event": ['{"id": "evt-2", "type": "RENEWAL", "app_user_id": "u"}'],
+ }
+ )
+
+ result = _webhook_table_transformer(table)
+ rows = result.to_pylist()
+
+ assert rows == [{"id": "evt-2", "type": "RENEWAL", "app_user_id": "u", "api_version": "1.0"}]
+
+ def test_skips_rows_with_null_event(self):
+ table = pa.table(
+ {
+ "api_version": ["1.0", "1.0"],
+ "event": [None, {"id": "evt-4", "type": "RENEWAL"}],
+ }
+ )
+
+ result = _webhook_table_transformer(table)
+ rows = result.to_pylist()
+
+ assert rows == [{"id": "evt-4", "type": "RENEWAL", "api_version": "1.0"}]
+
+ def test_returns_empty_when_event_column_missing(self):
+ table = pa.table({"api_version": ["1.0"]})
+
+ result = _webhook_table_transformer(table)
+
+ assert result.num_rows == 0
diff --git a/posthog/temporal/data_imports/sources/revenuecat/webhook_template.py b/posthog/temporal/data_imports/sources/revenuecat/webhook_template.py
new file mode 100644
index 000000000000..a3bf5c0d3aeb
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/revenuecat/webhook_template.py
@@ -0,0 +1,129 @@
+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
+
+template: HogFunctionTemplateDC = HogFunctionTemplateDC(
+ status="alpha",
+ free=False,
+ type="warehouse_source_webhook",
+ id="template-warehouse-source-revenuecat",
+ name="RevenueCat warehouse source webhook",
+ description="Receive RevenueCat webhook events for data warehouse ingestion",
+ icon_url="/static/services/revenuecat.png",
+ category=["Data warehouse"],
+ code_language="hog",
+ code="""\
+if (request.method != 'POST') {
+ return {
+ 'httpResponse': {
+ 'status': 405,
+ 'body': 'Method not allowed'
+ }
+ }
+}
+
+if (not inputs.bypass_authorization_check) {
+ if (empty(inputs.authorization_header)) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Authorization header value not configured',
+ }
+ }
+ }
+
+ let providedHeader := request.headers['authorization']
+
+ if (empty(providedHeader)) {
+ return {
+ 'httpResponse': {
+ 'status': 401,
+ 'body': 'Missing authorization header',
+ }
+ }
+ }
+
+ if (providedHeader != inputs.authorization_header) {
+ return {
+ 'httpResponse': {
+ 'status': 401,
+ 'body': 'Bad authorization header',
+ }
+ }
+ }
+}
+
+let eventType := request.body.event?.type
+
+if (empty(eventType)) {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': 'No event type found, skipping'
+ }
+ }
+}
+
+if (eventType = 'TEST') {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': 'Test event acknowledged'
+ }
+ }
+}
+
+// RevenueCat funnels every event type into the single `events` warehouse table
+// — the schema_mapping is keyed by a wildcard ("*") which we look up here.
+let schemaId := inputs.schema_mapping?.['*']
+
+if (empty(schemaId)) {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': f'No schema mapping for event type: {eventType}, skipping'
+ }
+ }
+}
+
+produceToWarehouseWebhooks(request.body, schemaId)""",
+ inputs_schema=[
+ {
+ "type": "string",
+ "key": "authorization_header",
+ "label": "Authorization header value",
+ "required": False,
+ "secret": True,
+ "hidden": False,
+ "description": (
+ "The exact value RevenueCat will send in the Authorization header "
+ "(e.g. `Bearer my-secret`). PostHog rejects deliveries whose header does not match."
+ ),
+ },
+ {
+ "type": "boolean",
+ "key": "bypass_authorization_check",
+ "label": "Bypass authorization header check",
+ "description": ("If set, the Authorization header will not be checked. This is not recommended."),
+ "default": False,
+ "required": False,
+ "secret": False,
+ },
+ {
+ "type": "json",
+ "key": "schema_mapping",
+ "label": "Schema mapping",
+ "description": "Maps RevenueCat resource names to ExternalDataSchema IDs",
+ "required": True,
+ "secret": False,
+ "hidden": True,
+ },
+ {
+ "type": "string",
+ "key": "source_id",
+ "label": "Source ID",
+ "description": "The ExternalDataSource ID this webhook is associated with",
+ "required": True,
+ "secret": False,
+ "hidden": True,
+ },
+ ],
+)