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): add Webflow webhook ingestion (#77469)

Tom Owersf56e1c44a2f8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index dc70c5e69227..df0d50106cd8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -657,7 +657,7 @@ the row lists both.
| vultr | HTTP | requests + `rest_source.RESTClient` | ✅ |
| wasabi | HTTP | requests + `rest_source.RESTClient` | ✅ |
| watchmode | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| webflow | HTTP | requests | ✅ |
+| webflow | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| weights_and_biases | HTTP (GraphQL) | requests | ✅ |
| whop | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| wikipedia_pageviews | HTTP | requests | ✅ |
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/settings.py
index 28421ff61b09..6b1810ce43e4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/settings.py
@@ -102,6 +102,37 @@ WEBFLOW_ENDPOINTS: dict[str, WebflowEndpointConfig] = {
STATIC_ENDPOINTS = tuple(WEBFLOW_ENDPOINTS.keys())
+# Webhook registrations live under the site, one registration per trigger type.
+WEBHOOK_PATH = "/sites/{site_id}/webhooks"
+WEBHOOK_DELETE_PATH = "/webhooks/{webhook_id}"
+
+# Only `orders` can be fed by webhooks. The ecomm order triggers deliver the whole Order
+# object under `payload`, with the same field names the /sites/{site_id}/orders list
+# endpoint returns (`orderId`, `status`, `acceptedOn`, `customerPaid`, …), so pushed rows
+# merge into the polled table on `orderId`. The other triggers Webflow offers either
+# describe a resource we don't sync (`form_submission` carries a submission, our `forms`
+# table carries form definitions), rename the object's fields (`page_created` sends
+# `pageId`/`pageTitle` where the Pages API sends `id`/`title`), or carry only publish
+# metadata rather than the resource (`site_publish`, `ecomm_inventory_changed`).
+SCHEMA_TO_WEBHOOK_EVENTS: dict[str, list[str]] = {
+ "orders": ["ecomm_new_order", "ecomm_order_changed"],
+}
+
+WEBHOOK_SCHEMA_NAMES = tuple(SCHEMA_TO_WEBHOOK_EVENTS)
+
+ALL_WEBHOOK_EVENTS = sorted({event for events in SCHEMA_TO_WEBHOOK_EVENTS.values() for event in events})
+
+# Trigger type -> the schema its payload belongs to. Several triggers feed one table, so the
+# Hog template collapses the trigger to this resource key before looking up the schema id.
+# Keep in sync with `resourceByTrigger` in webhook_template.py.
+WEBHOOK_EVENT_TO_RESOURCE: dict[str, str] = {
+ event: name for name, events in SCHEMA_TO_WEBHOOK_EVENTS.items() for event in events
+}
+
+# Schema name -> the `schema_mapping` key incoming deliveries are routed by. Identity here:
+# the template already collapses trigger types down to the schema name.
+WEBHOOK_RESOURCE_MAP: dict[str, str] = {name: name for name in SCHEMA_TO_WEBHOOK_EVENTS}
+
def collection_items_endpoint_config(collection_id: str) -> WebflowEndpointConfig:
"""Build the endpoint config for a single CMS collection's items.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/source.py
index 1a09fde744ca..c162e5f70982 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/source.py
@@ -1,4 +1,4 @@
-from typing import Optional, cast
+from typing import TYPE_CHECKING, Optional, cast
import structlog
@@ -11,7 +11,14 @@ from posthog.schema import (
SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ ExternalWebhookInfo,
+ FieldType,
+ ResumableSource,
+ WebhookCreationResult,
+ WebhookDeletionResult,
+ WebhookSource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
)
@@ -19,26 +26,39 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.reg
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.webflow import (
WebflowSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.webflow.settings import (
COLLECTION_SCHEMA_PREFIX,
+ SCHEMA_TO_WEBHOOK_EVENTS,
STATIC_ENDPOINTS,
+ WEBHOOK_RESOURCE_MAP,
+ WEBHOOK_SCHEMA_NAMES,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.webflow.webflow import (
WebflowResumeConfig,
+ create_webhook as create_webflow_webhook,
+ delete_webhook as delete_webflow_webhook,
+ get_external_webhook_info as get_webflow_webhook_info,
list_collections,
validate_credentials as validate_webflow_credentials,
webflow_source,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+if TYPE_CHECKING:
+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
+
logger = structlog.get_logger(__name__)
@SourceRegistry.register
-class WebflowSource(ResumableSource[WebflowSourceConfig, WebflowResumeConfig]):
+class WebflowSource(
+ ResumableSource[WebflowSourceConfig, WebflowResumeConfig],
+ WebhookSource[WebflowSourceConfig],
+):
supported_versions = ("v2",)
default_version = "v2"
api_docs_url = "https://developers.webflow.com"
@@ -87,7 +107,13 @@ class WebflowSource(ResumableSource[WebflowSourceConfig, WebflowResumeConfig]):
# endpoints (the createdOn/lastUpdated query params are exact-match, not
# ranges), so every endpoint is full-refresh only for now.
schemas = [
- SourceSchema(name=endpoint, supports_incremental=False, supports_append=False, incremental_fields=[])
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ supports_webhooks=endpoint in WEBHOOK_SCHEMA_NAMES,
+ )
for endpoint in STATIC_ENDPOINTS
]
@@ -135,6 +161,45 @@ class WebflowSource(ResumableSource[WebflowSourceConfig, WebflowResumeConfig]):
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[WebflowResumeConfig]:
return ResumableSourceManager[WebflowResumeConfig](inputs, WebflowResumeConfig)
+ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:
+ return WebhookSourceManager(inputs, inputs.logger)
+
+ @property
+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.webflow.webhook_template import template
+
+ return template
+
+ @property
+ def webhook_resource_map(self) -> dict[str, str]:
+ return WEBHOOK_RESOURCE_MAP
+
+ def create_webhook(
+ self, config: WebflowSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
+ ) -> WebhookCreationResult:
+ return create_webflow_webhook(config.api_token, config.site_id, webhook_url)
+
+ def get_desired_webhook_events(
+ self, config: WebflowSourceConfig, eligible_schema_names: list[str]
+ ) -> list[str] | None:
+ return sorted({event for name in eligible_schema_names for event in SCHEMA_TO_WEBHOOK_EVENTS.get(name, [])})
+
+ # `sync_webhook_events` stays on the base no-op. Webflow issues a registration's signing
+ # secret once, at creation, and reconciliation has no way to persist a new one — so a
+ # webhook re-created here would deliver events we could never verify. There is nothing to
+ # drift anyway: `create_webhook` registers every trigger the one eligible table needs, and
+ # anything missing afterwards is surfaced to the user by `get_desired_webhook_events`.
+
+ def get_external_webhook_info(
+ self, config: WebflowSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
+ ) -> ExternalWebhookInfo | None:
+ return get_webflow_webhook_info(config.api_token, config.site_id, webhook_url)
+
+ def delete_webhook(
+ self, config: WebflowSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
+ ) -> WebhookDeletionResult:
+ return delete_webflow_webhook(config.api_token, config.site_id, webhook_url)
+
def source_for_pipeline(
self,
config: WebflowSourceConfig,
@@ -148,6 +213,7 @@ class WebflowSource(ResumableSource[WebflowSourceConfig, WebflowResumeConfig]):
team_id=inputs.team_id,
job_id=inputs.job_id,
resumable_source_manager=resumable_source_manager,
+ webhook_source_manager=self.get_webhook_source_manager(inputs),
)
@property
@@ -192,4 +258,35 @@ Grant the read scopes for the resources you want to sync:
),
],
),
+ webhookSetupCaption=(
+ "PostHog registers a Webflow webhook for each order event using your API token, "
+ "which needs the `sites:write` scope. Webflow returns a secret key for each "
+ "registration, and PostHog uses those to verify deliveries.\n\n"
+ "**Manual setup** (only needed if automatic registration failed):\n\n"
+ "1. Send a POST request to Webflow's [Create Webhook]"
+ "(https://developers.webflow.com/data/reference/webhooks/create) endpoint for "
+ 'your site, once with `"triggerType": "ecomm_new_order"` and once with '
+ '`"triggerType": "ecomm_order_changed"`, using the webhook URL shown below\n'
+ "2. Copy the `secretKey` from a response and paste it into the field below so "
+ "PostHog can verify deliveries\n\n"
+ "Webhooks created from Webflow's site settings are not signed, so PostHog cannot "
+ "accept them. Create them through the API."
+ ),
+ webhookFields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="signing_secret",
+ label="Signing secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ caption=(
+ "The `secretKey` Webflow returned when the webhook was created. PostHog "
+ "uses it to verify the x-webflow-signature header on every delivery."
+ ),
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/tests/test_webflow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/tests/test_webflow.py
index b86a984b8dad..43ee22fb5b2b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/tests/test_webflow.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/tests/test_webflow.py
@@ -3,20 +3,29 @@ from collections.abc import Iterable
from typing import Any, cast
import pytest
-from unittest.mock import MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
import requests
from parameterized import parameterized
from requests import Response
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_list
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
-from products.warehouse_sources.backend.temporal.data_imports.sources.webflow.settings import WEBFLOW_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.webflow.settings import (
+ ALL_WEBHOOK_EVENTS,
+ WEBFLOW_ENDPOINTS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.webflow.webflow import (
WebflowResumeConfig,
_extract_items,
_resolve_collection_id,
+ create_webhook,
+ delete_webhook,
+ get_external_webhook_info,
validate_credentials,
webflow_source,
+ webhook_table_transformer,
)
# The sync transport builds its session via make_tracked_session inside the shared rest_client.
@@ -317,3 +326,313 @@ class TestWebflowSource:
)
assert callable(response.items)
assert isinstance(response.items(), Iterable)
+
+
+def _webhook_list_response(webhooks: list[dict[str, Any]]) -> Response:
+ return _make_response({"webhooks": webhooks, "pagination": {"limit": 100, "offset": 0, "total": len(webhooks)}})
+
+
+class TestCreateWebhook:
+ def test_registers_one_webhook_per_trigger_and_keeps_every_secret(self) -> None:
+ # Webflow's create endpoint takes a single triggerType and issues a separate secret per
+ # registration, so losing any of them leaves that trigger's deliveries unverifiable.
+ with patch(WEBFLOW_SESSION_PATCH) as MockSession:
+ session = MockSession.return_value
+ session.get.return_value = _webhook_list_response([])
+ session.post.side_effect = [
+ _make_response({"id": "w1", "triggerType": "ecomm_new_order", "secretKey": "s1"}, 201),
+ _make_response({"id": "w2", "triggerType": "ecomm_order_changed", "secretKey": "s2"}, 201),
+ ]
+
+ result = create_webhook("token", "site-1", "https://webhooks.example/dwh/1")
+
+ assert result.success is True
+ assert result.extra_inputs == {"signing_secrets": ["s1", "s2"]}
+ assert result.pending_inputs == []
+ assert [call.kwargs["json"]["triggerType"] for call in session.post.call_args_list] == list(ALL_WEBHOOK_EVENTS)
+ assert {call.kwargs["json"]["url"] for call in session.post.call_args_list} == {
+ "https://webhooks.example/dwh/1"
+ }
+
+ def test_skips_triggers_already_registered_for_our_url(self) -> None:
+ # Webflow caps registrations per trigger type per site, and a duplicate would keep
+ # delivering after we delete "the" webhook.
+ with patch(WEBFLOW_SESSION_PATCH) as MockSession:
+ session = MockSession.return_value
+ session.get.return_value = _webhook_list_response(
+ [{"id": "w1", "triggerType": "ecomm_new_order", "url": "https://webhooks.example/dwh/1"}]
+ )
+ session.post.return_value = _make_response(
+ {"id": "w2", "triggerType": "ecomm_order_changed", "secretKey": "s2"}, 201
+ )
+
+ result = create_webhook("token", "site-1", "https://webhooks.example/dwh/1")
+
+ assert [call.kwargs["json"]["triggerType"] for call in session.post.call_args_list] == ["ecomm_order_changed"]
+ assert result.success is True
+ # One trigger's secret was issued before we asked, so it can't be recovered.
+ assert result.pending_inputs == ["signing_secret"]
+
+ def test_registration_without_a_secret_asks_the_user_for_one(self) -> None:
+ # Site tokens predating Webflow's per-webhook secrets return no secretKey; silently
+ # succeeding would leave every delivery failing the signature check.
+ with patch(WEBFLOW_SESSION_PATCH) as MockSession:
+ session = MockSession.return_value
+ session.get.return_value = _webhook_list_response([])
+ session.post.return_value = _make_response({"id": "w1"}, 201)
+
+ result = create_webhook("token", "site-1", "https://webhooks.example/dwh/1")
+
+ assert result.success is True
+ assert result.extra_inputs == {}
+ assert result.pending_inputs == ["signing_secret"]
+
+ @parameterized.expand([("forbidden", 403), ("bad_request", 400)])
+ def test_reports_failure_when_no_registration_was_created(self, _name: str, status_code: int) -> None:
+ with patch(WEBFLOW_SESSION_PATCH) as MockSession:
+ session = MockSession.return_value
+ session.get.return_value = _webhook_list_response([])
+ session.post.return_value = _make_response({"message": "nope"}, status_code)
+
+ result = create_webhook("token", "site-1", "https://webhooks.example/dwh/1")
+
+ assert result.success is False
+ assert result.error is not None
+ assert "sites:write" in result.error
+
+ def test_network_failure_is_reported_not_raised(self) -> None:
+ with patch(WEBFLOW_SESSION_PATCH) as MockSession:
+ MockSession.return_value.get.side_effect = requests.exceptions.ConnectTimeout("boom")
+
+ result = create_webhook("token", "site-1", "https://webhooks.example/dwh/1")
+
+ assert result.success is False
+ assert result.error is not None and "boom" in result.error
+
+
+class TestDeleteWebhook:
+ def test_deletes_every_registration_pointing_at_our_url_and_leaves_others(self) -> None:
+ with patch(WEBFLOW_SESSION_PATCH) as MockSession:
+ session = MockSession.return_value
+ session.get.return_value = _webhook_list_response(
+ [
+ {"id": "w1", "triggerType": "ecomm_new_order", "url": "https://webhooks.example/dwh/1"},
+ {"id": "w2", "triggerType": "ecomm_order_changed", "url": "https://webhooks.example/dwh/1"},
+ {"id": "other", "triggerType": "form_submission", "url": "https://someone-else.example"},
+ ]
+ )
+ # A registration removed in Webflow between listing and deleting is already the
+ # outcome we wanted, so a 404 must not fail the teardown.
+ session.delete.side_effect = [_make_response({}, 204), _make_response({}, 404)]
+
+ result = delete_webhook("token", "site-1", "https://webhooks.example/dwh/1")
+
+ assert result.success is True
+ deleted_ids = [call.args[0].rsplit("/", 1)[-1] for call in session.delete.call_args_list]
+ assert deleted_ids == ["w1", "w2"]
+
+ def test_reports_a_registration_webflow_refused_to_delete(self) -> None:
+ with patch(WEBFLOW_SESSION_PATCH) as MockSession:
+ session = MockSession.return_value
+ session.get.return_value = _webhook_list_response(
+ [{"id": "w1", "triggerType": "ecomm_new_order", "url": "https://webhooks.example/dwh/1"}]
+ )
+ session.delete.return_value = _make_response({}, 403)
+
+ result = delete_webhook("token", "site-1", "https://webhooks.example/dwh/1")
+
+ assert result.success is False
+ assert result.error is not None and "w1" in result.error
+
+
+class TestGetExternalWebhookInfo:
+ def test_reports_the_triggers_currently_registered(self) -> None:
+ with patch(WEBFLOW_SESSION_PATCH) as MockSession:
+ MockSession.return_value.get.return_value = _webhook_list_response(
+ [
+ {
+ "id": "w1",
+ "triggerType": "ecomm_new_order",
+ "url": "https://webhooks.example/dwh/1",
+ "createdOn": "2026-01-02T00:00:00Z",
+ },
+ {
+ "id": "w2",
+ "triggerType": "ecomm_order_changed",
+ "url": "https://webhooks.example/dwh/1",
+ "createdOn": "2026-01-01T00:00:00Z",
+ },
+ ]
+ )
+
+ info = get_external_webhook_info("token", "site-1", "https://webhooks.example/dwh/1")
+
+ assert info.exists is True
+ # The set drives the "missing events" hint in the UI, so a partial registration has to
+ # report only what is really there.
+ assert info.enabled_events == ["ecomm_new_order", "ecomm_order_changed"]
+ assert info.created_at == "2026-01-01T00:00:00Z"
+
+ def test_reports_absence_when_only_other_webhooks_exist(self) -> None:
+ with patch(WEBFLOW_SESSION_PATCH) as MockSession:
+ MockSession.return_value.get.return_value = _webhook_list_response(
+ [{"id": "w1", "triggerType": "form_submission", "url": "https://someone-else.example"}]
+ )
+
+ info = get_external_webhook_info("token", "site-1", "https://webhooks.example/dwh/1")
+
+ assert info.exists is False
+
+ def test_lookup_failure_is_reported_not_raised(self) -> None:
+ with patch(WEBFLOW_SESSION_PATCH) as MockSession:
+ MockSession.return_value.get.return_value = _make_response({"message": "nope"}, 401)
+
+ info = get_external_webhook_info("token", "site-1", "https://webhooks.example/dwh/1")
+
+ assert info.exists is False
+ assert info.error is not None
+
+
+class TestWebhookTableTransformer:
+ def _table(self, rows: list[dict[str, Any]]) -> Any:
+ return table_from_py_list(rows)
+
+ def test_keeps_only_the_latest_delivery_per_order(self) -> None:
+ # Delta merge dedupes across syncs but not within a batch, so a created-then-changed
+ # pair for one order would otherwise land as two rows racing on the same primary key.
+ table = self._table(
+ [
+ {
+ "triggerType": "ecomm_new_order",
+ "webflowTimestamp": "1700000000000",
+ "payload": {"orderId": "abc123", "status": "unfulfilled"},
+ },
+ {
+ "triggerType": "ecomm_order_changed",
+ "webflowTimestamp": "1700000060000",
+ "payload": {"orderId": "abc123", "status": "fulfilled"},
+ },
+ {
+ "triggerType": "ecomm_new_order",
+ "webflowTimestamp": "1700000030000",
+ "payload": {"orderId": "def456", "status": "unfulfilled"},
+ },
+ ]
+ )
+
+ rows = webhook_table_transformer(table).to_pylist()
+
+ assert sorted(rows, key=lambda r: r["orderId"]) == [
+ {"orderId": "abc123", "status": "fulfilled"},
+ {"orderId": "def456", "status": "unfulfilled"},
+ ]
+
+ def test_out_of_order_delivery_does_not_resurrect_the_older_row(self) -> None:
+ # Webflow retries failed deliveries, so a stale event can arrive after a newer one.
+ table = self._table(
+ [
+ {
+ "triggerType": "ecomm_order_changed",
+ "webflowTimestamp": "1700000060000",
+ "payload": {"orderId": "abc123", "status": "fulfilled"},
+ },
+ {
+ "triggerType": "ecomm_new_order",
+ "webflowTimestamp": "1700000000000",
+ "payload": {"orderId": "abc123", "status": "unfulfilled"},
+ },
+ ]
+ )
+
+ assert webhook_table_transformer(table).to_pylist() == [{"orderId": "abc123", "status": "fulfilled"}]
+
+ def test_equal_timestamps_fall_back_to_arrival_order(self) -> None:
+ table = self._table(
+ [
+ {
+ "triggerType": "ecomm_new_order",
+ "webflowTimestamp": "1700000000000",
+ "payload": {"orderId": "abc123", "status": "unfulfilled"},
+ },
+ {
+ "triggerType": "ecomm_order_changed",
+ "webflowTimestamp": "1700000000000",
+ "payload": {"orderId": "abc123", "status": "fulfilled"},
+ },
+ ]
+ )
+
+ assert webhook_table_transformer(table).to_pylist() == [{"orderId": "abc123", "status": "fulfilled"}]
+
+ def test_rows_without_an_order_id_are_dropped(self) -> None:
+ # A row with no primary key can't be merged; keeping it would fail the whole batch.
+ table = self._table(
+ [
+ {"triggerType": "ecomm_new_order", "webflowTimestamp": "1700000000000", "payload": {"status": "x"}},
+ {
+ "triggerType": "ecomm_new_order",
+ "webflowTimestamp": "1700000000000",
+ "payload": {"orderId": "abc123", "status": "unfulfilled"},
+ },
+ ]
+ )
+
+ assert webhook_table_transformer(table).to_pylist() == [{"orderId": "abc123", "status": "unfulfilled"}]
+
+ def test_table_without_a_payload_column_yields_no_rows(self) -> None:
+ assert webhook_table_transformer(self._table([{"triggerType": "site_publish"}])).num_rows == 0
+
+
+class TestWebhookBackedSource:
+ def test_orders_reads_from_the_webhook_manager_once_webhooks_are_live(self) -> None:
+ manager = _make_manager()
+ webhook_manager = MagicMock(spec=WebhookSourceManager)
+ webhook_manager.webhook_enabled = AsyncMock(return_value=True)
+ webhook_manager.get_items.return_value = "webhook-items"
+
+ with patch(CLIENT_SESSION_PATCH) as MockSession:
+ MockSession.return_value.send.side_effect = AssertionError("the pull API must not be hit")
+ response = webflow_source(
+ "token",
+ "site-1",
+ "orders",
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=manager,
+ webhook_source_manager=webhook_manager,
+ )
+ assert response.items() == "webhook-items"
+
+ webhook_manager.get_items.assert_called_once_with(table_transformer=webhook_table_transformer)
+ # The polled table's identity must not change when rows arrive by webhook, or pushed
+ # rows land in a different Delta table than the backfill.
+ assert response.primary_keys == ["orderId"]
+ assert response.partition_keys == ["acceptedOn"]
+
+ @parameterized.expand([("pages",), ("collection_blog",)])
+ def test_schema_without_webhook_support_never_consults_the_webhook_manager(self, schema_name: str) -> None:
+ # Only `orders` has a Webflow trigger whose payload matches the polled table, so any
+ # other schema must keep polling even when a webhook is registered on the source.
+ manager = _make_manager()
+ webhook_manager = MagicMock(spec=WebhookSourceManager)
+ webhook_manager.webhook_enabled = AsyncMock(return_value=True)
+
+ with (
+ patch(CLIENT_SESSION_PATCH),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.webflow.webflow._resolve_collection_id",
+ return_value="c1",
+ ),
+ ):
+ webflow_source(
+ "token",
+ "site-1",
+ schema_name,
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=manager,
+ webhook_source_manager=webhook_manager,
+ )
+
+ webhook_manager.webhook_enabled.assert_not_called()
+ webhook_manager.get_items.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/tests/test_webflow_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/tests/test_webflow_source.py
index 049e51ac1ba7..1670c75c0b62 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/tests/test_webflow_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/tests/test_webflow_source.py
@@ -1,9 +1,12 @@
from unittest.mock import MagicMock, patch
+from parameterized import parameterized
+
from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.webflow import (
WebflowSourceConfig,
)
@@ -130,11 +133,70 @@ class TestWebflowSource:
with patch(f"{SOURCE_MODULE}.webflow_source") as mock_source:
WebflowSource().source_for_pipeline(_config(), manager, inputs)
- mock_source.assert_called_once_with(
- api_token="token",
- site_id="site-1",
- schema_name="collection_blog",
- team_id=inputs.team_id,
- job_id=inputs.job_id,
- resumable_source_manager=manager,
- )
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_token"] == "token"
+ assert kwargs["site_id"] == "site-1"
+ assert kwargs["schema_name"] == "collection_blog"
+ assert kwargs["team_id"] == inputs.team_id
+ assert kwargs["job_id"] == inputs.job_id
+ assert kwargs["resumable_source_manager"] is manager
+ # Backfill and pushed rows have to reach the same sync, so the webhook manager is
+ # always handed over; the transport decides whether the schema can use it.
+ assert isinstance(kwargs["webhook_source_manager"], WebhookSourceManager)
+
+
+class TestWebflowWebhookSupport:
+ def test_only_orders_is_offered_as_a_webhook_table(self) -> None:
+ # Every other Webflow trigger either describes a resource we don't sync (form_submission
+ # carries a submission, our forms table carries form definitions) or renames the object's
+ # fields (page_created sends pageId/pageTitle where the Pages API sends id/title), so
+ # marking one webhook-capable would merge mismatched rows into the polled table.
+ with patch(f"{SOURCE_MODULE}.list_collections", return_value=[{"id": "c1", "slug": "blog"}]):
+ schemas = WebflowSource().get_schemas(_config(), team_id=1)
+
+ assert {s.name for s in schemas if s.supports_webhooks} == {"orders"}
+
+ def test_webhook_resource_map_keys_are_real_schema_names(self) -> None:
+ # The resource map is what builds schema_mapping; a key that isn't a schema name means
+ # deliveries route to nothing and are dropped with a 200.
+ source = WebflowSource()
+ with patch(f"{SOURCE_MODULE}.list_collections", return_value=[]):
+ schema_names = {s.name for s in source.get_schemas(_config(), team_id=1)}
+
+ assert set(source.webhook_resource_map) <= schema_names
+ # The Hog template collapses trigger types down to the schema name before the lookup.
+ assert source.webhook_resource_map == {"orders": "orders"}
+ assert source.webhook_mapping_key("orders") == "orders"
+
+ def test_webhook_template_is_wired_for_this_source(self) -> None:
+ template = WebflowSource().webhook_template
+ assert template is not None
+ assert template.id == "template-warehouse-source-webflow"
+ assert template.type == "warehouse_source_webhook"
+
+ @parameterized.expand(
+ [
+ ("eligible", ["orders"], ["ecomm_new_order", "ecomm_order_changed"]),
+ ("not_eligible", ["pages", "forms"], []),
+ ("mixed", ["orders", "pages"], ["ecomm_new_order", "ecomm_order_changed"]),
+ ]
+ )
+ def test_desired_events_follow_the_enabled_tables(
+ self, _name: str, enabled: list[str], expected: list[str]
+ ) -> None:
+ assert WebflowSource().get_desired_webhook_events(_config(), enabled) == expected
+
+ @parameterized.expand(
+ [
+ ("create", "create_webflow_webhook", "create_webhook"),
+ ("delete", "delete_webflow_webhook", "delete_webhook"),
+ ("info", "get_webflow_webhook_info", "get_external_webhook_info"),
+ ]
+ )
+ def test_webhook_management_uses_the_configured_site_and_token(self, _name: str, patched: str, method: str) -> None:
+ # Webflow webhooks are site-scoped; calling with the wrong site would register or delete
+ # a webhook on a different site the token can reach.
+ with patch(f"{SOURCE_MODULE}.{patched}") as mock_call:
+ getattr(WebflowSource(), method)(_config(), "https://webhooks.example/dwh/1", team_id=1)
+
+ mock_call.assert_called_once_with("token", "site-1", "https://webhooks.example/dwh/1")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/tests/test_webflow_webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/tests/test_webflow_webhook_template.py
new file mode 100644
index 000000000000..a5a9d5cfe96c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/tests/test_webflow_webhook_template.py
@@ -0,0 +1,200 @@
+import hmac
+import json
+import time
+import hashlib
+
+from parameterized import parameterized
+
+from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.webflow.webhook_template import template
+
+SOURCE_ID = "source_test_123"
+NEW_ORDER_SECRET = "2b4acfd1c5518bf03c73a4889d197d77251353857c22694bf150b9e3402ba15f"
+ORDER_CHANGED_SECRET = "9f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0"
+SCHEMA_MAPPING = {"orders": "schema_orders"}
+
+
+def _now_ms() -> int:
+ return int(time.time() * 1000)
+
+
+class TestWebflowWarehouseWebhookTemplate(BaseHogFunctionTemplateTest):
+ template = template
+
+ def createHogGlobals(self, globals=None) -> dict:
+ data: dict = {
+ "request": {
+ "method": "POST",
+ "headers": {},
+ "body": {},
+ "query": {},
+ "stringBody": "",
+ "ip": "127.0.0.1",
+ },
+ }
+ if globals and globals.get("request"):
+ data["request"].update(globals["request"])
+ return data
+
+ def _event(self, trigger_type: str = "ecomm_new_order") -> dict:
+ return {
+ "triggerType": trigger_type,
+ "payload": {
+ "orderId": "abc123",
+ "status": "unfulfilled",
+ "acceptedOn": "2026-05-01T10:00:00.000Z",
+ },
+ }
+
+ def _request(self, secret: str, body: dict, method: str = "POST", timestamp: int | None = None) -> dict:
+ payload = json.dumps(body)
+ request_timestamp = _now_ms() if timestamp is None else timestamp
+ signature = hmac.new(secret.encode(), f"{request_timestamp}:{payload}".encode(), hashlib.sha256).hexdigest()
+ return {
+ "request": {
+ "method": method,
+ "headers": {
+ "x-webflow-signature": signature,
+ "x-webflow-timestamp": str(request_timestamp),
+ },
+ "body": json.loads(payload),
+ "stringBody": payload,
+ "query": {},
+ }
+ }
+
+ def _inputs(self, **overrides) -> dict:
+ return {
+ "signing_secret": "",
+ "signing_secrets": [NEW_ORDER_SECRET, ORDER_CHANGED_SECRET],
+ "bypass_signature_check": False,
+ "schema_mapping": SCHEMA_MAPPING,
+ "source_id": SOURCE_ID,
+ **overrides,
+ }
+
+ @parameterized.expand(
+ [
+ ("new_order", "ecomm_new_order", NEW_ORDER_SECRET),
+ ("order_changed", "ecomm_order_changed", ORDER_CHANGED_SECRET),
+ ]
+ )
+ def test_each_order_trigger_verifies_against_its_own_secret_and_routes_to_orders(
+ self, _name: str, trigger_type: str, secret: str
+ ) -> None:
+ # Webflow issues a separate secret per trigger registration, so a template that only
+ # checked one of them would reject half the deliveries.
+ globals = self._request(secret, self._event(trigger_type))
+
+ self.run_function(self._inputs(), globals=globals)
+
+ produced, schema_id = self.mock_produce_to_warehouse_webhooks.call_args.args
+ assert schema_id == "schema_orders"
+ assert produced["triggerType"] == trigger_type
+ # The Order object is delivered unwrapped so pushed rows match the polled table.
+ assert produced["payload"]["orderId"] == "abc123"
+ assert produced["webflowTimestamp"] == globals["request"]["headers"]["x-webflow-timestamp"]
+
+ def test_manually_entered_secret_is_accepted(self) -> None:
+ # Sites set up by hand have no secrets from the create response, only the one pasted in.
+ globals = self._request("pasted-by-hand", self._event())
+
+ self.run_function(
+ self._inputs(signing_secret="pasted-by-hand", signing_secrets=[]),
+ globals=globals,
+ )
+
+ self.mock_produce_to_warehouse_webhooks.assert_called_once()
+
+ def test_bad_signature_is_rejected(self) -> None:
+ globals = self._request("some-other-secret", self._event())
+
+ res = self.run_function(self._inputs(), globals=globals)
+
+ assert res.result == {"httpResponse": {"status": 400, "body": "Bad signature"}}
+ self.mock_produce_to_warehouse_webhooks.assert_not_called()
+
+ def test_replayed_delivery_is_rejected(self) -> None:
+ # The signature covers the timestamp, so without an age check a captured delivery would
+ # stay valid forever and could rewrite an order row.
+ globals = self._request(NEW_ORDER_SECRET, self._event(), timestamp=_now_ms() - 600_000)
+
+ res = self.run_function(self._inputs(), globals=globals)
+
+ assert res.result == {"httpResponse": {"status": 400, "body": "Stale delivery"}}
+ self.mock_produce_to_warehouse_webhooks.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("missing_signature", {"x-webflow-timestamp": "1700000000000"}, {}, "Missing signature"),
+ ("missing_timestamp", {"x-webflow-signature": "abc"}, {}, "Missing signature"),
+ (
+ "no_secret_configured",
+ {"x-webflow-signature": "abc", "x-webflow-timestamp": "1700000000000"},
+ {"signing_secret": "", "signing_secrets": []},
+ "Signing secret not configured",
+ ),
+ ]
+ )
+ def test_unverifiable_delivery_is_rejected(
+ self, _name: str, headers: dict, input_overrides: dict, expected_body: str
+ ) -> None:
+ body = self._event()
+ globals = {
+ "request": {
+ "method": "POST",
+ "headers": headers,
+ "body": body,
+ "stringBody": json.dumps(body),
+ "query": {},
+ }
+ }
+
+ res = self.run_function(self._inputs(**input_overrides), globals=globals)
+
+ assert res.result == {"httpResponse": {"status": 400, "body": expected_body}}
+ self.mock_produce_to_warehouse_webhooks.assert_not_called()
+
+ def test_unhandled_trigger_is_acknowledged_and_dropped(self) -> None:
+ # A site can carry webhooks we didn't register; a 500 here would put Webflow into a
+ # retry loop and eventually deactivate our webhook.
+ globals = self._request(NEW_ORDER_SECRET, {"triggerType": "site_publish", "payload": {"siteId": "s1"}})
+
+ res = self.run_function(self._inputs(), globals=globals)
+
+ assert res.result["httpResponse"]["status"] == 200
+ self.mock_produce_to_warehouse_webhooks.assert_not_called()
+
+ def test_event_for_a_table_the_user_did_not_enable_is_dropped(self) -> None:
+ globals = self._request(NEW_ORDER_SECRET, self._event())
+
+ res = self.run_function(self._inputs(schema_mapping={}), globals=globals)
+
+ assert res.result["httpResponse"]["status"] == 200
+ self.mock_produce_to_warehouse_webhooks.assert_not_called()
+
+ def test_non_post_request_returns_405(self) -> None:
+ globals = self._request(NEW_ORDER_SECRET, self._event(), method="GET")
+
+ res = self.run_function(self._inputs(), globals=globals)
+
+ assert res.result == {"httpResponse": {"status": 405, "body": "Method not allowed"}}
+
+ def test_bypass_signature_check_still_routes(self) -> None:
+ body = self._event()
+ globals = {
+ "request": {
+ "method": "POST",
+ "headers": {},
+ "body": body,
+ "stringBody": json.dumps(body),
+ "query": {},
+ }
+ }
+
+ self.run_function(
+ self._inputs(signing_secret="", signing_secrets=[], bypass_signature_check=True), globals=globals
+ )
+
+ self.mock_produce_to_warehouse_webhooks.assert_called_once()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/webflow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/webflow.py
index 3d1ab284d2d9..278677ef2334 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/webflow.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/webflow.py
@@ -3,8 +3,17 @@ from collections.abc import Callable
from typing import Any, Optional
from urllib.parse import quote
+import orjson
+import pyarrow as pa
import requests
+from asgiref.sync import async_to_sync
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_list
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ ExternalWebhookInfo,
+ WebhookCreationResult,
+ WebhookDeletionResult,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
Endpoint,
@@ -18,15 +27,22 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.webflow.settings import (
+ ALL_WEBHOOK_EVENTS,
COLLECTION_SCHEMA_PREFIX,
DEFAULT_PAGE_SIZE,
WEBFLOW_BASE_URL,
WEBFLOW_ENDPOINTS,
+ WEBHOOK_DELETE_PATH,
+ WEBHOOK_PATH,
+ WEBHOOK_SCHEMA_NAMES,
WebflowEndpointConfig,
collection_items_endpoint_config,
)
+REQUEST_TIMEOUT_SECONDS = 30
+
@dataclasses.dataclass
class WebflowResumeConfig:
@@ -155,6 +171,191 @@ def _endpoint_config_for_schema(api_token: str, site_id: str, schema_name: str)
raise ValueError(f"Unknown Webflow schema '{schema_name}'")
+def _make_webhook_session(api_token: str) -> requests.Session:
+ # Webflow returns a webhook's signing secret in the create response, so these responses
+ # must stay out of sample capture.
+ return make_tracked_session(
+ headers=_get_headers(api_token),
+ redact_values=(api_token,),
+ capture=False,
+ )
+
+
+def _list_webhooks(session: requests.Session, site_id: str) -> list[dict[str, Any]]:
+ url = f"{WEBFLOW_BASE_URL}{WEBHOOK_PATH.format(site_id=_encode_path_segment(site_id))}"
+ webhooks: list[dict[str, Any]] = []
+ offset = 0
+ while True:
+ response = session.get(
+ url, params={"limit": DEFAULT_PAGE_SIZE, "offset": offset}, timeout=REQUEST_TIMEOUT_SECONDS
+ )
+ response.raise_for_status()
+ body = response.json()
+ page = [item for item in _extract_items(body, "webhooks") if isinstance(item, dict)]
+ webhooks.extend(page)
+
+ total = (body.get("pagination") or {}).get("total") if isinstance(body, dict) else None
+ offset += len(page)
+ if not page or not isinstance(total, int) or offset >= total:
+ return webhooks
+
+
+def _webhooks_matching(session: requests.Session, site_id: str, webhook_url: str) -> list[dict[str, Any]]:
+ return [item for item in _list_webhooks(session, site_id) if item.get("url") == webhook_url]
+
+
+def create_webhook(api_token: str, site_id: str, webhook_url: str) -> WebhookCreationResult:
+ """Register one Webflow webhook per trigger type feeding a webhook-eligible table.
+
+ Webflow's create endpoint takes a single ``triggerType``, so covering the order tables needs
+ one registration per event. Each registration is issued its own ``secretKey``, returned only
+ at creation time, so every secret is collected and stored together — a delivery is accepted
+ if it verifies against any of them.
+ """
+ try:
+ session = _make_webhook_session(api_token)
+ url = f"{WEBFLOW_BASE_URL}{WEBHOOK_PATH.format(site_id=_encode_path_segment(site_id))}"
+
+ # Already-registered triggers are skipped: Webflow caps registrations per trigger type
+ # per site, and re-creating one would leave an orphan we'd keep delivering to.
+ existing = {webhook.get("triggerType") for webhook in _webhooks_matching(session, site_id, webhook_url)}
+
+ secrets: list[str] = []
+ registered: list[str] = []
+ errors: list[str] = []
+
+ for trigger_type in ALL_WEBHOOK_EVENTS:
+ if trigger_type in existing:
+ continue
+ response = session.post(
+ url,
+ json={"triggerType": trigger_type, "url": webhook_url},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ if response.status_code not in (200, 201):
+ errors.append(f"{trigger_type}: HTTP {response.status_code}")
+ continue
+ registered.append(trigger_type)
+ secret = response.json().get("secretKey")
+ if secret:
+ secrets.append(secret)
+
+ if not registered and not existing:
+ detail = f" ({'; '.join(errors)})" if errors else ""
+ return WebhookCreationResult(
+ success=False,
+ error=(
+ f"Webflow refused to register the webhook{detail}. Check that your API token has "
+ "the sites:write scope, or create the webhook manually below."
+ ),
+ )
+
+ # A secret we never saw can't be reconstructed — Webflow only returns it on create, and
+ # tokens predating its per-webhook secrets return none at all. Ask for one by hand so
+ # deliveries aren't silently rejected.
+ pending_inputs = [] if len(secrets) == len(ALL_WEBHOOK_EVENTS) else ["signing_secret"]
+ extra_inputs: dict[str, Any] = {"signing_secrets": secrets} if secrets else {}
+ return WebhookCreationResult(success=True, extra_inputs=extra_inputs, pending_inputs=pending_inputs)
+ except Exception as e:
+ return WebhookCreationResult(
+ success=False,
+ error=f"Failed to create the Webflow webhook: {e}. Please create it manually below.",
+ )
+
+
+def get_external_webhook_info(api_token: str, site_id: str, webhook_url: str) -> ExternalWebhookInfo:
+ try:
+ matching = _webhooks_matching(_make_webhook_session(api_token), site_id, webhook_url)
+ if not matching:
+ return ExternalWebhookInfo(exists=False)
+ return ExternalWebhookInfo(
+ exists=True,
+ url=webhook_url,
+ enabled_events=sorted({str(webhook.get("triggerType")) for webhook in matching}),
+ status="enabled",
+ created_at=min(
+ (str(webhook["createdOn"]) for webhook in matching if webhook.get("createdOn")), default=None
+ ),
+ )
+ except Exception as e:
+ return ExternalWebhookInfo(exists=False, error=str(e))
+
+
+def delete_webhook(api_token: str, site_id: str, webhook_url: str) -> WebhookDeletionResult:
+ try:
+ session = _make_webhook_session(api_token)
+ errors: list[str] = []
+ for webhook in _webhooks_matching(session, site_id, webhook_url):
+ webhook_id = webhook.get("id")
+ if not webhook_id:
+ continue
+ response = session.delete(
+ f"{WEBFLOW_BASE_URL}{WEBHOOK_DELETE_PATH.format(webhook_id=_encode_path_segment(str(webhook_id)))}",
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ # 404 means it's already gone, which is the outcome we wanted.
+ if response.status_code not in (200, 204, 404):
+ errors.append(f"webhook {webhook_id}: HTTP {response.status_code}")
+ if errors:
+ return WebhookDeletionResult(success=False, error="; ".join(errors))
+ return WebhookDeletionResult(success=True)
+ except Exception as e:
+ return WebhookDeletionResult(success=False, error=str(e))
+
+
+def _delivered_at(value: Any) -> int:
+ """Webflow's x-webflow-timestamp as an int, or 0 when it's missing or unparseable."""
+ try:
+ return int(str(value))
+ except (TypeError, ValueError):
+ return 0
+
+
+def _coerce_payload(value: Any) -> Optional[dict[str, Any]]:
+ """Nested objects survive the arrow round trip as JSON strings, so decode before reading."""
+ if isinstance(value, str | bytes):
+ try:
+ value = orjson.loads(value)
+ except orjson.JSONDecodeError:
+ return None
+ return value if isinstance(value, dict) else None
+
+
+def webhook_table_transformer(table: pa.Table) -> pa.Table:
+ """Reshape raw webhook deliveries into rows matching the polled orders table.
+
+ The Hog template delivers `{triggerType, webflowTimestamp, payload}`, so the Order object has
+ to be lifted out of `payload`. Only the newest delivery per `orderId` survives: delta merge
+ dedupes across syncs but not within one batch, so an `ecomm_new_order` followed by an
+ `ecomm_order_changed` for the same order must collapse here.
+ """
+ if "payload" not in table.column_names:
+ return table_from_py_list([])
+
+ timestamps = (
+ table.column("webflowTimestamp").to_pylist()
+ if "webflowTimestamp" in table.column_names
+ else [None] * table.num_rows
+ )
+
+ latest_by_id: dict[Any, tuple[int, dict[str, Any]]] = {}
+ for raw_payload, timestamp in zip(table.column("payload").to_pylist(), timestamps):
+ payload = _coerce_payload(raw_payload)
+ if payload is None:
+ continue
+ order_id = payload.get("orderId")
+ if order_id is None:
+ continue
+
+ delivered_at = _delivered_at(timestamp)
+ existing = latest_by_id.get(order_id)
+ # Later rows win ties, so batch arrival order breaks equal or missing timestamps.
+ if existing is None or delivered_at >= existing[0]:
+ latest_by_id[order_id] = (delivered_at, payload)
+
+ return table_from_py_list([payload for _, payload in latest_by_id.values()])
+
+
def webflow_source(
api_token: str,
site_id: str,
@@ -162,6 +363,7 @@ def webflow_source(
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[WebflowResumeConfig],
+ webhook_source_manager: Optional[WebhookSourceManager] = None,
) -> SourceResponse:
config = _endpoint_config_for_schema(api_token, site_id, schema_name)
@@ -229,9 +431,18 @@ def webflow_source(
initial_paginator_state=initial_paginator_state,
)
+ webhook_enabled = False
+ if webhook_source_manager is not None and schema_name in WEBHOOK_SCHEMA_NAMES:
+ webhook_enabled = async_to_sync(webhook_source_manager.webhook_enabled)()
+
+ def items():
+ if webhook_enabled and webhook_source_manager is not None:
+ return webhook_source_manager.get_items(table_transformer=webhook_table_transformer)
+ return resource
+
return SourceResponse(
name=schema_name,
- items=lambda: resource,
+ items=items,
primary_keys=[config.primary_key],
partition_count=1,
partition_size=1,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/webhook_template.py
new file mode 100644
index 000000000000..e4902ec9c176
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/webflow/webhook_template.py
@@ -0,0 +1,190 @@
+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
+
+template: HogFunctionTemplateDC = HogFunctionTemplateDC(
+ status="alpha",
+ free=False,
+ type="warehouse_source_webhook",
+ id="template-warehouse-source-webflow",
+ name="Webflow warehouse source webhook",
+ description="Receive Webflow webhook events for data warehouse ingestion",
+ icon_url="/static/services/webflow.png",
+ category=["Data warehouse"],
+ code_language="hog",
+ code="""\
+if (request.method != 'POST') {
+ return {
+ 'httpResponse': {
+ 'status': 405,
+ 'body': 'Method not allowed'
+ }
+ }
+}
+
+let timestamp := request.headers['x-webflow-timestamp']
+
+if (not inputs.bypass_signature_check) {
+ let signature := request.headers['x-webflow-signature']
+
+ if (empty(timestamp) or empty(signature)) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Missing signature',
+ }
+ }
+ }
+
+ // Webflow registers one webhook per trigger type and issues each its own secret, so a
+ // delivery can be signed by any of the secrets handed back when we registered them.
+ // The manually-entered secret is appended for sites set up by hand.
+ let secrets := []
+ if (not empty(inputs.signing_secrets)) {
+ secrets := inputs.signing_secrets
+ }
+ if (not empty(inputs.signing_secret)) {
+ secrets := arrayPushBack(secrets, inputs.signing_secret)
+ }
+
+ if (empty(secrets)) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Signing secret not configured',
+ }
+ }
+ }
+
+ // Webflow signs `<timestamp>:<raw body>` with HMAC-SHA256, hex encoded.
+ let signedPayload := concat(timestamp, ':', request.stringBody)
+ let signatureValid := false
+
+ for (let _, secret in secrets) {
+ if (sha256HmacChainHex([secret, signedPayload]) = signature) {
+ signatureValid := true
+ }
+ }
+
+ if (not signatureValid) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Bad signature',
+ }
+ }
+ }
+
+ // The signature covers the timestamp, so a captured delivery stays valid forever unless we
+ // bound its age. Webflow's timestamp is Unix epoch milliseconds and their guidance is to
+ // treat anything older than five minutes as compromised.
+ if (toUnixTimestampMilli(now()) - toInt(timestamp) > 300000) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Stale delivery',
+ }
+ }
+ }
+}
+
+let triggerType := request.body.triggerType
+
+if (empty(triggerType)) {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': 'No trigger type found, skipping'
+ }
+ }
+}
+
+// Several trigger types feed one warehouse table, so the trigger is collapsed to a resource
+// key before the schema lookup. Keep in sync with WEBHOOK_EVENT_TO_RESOURCE in settings.py.
+let resourceByTrigger := {
+ 'ecomm_new_order': 'orders',
+ 'ecomm_order_changed': 'orders',
+}
+
+let resource := resourceByTrigger?.[triggerType]
+
+if (empty(resource)) {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': f'Unhandled trigger type: {triggerType}, skipping'
+ }
+ }
+}
+
+let schemaId := inputs.schema_mapping?.[resource]
+
+if (empty(schemaId)) {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': f'No schema mapping for trigger type: {triggerType}, skipping'
+ }
+ }
+}
+
+// The delivery timestamp is kept alongside the resource so the loader can tell which of two
+// events for the same object is the newer one. Webflow puts no timestamp in the body.
+produceToWarehouseWebhooks(
+ {
+ 'triggerType': triggerType,
+ 'webflowTimestamp': timestamp,
+ 'payload': request.body.payload,
+ },
+ schemaId
+)""",
+ inputs_schema=[
+ {
+ "type": "string",
+ "key": "signing_secret",
+ "label": "Signing secret",
+ "required": False,
+ "secret": True,
+ "hidden": False,
+ "description": (
+ "A webhook's secret key from Webflow. Used to verify the x-webflow-signature header "
+ "(HMAC-SHA256 of `<x-webflow-timestamp>:<raw body>`) so deliveries provably come from Webflow."
+ ),
+ },
+ {
+ "type": "json",
+ "key": "signing_secrets",
+ "label": "Signing secrets",
+ "description": ("Secret keys Webflow returned when PostHog registered the webhooks. One per trigger type."),
+ "default": [],
+ "required": False,
+ "secret": True,
+ "hidden": True,
+ },
+ {
+ "type": "boolean",
+ "key": "bypass_signature_check",
+ "label": "Bypass signature check",
+ "description": "If set, the x-webflow-signature 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 Webflow resources 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,
+ },
+ ],
+)