:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add WooCommerce webhook ingestion (#77470)
Tom Owers72c1bb46d51f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.mdindex 5f93f7ca04c1..28cabe0b5a33 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md@@ -718,12 +718,14 @@ Two tables (`forms`, `responses`).### WooCommerce — needs confirmation-Ten tables, decent coverage.+Ten tables, decent coverage. Products, orders, coupons and customers can also sync via webhooks+(`/webhooks`, HMAC-SHA256 signed deliveries) instead of polling.- [ ] Product variations.- [ ] Order refunds and order notes.- [ ] Reports endpoints.-- [ ] Payment gateways, shipping methods, webhooks.+- [ ] Payment gateways, shipping methods. Webhooks are now managed programmatically for sync, but+ are not exposed as a table.### Slack — needs confirmationdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 18b172fa77f1..dc70c5e69227 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -662,7 +662,7 @@ the row lists both.| whop | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || wikipedia_pageviews | HTTP | requests | ✅ || windmill | HTTP | requests | ✅ |-| woocommerce | HTTP | requests + `rest_source.RESTClient` | ✅ |+| woocommerce | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || wordpress | HTTP | requests | ✅ || workable | HTTP | requests | ✅ || workday | HTTP | requests + `rest_source.RESTClient` | ✅ |diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/settings.pyindex afa168e19b58..50623e61efcd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/settings.py@@ -56,3 +56,28 @@ PARTITION_FIELDS: dict[str, str] = {"customers": "date_created_gmt","product_reviews": "date_created_gmt",}++# Schema name -> the WooCommerce webhook resource that carries it. WooCommerce only ships core+# webhook topics for these four resources, and for each one the delivered payload is built by+# calling `/wc/v3/<resource>s/<id>` — the same controller the list endpoint we poll uses — so the+# field names match the polled table and rows merge on `id`. The other six tables (categories,+# tags, reviews, attributes, tax rates, shipping zones) have no webhook topic at all.+SCHEMA_TO_WEBHOOK_RESOURCE: dict[str, str] = {+ "products": "product",+ "orders": "order",+ "coupons": "coupon",+ "customers": "customer",+}++WEBHOOK_SCHEMA_NAMES = tuple(SCHEMA_TO_WEBHOOK_RESOURCE)++# `.deleted` is deliberately excluded: WooCommerce sends only `{"id": ...}` for it, so merging one+# would blank every other column on the row it matched. `.restored` exists for orders, coupons and+# products but fires on untrashing, which `.updated` already covers on the next edit.+WEBHOOK_EVENTS = ("created", "updated")++# One WooCommerce webhook subscribes to exactly one topic, so a full setup registers the cross+# product of resource and event.+WEBHOOK_TOPICS = tuple(+ f"{resource}.{event}" for resource in SCHEMA_TO_WEBHOOK_RESOURCE.values() for event in WEBHOOK_EVENTS+)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/source.pyindex 4ace3cd3adb4..dbbf88be0c68 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/source.py@@ -1,4 +1,6 @@-from typing import Optional, cast+from typing import TYPE_CHECKING, Optional, cast++from asgiref.sync import async_to_syncfrom posthog.schema import (DataWarehouseSourceCategory,@@ -9,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,)@@ -20,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.schbuild_endpoint_schemas,)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 WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.woocommerce import (WooCommerceSourceConfig,)@@ -27,17 +37,40 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.woocommercENDPOINTS,INCREMENTAL_FIELDS,PARTITION_FIELDS,+ SCHEMA_TO_WEBHOOK_RESOURCE,+ WEBHOOK_SCHEMA_NAMES,)from products.warehouse_sources.backend.temporal.data_imports.sources.woocommerce.woocommerce import (WooCommerceResumeConfig,+ create_webhook as create_woocommerce_webhook,+ delete_webhook as delete_woocommerce_webhook,+ get_external_webhook_info as get_woocommerce_webhook_info,validate_credentials as validate_woocommerce_credentials,+ webhook_table_transformer,woocommerce_source,)from products.warehouse_sources.backend.types import ExternalDataSourceType+if TYPE_CHECKING:+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC++WEBHOOK_SETUP_CAPTION = (+ "PostHog registers a webhook on your store for each of the product, order, coupon and customer "+ "created and updated topics, using the API key above. The key needs **Read/Write** permission "+ "for this to work.\n\n"+ "**Manual setup** (only needed if automatic registration failed):\n\n"+ "1. Go to **WooCommerce > Settings > Advanced > Webhooks** in your store admin\n"+ "2. Add one webhook per topic you want, pointing its delivery URL at the URL shown below\n"+ "3. Give every one of them the same secret, and paste that secret into the field below so "+ "PostHog can verify deliveries"+)+@SourceRegistry.register-class WooCommerceSource(ResumableSource[WooCommerceSourceConfig, WooCommerceResumeConfig]):+class WooCommerceSource(+ ResumableSource[WooCommerceSourceConfig, WooCommerceResumeConfig],+ WebhookSource[WooCommerceSourceConfig],+):supported_versions = ("v3",)default_version = "v3"api_docs_url = "https://woocommerce.github.io/woocommerce-rest-api-docs/"@@ -48,6 +81,21 @@ class WooCommerceSource(ResumableSource[WooCommerceSourceConfig, WooCommerceResudef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.WOOCOMMERCE+ @property+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:+ from products.warehouse_sources.backend.temporal.data_imports.sources.woocommerce.webhook_template import ( # noqa: PLC0415+ template,+ )++ return template++ @property+ def webhook_resource_map(self) -> dict[str, str]:+ # WooCommerce identifies the object type in the `X-WC-Webhook-Resource` header rather than+ # the body, so deliveries are routed by resource and both of a resource's topics land on+ # the same table.+ return SCHEMA_TO_WEBHOOK_RESOURCE+def get_canonical_descriptions(self) -> CanonicalDescriptions:from products.warehouse_sources.backend.temporal.data_imports.sources.woocommerce.canonical_descriptions import (CANONICAL_DESCRIPTIONS,@@ -81,7 +129,7 @@ class WooCommerceSource(ResumableSource[WooCommerceSourceConfig, WooCommerceResuforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, supports_webhooks=WEBHOOK_SCHEMA_NAMES)def validate_credentials(self,@@ -124,6 +172,30 @@ class WooCommerceSource(ResumableSource[WooCommerceSourceConfig, WooCommerceResudef get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[WooCommerceResumeConfig]:return ResumableSourceManager[WooCommerceResumeConfig](inputs, WooCommerceResumeConfig)+ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:+ return WebhookSourceManager(inputs, inputs.logger)++ def create_webhook(+ self, config: WooCommerceSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> WebhookCreationResult:+ return create_woocommerce_webhook(+ config.store_url, config.consumer_key, config.consumer_secret, team_id, webhook_url+ )++ def get_external_webhook_info(+ self, config: WooCommerceSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> ExternalWebhookInfo:+ return get_woocommerce_webhook_info(+ config.store_url, config.consumer_key, config.consumer_secret, team_id, webhook_url+ )++ def delete_webhook(+ self, config: WooCommerceSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> WebhookDeletionResult:+ return delete_woocommerce_webhook(+ config.store_url, config.consumer_key, config.consumer_secret, team_id, webhook_url+ )+def source_for_pipeline(self,config: WooCommerceSourceConfig,@@ -146,15 +218,29 @@ class WooCommerceSource(ResumableSource[WooCommerceSourceConfig, WooCommerceResudb_incremental_field_last_value=inputs.db_incremental_field_last_value if use_incremental else None,)+ # Webhooks supplement the backfill rather than replacing it: the manager stays disabled+ # until the schema is on webhook sync and its initial pull has completed, so the first+ # sync still walks the REST API and later ones drain the pushed rows.+ webhook_source_manager = self.get_webhook_source_manager(inputs)+ webhook_enabled = (+ inputs.schema_name in WEBHOOK_SCHEMA_NAMES and async_to_sync(webhook_source_manager.webhook_enabled)()+ )++ def items():+ if webhook_enabled:+ return webhook_source_manager.get_items(table_transformer=webhook_table_transformer)+ return resource+response = SourceResponse(name=resource.name,- items=lambda: resource,+ items=items,primary_keys=["id"],column_hints=resource.column_hints,# Incremental endpoints can't be reliably sorted ascending by the# `date_modified` cursor server-side, so we only commit the watermark- # once the whole resource has been read (desc semantics).- sort_mode="desc" if use_incremental else "asc",+ # once the whole resource has been read (desc semantics). Webhook batches carry no+ # ordering guarantee either, so they take the same conservative path.+ sort_mode="desc" if use_incremental or webhook_enabled else "asc",)partition_key = PARTITION_FIELDS.get(inputs.schema_name)@@ -211,4 +297,24 @@ class WooCommerceSource(ResumableSource[WooCommerceSourceConfig, WooCommerceResu),],),+ webhookSetupCaption=WEBHOOK_SETUP_CAPTION,+ webhookFields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="signing_secret",+ label="Signing secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ caption=(+ "The secret set on your WooCommerce webhooks. PostHog fills this in "+ "automatically when it registers them for you, so you only need it for "+ "manual setup. It verifies the X-WC-Webhook-Signature header on every "+ "delivery."+ ),+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/tests/test_woocommerce.py b/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/tests/test_woocommerce.pyindex 8d1f74825281..70d722777733 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/tests/test_woocommerce.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/tests/test_woocommerce.py@@ -8,11 +8,13 @@ from unittest.mock import MagicMock, patchfrom requests import Request, Response+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_listfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import TrackedHTTPAdapterfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.woocommerce.settings import (ENDPOINT_PATHS,INCREMENTAL_FIELDS,+ WEBHOOK_TOPICS,)from products.warehouse_sources.backend.temporal.data_imports.sources.woocommerce.woocommerce import (DEFAULT_PER_PAGE,@@ -23,9 +25,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.woocommerc_HostGuardedAdapter,_make_guarded_session,_to_woocommerce_datetime,+ create_webhook,+ delete_webhook,+ get_external_webhook_info,get_resource,normalize_store_url,validate_credentials,+ webhook_table_transformer,woocommerce_source,)@@ -394,3 +400,235 @@ class TestSourceHostGuard:resumable_source_manager=manager,db_incremental_field_last_value=None,)+++def _json_response(status_code: int, payload: Any) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 300+ response.json.return_value = payload+ return response+++class TestWebhookManagement:+ """`_make_guarded_session` is the network boundary; everything below it is mocked."""++ def _session(self, list_pages: list[Any], write_response: Any = None) -> MagicMock:+ session = MagicMock()+ session.get.side_effect = [_json_response(200, page) for page in list_pages]+ session.post.return_value = write_response or _json_response(201, {"id": 1})+ session.delete.return_value = _json_response(200, {"id": 1})+ return session++ def _patch(self, session: MagicMock) -> Any:+ return patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.woocommerce.woocommerce._make_guarded_session",+ return_value=session,+ )++ def test_create_registers_every_topic_with_one_shared_secret(self) -> None:+ # Every WooCommerce webhook subscribes to exactly one topic, and they must all carry the+ # same secret — a per-topic secret would make the hog function reject seven of eight.+ session = self._session([[]])++ with self._patch(session):+ result = create_webhook("https://example.com", "ck", "cs", 123, "https://ph.test/hook")++ assert result.success is True+ secret = result.extra_inputs["signing_secret"]+ assert secret++ posted = [call.kwargs["json"] for call in session.post.call_args_list]+ assert [payload["topic"] for payload in posted] == list(WEBHOOK_TOPICS)+ assert {payload["secret"] for payload in posted} == {secret}+ assert {payload["delivery_url"] for payload in posted} == {"https://ph.test/hook"}+ assert {payload["status"] for payload in posted} == {"active"}++ def test_create_updates_an_existing_webhook_instead_of_duplicating_it(self) -> None:+ # A retried setup (or one WooCommerce auto-disabled after five failed deliveries) must+ # re-pin the new secret on the existing hook, not leave the store with two per topic.+ existing = [{"id": 7, "topic": "order.created", "delivery_url": "https://ph.test/hook", "status": "disabled"}]+ session = self._session([existing])++ with self._patch(session):+ result = create_webhook("https://example.com", "ck", "cs", 123, "https://ph.test/hook")++ assert result.success is True+ targets = [call.args[0] for call in session.post.call_args_list]+ assert "https://example.com/wp-json/wc/v3/webhooks/7" in targets+ update = next(+ call.kwargs["json"] for call in session.post.call_args_list if call.args[0].endswith("/webhooks/7")+ )+ assert update["status"] == "active"+ assert "topic" not in update++ def test_create_rolls_back_when_one_topic_fails(self) -> None:+ # Partial registration is worse than none: setup flips every webhook-capable table to+ # webhook sync, so a table whose topic never registered would stop being polled.+ session = MagicMock()+ session.get.side_effect = [+ _json_response(200, []),+ _json_response(200, [{"id": 9, "topic": "product.created", "delivery_url": "https://ph.test/hook"}]),+ ]+ session.post.side_effect = [_json_response(201, {"id": 9}), _json_response(500, {})]+ session.delete.return_value = _json_response(200, {})++ with self._patch(session):+ result = create_webhook("https://example.com", "ck", "cs", 123, "https://ph.test/hook")++ assert result.success is False+ assert result.extra_inputs == {}+ session.delete.assert_called_once()+ assert session.delete.call_args.args[0].endswith("/webhooks/9")++ @pytest.mark.parametrize("status_code", [401, 403])+ def test_create_reports_a_read_only_key_as_a_permission_problem(self, status_code: int) -> None:+ # Webhook management needs Read/Write; the source itself only asks for Read, so this is+ # the expected failure and the message has to say how to fix it.+ session = self._session([[]], write_response=_json_response(status_code, {}))+ session.get.side_effect = [_json_response(200, []), _json_response(200, [])]++ with self._patch(session):+ result = create_webhook("https://example.com", "ck", "cs", 123, "https://ph.test/hook")++ assert result.success is False+ assert result.error is not None+ assert "Read/Write" in result.error++ def test_list_pages_until_a_short_page(self) -> None:+ first_page = [+ {"id": index, "topic": "order.created", "delivery_url": "https://other.test/hook"}+ for index in range(DEFAULT_PER_PAGE)+ ]+ session = self._session(+ [first_page, [{"id": 999, "topic": "order.updated", "delivery_url": "https://ph.test/hook"}]]+ )++ with self._patch(session):+ info = get_external_webhook_info("https://example.com", "ck", "cs", 123, "https://ph.test/hook")++ assert session.get.call_count == 2+ # `status=all` matters: the default list hides the paused and auto-disabled hooks we+ # need to find rather than duplicate.+ assert session.get.call_args.kwargs["params"]["status"] == "all"+ assert info.exists is True+ assert info.enabled_events == ["order.updated"]++ def test_delete_only_removes_our_delivery_url_and_forces(self) -> None:+ # `force=true` is required — WooCommerce 501s on a soft delete — and a store's own+ # webhooks must survive.+ session = self._session(+ [+ [+ {"id": 1, "topic": "order.created", "delivery_url": "https://ph.test/hook"},+ {"id": 2, "topic": "order.created", "delivery_url": "https://someone-else.test/hook"},+ ]+ ]+ )++ with self._patch(session):+ result = delete_webhook("https://example.com", "ck", "cs", 123, "https://ph.test/hook")++ assert result.success is True+ assert session.delete.call_count == 1+ assert session.delete.call_args.args[0].endswith("/webhooks/1")+ assert session.delete.call_args.kwargs["params"] == {"force": "true"}++ def test_delete_succeeds_when_nothing_is_registered(self) -> None:+ session = self._session([[]])++ with self._patch(session):+ result = delete_webhook("https://example.com", "ck", "cs", 123, "https://ph.test/hook")++ assert result.success is True+ session.delete.assert_not_called()++ def test_info_reports_the_unhealthy_topic_not_the_first_one(self) -> None:+ # WooCommerce disables one webhook at a time after five failures, so an "active" first+ # row would hide a topic that has stopped delivering.+ session = self._session(+ [+ [+ {"id": 1, "topic": "order.created", "delivery_url": "https://ph.test/hook", "status": "active"},+ {"id": 2, "topic": "order.updated", "delivery_url": "https://ph.test/hook", "status": "disabled"},+ ]+ ]+ )++ with self._patch(session):+ info = get_external_webhook_info("https://example.com", "ck", "cs", 123, "https://ph.test/hook")++ assert info.exists is True+ assert info.status == "disabled"+ assert info.enabled_events == ["order.created", "order.updated"]++ def test_info_reports_absence_when_no_webhook_targets_us(self) -> None:+ session = self._session([[{"id": 1, "topic": "order.created", "delivery_url": "https://someone-else.test"}]])++ with self._patch(session):+ info = get_external_webhook_info("https://example.com", "ck", "cs", 123, "https://ph.test/hook")++ assert info.exists is False++ @pytest.mark.parametrize(+ "operation",+ [create_webhook, delete_webhook, get_external_webhook_info],+ )+ def test_unsafe_host_never_reaches_the_network(self, operation: Any) -> None:+ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.woocommerce.woocommerce._is_host_safe",+ return_value=(False, "blocked"),+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.woocommerce.woocommerce._make_guarded_session"+ ) as MockSession,+ ):+ result = operation("https://169.254.169.254", "ck", "cs", 123, "https://ph.test/hook")++ assert getattr(result, "success", None) is not True+ MockSession.assert_not_called()+++class TestWebhookTableTransformer:+ def _row(self, row_id: int, modified: str | None, status: str) -> dict[str, Any]:+ return {"id": row_id, "date_modified_gmt": modified, "status": status}++ def test_keeps_only_the_latest_delivery_per_id(self) -> None:+ # Delta merge dedupes across syncs but not within one batch, so a `created` followed by+ # an `updated` for the same order would otherwise both reach the merge.+ table = table_from_py_list(+ [+ self._row(1, "2026-05-01T10:00:00", "pending"),+ self._row(1, "2026-05-01T12:00:00", "completed"),+ self._row(2, "2026-05-01T09:00:00", "processing"),+ ]+ )++ result = webhook_table_transformer(table).to_pylist()++ assert sorted(row["id"] for row in result) == [1, 2]+ assert next(row for row in result if row["id"] == 1)["status"] == "completed"++ def test_out_of_order_delivery_still_keeps_the_newest(self) -> None:+ table = table_from_py_list(+ [+ self._row(1, "2026-05-01T12:00:00", "completed"),+ self._row(1, "2026-05-01T10:00:00", "pending"),+ ]+ )++ result = webhook_table_transformer(table).to_pylist()++ assert [row["status"] for row in result] == ["completed"]++ def test_rows_without_a_modified_timestamp_fall_back_to_delivery_order(self) -> None:+ table = table_from_py_list([self._row(1, None, "first"), self._row(1, None, "second")])++ result = webhook_table_transformer(table).to_pylist()++ assert [row["status"] for row in result] == ["second"]++ def test_empty_batch_passes_through(self) -> None:+ table = table_from_py_list([])+ assert webhook_table_transformer(table).num_rows == 0diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/tests/test_woocommerce_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/tests/test_woocommerce_source.pyindex d574a614819c..6c95997702d8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/tests/test_woocommerce_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/tests/test_woocommerce_source.py@@ -6,6 +6,7 @@ from unittest import mockfrom posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigTypefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.woocommerce import (WooCommerceSourceConfig,)@@ -13,6 +14,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.woocommercENDPOINTS,INCREMENTAL_FIELDS,PARTITION_FIELDS,+ SCHEMA_TO_WEBHOOK_RESOURCE,+ WEBHOOK_SCHEMA_NAMES,+ WEBHOOK_TOPICS,)from products.warehouse_sources.backend.temporal.data_imports.sources.woocommerce.source import WooCommerceSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.woocommerce.woocommerce import (@@ -33,6 +37,17 @@ def _make_inputs(schema_name: str, should_use_incremental_field: bool = False, l)[email protected](autouse=True)+def webhook_disabled():+ """Default every test to the polling path.++ `webhook_enabled` reads the schema row out of Postgres to decide whether the table has been+ switched to webhook sync; tests that care about that branch re-patch it themselves.+ """+ with mock.patch.object(WebhookSourceManager, "webhook_enabled", new=mock.AsyncMock(return_value=False)) as patched:+ yield patched++class TestWooCommerceSource:def setup_method(self):self.source = WooCommerceSource()@@ -195,3 +210,104 @@ class TestWooCommerceSource:assert response.partition_keys == [expected_key]else:assert response.partition_keys is None++ def test_get_schemas_marks_only_webhook_capable_tables(self):+ # WooCommerce only ships core webhook topics for four resources. Marking any other table+ # would let setup switch it to webhook sync, which stops polling it for rows that can+ # never arrive.+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}++ assert {name for name, s in schemas.items() if s.supports_webhooks} == set(WEBHOOK_SCHEMA_NAMES)++ def test_webhook_resource_map_covers_every_webhook_capable_schema(self):+ # The map is what routes an incoming delivery to a table; a schema missing from it is a+ # table that silently receives nothing.+ assert set(self.source.webhook_resource_map) == set(WEBHOOK_SCHEMA_NAMES)+ assert {f"{resource}.created" for resource in self.source.webhook_resource_map.values()} <= set(WEBHOOK_TOPICS)++ def test_webhook_template_verifies_the_woocommerce_signature_header(self):+ template = self.source.webhook_template++ assert template is not None+ assert template.type == "warehouse_source_webhook"+ assert "x-wc-webhook-signature" in template.code+ assert {field["key"] for field in template.inputs_schema} >= {"signing_secret", "schema_mapping", "source_id"}++ def test_webhook_signing_secret_field_is_offered_for_manual_setup(self):+ config = self.source.get_source_config++ assert config.webhookSetupCaption+ assert config.webhookFields is not None+ signing_secret = config.webhookFields[0]+ assert isinstance(signing_secret, SourceFieldInputConfig)+ assert signing_secret.name == "signing_secret"+ assert signing_secret.type == SourceFieldInputConfigType.PASSWORD+ assert signing_secret.secret is True++ @pytest.mark.parametrize(+ "method_name, transport_name",+ [+ ("create_webhook", "create_woocommerce_webhook"),+ ("delete_webhook", "delete_woocommerce_webhook"),+ ("get_external_webhook_info", "get_woocommerce_webhook_info"),+ ],+ )+ def test_webhook_management_passes_the_store_credentials_through(self, method_name, transport_name):+ # The store URL and the key/secret pair are positional; swapping two of them would send+ # the consumer key as the secret and 401 on every store.+ with mock.patch(+ f"products.warehouse_sources.backend.temporal.data_imports.sources.woocommerce.source.{transport_name}"+ ) as mock_transport:+ getattr(self.source, method_name)(self.config, "https://ph.test/hook", self.team_id)++ mock_transport.assert_called_once_with(+ "https://example.com", "ck_test", "cs_test", self.team_id, "https://ph.test/hook"+ )++ def test_source_for_pipeline_keeps_polling_while_webhooks_are_not_active(self, webhook_disabled):+ manager = mock.MagicMock(spec=ResumableSourceManager)++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.woocommerce.source.woocommerce_source"+ ) as mock_source:+ resource = mock.MagicMock(name="orders", column_hints=None)+ mock_source.return_value = resource+ response = self.source.source_for_pipeline(self.config, manager, _make_inputs("orders"))++ assert response.items() is resource++ def test_source_for_pipeline_reads_pushed_rows_once_webhooks_are_active(self, webhook_disabled):+ # Once the schema is on webhook sync and its backfill has completed, the sync has to drain+ # the buffered deliveries instead of re-walking the REST API.+ webhook_disabled.return_value = True+ manager = mock.MagicMock(spec=ResumableSourceManager)++ with (+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.woocommerce.source.woocommerce_source"+ ) as mock_source,+ mock.patch.object(WebhookSourceManager, "get_items") as mock_get_items,+ ):+ mock_source.return_value = mock.MagicMock(name="orders", column_hints=None)+ response = self.source.source_for_pipeline(self.config, manager, _make_inputs("orders"))+ items = response.items()++ assert items is mock_get_items.return_value+ # Delta merge only dedupes across syncs, so the within-batch transformer must be wired up.+ assert mock_get_items.call_args.kwargs["table_transformer"] is not None++ def test_source_for_pipeline_never_consults_webhooks_for_a_polling_only_table(self, webhook_disabled):+ manager = mock.MagicMock(spec=ResumableSourceManager)++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.woocommerce.source.woocommerce_source"+ ) as mock_source:+ mock_source.return_value = mock.MagicMock(name="tax_rates", column_hints=None)+ self.source.source_for_pipeline(self.config, manager, _make_inputs("tax_rates"))++ webhook_disabled.assert_not_awaited()++ def test_webhook_resources_are_distinct(self):+ # Two schemas sharing a resource key would collide in `schema_mapping` and one table+ # would stop receiving deliveries entirely.+ assert len(set(SCHEMA_TO_WEBHOOK_RESOURCE.values())) == len(SCHEMA_TO_WEBHOOK_RESOURCE)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/tests/test_woocommerce_webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/tests/test_woocommerce_webhook_template.pynew file mode 100644index 000000000000..59ee3422d135--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/tests/test_woocommerce_webhook_template.py@@ -0,0 +1,193 @@+import hmac+import json+import base64+import hashlib++from parameterized import parameterized++from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest++from products.warehouse_sources.backend.temporal.data_imports.sources.woocommerce.webhook_template import template++SOURCE_ID = "source_test_123"+SIGNING_SECRET = "cQ8oXhZ0mF3jWl2pR7tYb5NvA1sKdE6g"+SCHEMA_MAPPING = {+ "product": "schema_products",+ "order": "schema_orders",+ "coupon": "schema_coupons",+ "customer": "schema_customers",+}+++class TestWooCommerceWarehouseWebhookTemplate(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 _object(self, object_id: int = 42) -> dict:+ return {+ "id": object_id,+ "status": "completed",+ "date_created_gmt": "2026-05-01T10:00:00",+ "date_modified_gmt": "2026-05-01T11:00:00",+ }++ def _request(+ self,+ secret: str,+ body: dict,+ resource: str = "order",+ event: str = "updated",+ method: str = "POST",+ ) -> dict:+ payload = json.dumps(body)+ signature = base64.b64encode(hmac.new(secret.encode(), payload.encode(), hashlib.sha256).digest()).decode()+ return {+ "request": {+ "method": method,+ "headers": {+ "x-wc-webhook-signature": signature,+ "x-wc-webhook-resource": resource,+ "x-wc-webhook-event": event,+ "x-wc-webhook-topic": f"{resource}.{event}",+ },+ "body": json.loads(payload),+ "stringBody": payload,+ "query": {},+ }+ }++ def _inputs(self, **overrides) -> dict:+ return {+ "signing_secret": SIGNING_SECRET,+ "bypass_signature_check": False,+ "schema_mapping": SCHEMA_MAPPING,+ "source_id": SOURCE_ID,+ **overrides,+ }++ @parameterized.expand(+ [+ ("product", "created", "schema_products"),+ ("product", "updated", "schema_products"),+ ("order", "created", "schema_orders"),+ ("order", "updated", "schema_orders"),+ ("coupon", "updated", "schema_coupons"),+ ("customer", "created", "schema_customers"),+ ]+ )+ def test_routes_each_subscribed_topic_to_its_table(self, resource, event, expected_schema_id):+ # WooCommerce puts the object type in a header, not the body, and signs with base64+ # rather than hex - getting either wrong drops every delivery.+ globals = self._request(SIGNING_SECRET, self._object(), resource=resource, event=event)++ self.run_function(self._inputs(), globals=globals)++ self.mock_produce_to_warehouse_webhooks.assert_called_once_with(globals["request"]["body"], expected_schema_id)++ def test_delete_event_is_dropped(self):+ # A `.deleted` payload is only `{"id": ...}`; merging it would null every other column+ # on the row it matched.+ globals = self._request(SIGNING_SECRET, {"id": 42}, resource="order", event="deleted")++ res = self.run_function(self._inputs(), globals=globals)++ assert res.result["httpResponse"]["status"] == 200+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ @parameterized.expand(+ [+ ("unmapped_resource", {"x-wc-webhook-resource": "product_review"}, SCHEMA_MAPPING),+ ("table_not_enabled", {}, {"product": "schema_products"}),+ ]+ )+ def test_delivery_with_no_schema_is_acknowledged_and_dropped(self, _name, header_overrides, schema_mapping):+ # WooCommerce disables a webhook after five consecutive non-2xx responses, so a delivery+ # we have nowhere to put must still be acknowledged.+ globals = self._request(SIGNING_SECRET, self._object())+ globals["request"]["headers"].update(header_overrides)++ res = self.run_function(self._inputs(schema_mapping=schema_mapping), globals=globals)++ assert res.result["httpResponse"]["status"] == 200+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_payload_without_an_id_is_dropped(self):+ globals = self._request(SIGNING_SECRET, {"status": "completed"})++ 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_bad_signature_is_rejected(self):+ globals = self._request("some-other-secret", self._object())++ 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()++ @parameterized.expand(+ [+ ("missing_signature", {}, {"signing_secret": SIGNING_SECRET}, "Missing signature"),+ (+ "no_secret_configured",+ {"x-wc-webhook-signature": "x"},+ {"signing_secret": ""},+ "Signing secret not configured",+ ),+ ]+ )+ def test_unverifiable_delivery_is_rejected(self, _name, headers, input_overrides, expected_body):+ body = self._object()+ globals = {+ "request": {+ "method": "POST",+ "headers": {"x-wc-webhook-resource": "order", "x-wc-webhook-event": "updated", **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_non_post_request_returns_405(self):+ globals = self._request(SIGNING_SECRET, self._object(), 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):+ body = self._object()+ globals = {+ "request": {+ "method": "POST",+ "headers": {"x-wc-webhook-resource": "order", "x-wc-webhook-event": "updated"},+ "body": body,+ "stringBody": json.dumps(body),+ "query": {},+ }+ }++ self.run_function(self._inputs(signing_secret="", bypass_signature_check=True), globals=globals)++ self.mock_produce_to_warehouse_webhooks.assert_called_once_with(body, "schema_orders")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/webhook_template.pynew file mode 100644index 000000000000..0505bfff7e62--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/webhook_template.py@@ -0,0 +1,148 @@+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC++template: HogFunctionTemplateDC = HogFunctionTemplateDC(+ status="alpha",+ free=False,+ type="warehouse_source_webhook",+ id="template-warehouse-source-woocommerce",+ name="WooCommerce warehouse source webhook",+ description="Receive WooCommerce webhook events for data warehouse ingestion",+ icon_url="/static/services/woocommerce.png",+ category=["Data warehouse"],+ code_language="hog",+ code="""\+if (request.method != 'POST') {+ return {+ 'httpResponse': {+ 'status': 405,+ 'body': 'Method not allowed'+ }+ }+}++if (not inputs.bypass_signature_check) {+ if (empty(inputs.signing_secret)) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Signing secret not configured',+ }+ }+ }++ let signature := request.headers['x-wc-webhook-signature']++ if (empty(signature)) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Missing signature',+ }+ }+ }++ // WooCommerce sends base64(HMAC-SHA256(raw body, webhook secret)). No timestamp is involved.+ // The store's create-time ping carries no signature and lands here as a 400, which is expected+ // and harmless: WooCommerce ignores the ping response and it never counts as a delivery failure.+ let computedSignature := sha256HmacChain([inputs.signing_secret, request.stringBody], 'base64')++ if (computedSignature != signature) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Bad signature',+ }+ }+ }+}++// `deleted` payloads carry only `{"id": ...}`, so merging one would null out every other column+// of the row it matched.+if (request.headers['x-wc-webhook-event'] == 'deleted') {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'Delete event, skipping'+ }+ }+}++// WooCommerce puts the object type in a header rather than the body, so this is the only+// discriminator available for routing a delivery to its table.+let resource := request.headers['x-wc-webhook-resource']++if (empty(resource)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'No webhook resource header found, skipping'+ }+ }+}++let schemaId := inputs.schema_mapping?.[resource]++if (empty(schemaId)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': f'No schema mapping for resource: {resource}, skipping'+ }+ }+}++// A payload with no id can't be merged onto the table, and it's what WooCommerce sends when the+// object was removed between the hook firing and the payload being built.+if (empty(request.body.id)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'Payload has no id, skipping'+ }+ }+}++produceToWarehouseWebhooks(request.body, schemaId)""",+ inputs_schema=[+ {+ "type": "string",+ "key": "signing_secret",+ "label": "Signing secret",+ "required": False,+ "secret": True,+ "hidden": False,+ "description": (+ "The secret set on the WooCommerce webhook. Used to verify the X-WC-Webhook-Signature "+ "header (base64 HMAC-SHA256 of the raw request body) so deliveries provably come from "+ "your store."+ ),+ },+ {+ "type": "boolean",+ "key": "bypass_signature_check",+ "label": "Bypass signature check",+ "description": "If set, the X-WC-Webhook-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 WooCommerce webhook 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,+ },+ ],+)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/woocommerce.py b/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/woocommerce.pyindex 5188f46338dc..de1e1577f627 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/woocommerce.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/woocommerce.py@@ -1,11 +1,19 @@+import secretsimport dataclassesfrom collections.abc import Mappingfrom datetime import UTC, date, datetimefrom typing import Any, Optionalfrom urllib.parse import urlparse-from requests import PreparedRequest, Request, Response, Session+import pyarrow as pa+from requests import PreparedRequest, Request, RequestException, Response, Session+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 (DEFAULT_RETRY,TrackedHTTPAdapter,@@ -22,6 +30,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.woocommerce.settings import (ENDPOINT_PATHS,INCREMENTAL_FIELDS,+ WEBHOOK_TOPICS,)# All WooCommerce REST API v3 endpoints hang off this path on the store domain.@@ -33,6 +42,13 @@ DEFAULT_PER_PAGE = 100# before the request ever reaches WooCommerce. Identify ourselves with a stable,# non-default agent so those layers let legitimate sync traffic through.WOOCOMMERCE_USER_AGENT = "PostHog Data Warehouse (WooCommerce source; +https://posthog.com)"+# Name given to every webhook we register, so a store owner can tell ours apart in+# WooCommerce > Settings > Advanced > Webhooks.+WEBHOOK_NAME = "PostHog Data warehouse"+# Webhook lists are page-numbered like every other WooCommerce collection. A store with more+# than this many webhooks is pathological; cap the scan rather than paging forever.+WEBHOOK_LIST_MAX_PAGES = 20+REQUEST_TIMEOUT_SECONDS = 30@dataclasses.dataclass@@ -295,6 +311,234 @@ def woocommerce_source()+def webhook_table_transformer(table: pa.Table) -> pa.Table:+ """Keep only the newest delivery per object id within one webhook batch.++ Deliveries land as the bare wc/v3 object, so the table is already shaped like the polled+ table. What it isn't is deduplicated: delta merge dedupes across syncs but not within a+ single source batch, so a `created` followed by an `updated` for the same order both survive+ into the batch and the merge would multi-match them. WooCommerce stamps every one of these+ objects with `date_modified_gmt`, which is ISO8601 and therefore lexicographically ordered;+ ties fall back to delivery order, which S3 preserves.+ """+ if table.num_rows == 0 or "id" not in table.column_names:+ return table++ modified_column = (+ table.column("date_modified_gmt").to_pylist()+ if "date_modified_gmt" in table.column_names+ else [None] * table.num_rows+ )++ latest_by_id: dict[Any, tuple[str, dict[str, Any]]] = {}+ for row, modified in zip(table.to_pylist(), modified_column):+ row_id = row.get("id")+ if row_id is None:+ continue+ modified_at = str(modified) if modified is not None else ""+ existing = latest_by_id.get(row_id)+ if existing is None or modified_at >= existing[0]:+ latest_by_id[row_id] = (modified_at, row)++ return table_from_py_list([row for _, row in latest_by_id.values()])+++def _webhook_error(response: Response, action: str) -> str:+ """Turn a failed webhook-management response into something the user can act on."""+ if response.status_code in (401, 403):+ return (+ f"Your WooCommerce API key is not allowed to {action} webhooks. Webhook management needs a "+ "key with **Read/Write** permission - edit the key under WooCommerce > Settings > Advanced > "+ "REST API, or set the webhooks up manually."+ )++ detail = ""+ try:+ body = response.json()+ if isinstance(body, dict) and isinstance(body.get("message"), str):+ detail = f": {body['message']}"+ except ValueError:+ pass++ return f"WooCommerce returned {response.status_code} when trying to {action} webhooks{detail}."+++def _list_webhooks(+ store_url: str, consumer_key: str, consumer_secret: str, team_id: int+) -> tuple[list[dict[str, Any]], Optional[str]]:+ """Every webhook registered on the store, paged. Returns (webhooks, error)."""+ session = _make_guarded_session(team_id, redact_values=(consumer_key, consumer_secret))+ auth = WooCommerceAuth(consumer_key, consumer_secret)+ url = f"{_base_url(store_url)}/webhooks"++ webhooks: list[dict[str, Any]] = []+ for page in range(1, WEBHOOK_LIST_MAX_PAGES + 1):+ # `status=all` is required: WooCommerce's default list hides paused and auto-disabled+ # webhooks, and those are exactly the ones we need to find and reactivate rather than+ # duplicate.+ params: dict[str, str | int] = {"per_page": DEFAULT_PER_PAGE, "page": page, "status": "all"}+ try:+ response = session.get(+ url,+ params=params,+ auth=auth,+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ except (RequestException, ValueError) as e:+ return [], f"Could not reach your WooCommerce store to list webhooks: {e}"++ if not response.ok:+ return [], _webhook_error(response, "list")++ try:+ batch = response.json()+ except ValueError:+ return [], "Your WooCommerce store returned an unexpected response when listing webhooks."++ if not isinstance(batch, list) or not batch:+ break++ webhooks.extend(item for item in batch if isinstance(item, dict))++ if len(batch) < DEFAULT_PER_PAGE:+ break++ return webhooks, None+++def _webhooks_for_url(webhooks: list[dict[str, Any]], webhook_url: str) -> list[dict[str, Any]]:+ return [webhook for webhook in webhooks if webhook.get("delivery_url") == webhook_url]+++def create_webhook(+ store_url: str, consumer_key: str, consumer_secret: str, team_id: int, webhook_url: str+) -> WebhookCreationResult:+ """Register one WooCommerce webhook per topic, all pointing at `webhook_url` with one secret.++ WooCommerce subscribes a webhook to exactly one topic, so a store ends up with one webhook per+ resource/event pair. All of them share the secret we generate here, which WooCommerce never+ echoes back on read - hence returning it via `extra_inputs` for the hog function to verify with.++ Existing webhooks on the same delivery URL are updated in place rather than duplicated, so a+ retried setup re-pins the new secret and reactivates anything WooCommerce auto-disabled after+ five failed deliveries.+ """+ try:+ _assert_host_safe(store_url, team_id)+ except ValueError as e:+ return WebhookCreationResult(success=False, error=str(e))++ existing, error = _list_webhooks(store_url, consumer_key, consumer_secret, team_id)+ if error is not None:+ return WebhookCreationResult(success=False, error=error)++ # WooCommerce runs the secret through `wp_specialchars_decode` before hashing, so the alphabet+ # has to be free of HTML entities - `token_urlsafe` is.+ secret = secrets.token_urlsafe(32)+ session = _make_guarded_session(team_id, redact_values=(consumer_key, consumer_secret, secret))+ auth = WooCommerceAuth(consumer_key, consumer_secret)+ url = f"{_base_url(store_url)}/webhooks"++ by_topic = {webhook.get("topic"): webhook for webhook in _webhooks_for_url(existing, webhook_url)}++ for topic in WEBHOOK_TOPICS:+ match = by_topic.get(topic)+ payload: dict[str, Any] = {"name": WEBHOOK_NAME, "status": "active", "secret": secret}+ if match is None:+ payload |= {"topic": topic, "delivery_url": webhook_url}+ target = url+ else:+ # WooCommerce accepts POST as well as PUT for an update, so one verb covers both.+ target = f"{url}/{match['id']}"++ try:+ response = session.post(target, json=payload, auth=auth, timeout=REQUEST_TIMEOUT_SECONDS)+ except (RequestException, ValueError) as e:+ error = f"Could not reach your WooCommerce store to create webhooks: {e}"+ else:+ if response.ok:+ continue+ error = _webhook_error(response, "create")++ # Partial success is worse than none: the setup flow switches every webhook-capable table+ # to webhook sync on success, so a table whose topic never registered would stop being+ # polled and receive nothing. Roll back what we just created and report the failure.+ delete_webhook(store_url, consumer_key, consumer_secret, team_id, webhook_url)+ return WebhookCreationResult(success=False, error=error)++ return WebhookCreationResult(success=True, extra_inputs={"signing_secret": secret})+++def delete_webhook(+ store_url: str, consumer_key: str, consumer_secret: str, team_id: int, webhook_url: str+) -> WebhookDeletionResult:+ """Delete every webhook on the store that delivers to `webhook_url`."""+ try:+ _assert_host_safe(store_url, team_id)+ except ValueError as e:+ return WebhookDeletionResult(success=False, error=str(e))++ existing, error = _list_webhooks(store_url, consumer_key, consumer_secret, team_id)+ if error is not None:+ return WebhookDeletionResult(success=False, error=error)++ matches = _webhooks_for_url(existing, webhook_url)+ if not matches:+ return WebhookDeletionResult(success=True)++ session = _make_guarded_session(team_id, redact_values=(consumer_key, consumer_secret))+ auth = WooCommerceAuth(consumer_key, consumer_secret)++ for webhook in matches:+ try:+ response = session.delete(+ f"{_base_url(store_url)}/webhooks/{webhook['id']}",+ # Webhooks don't support trashing - WooCommerce 501s without this.+ params={"force": "true"},+ auth=auth,+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ except (RequestException, ValueError) as e:+ return WebhookDeletionResult(success=False, error=f"Could not reach your WooCommerce store: {e}")++ if not response.ok:+ return WebhookDeletionResult(success=False, error=_webhook_error(response, "delete"))++ return WebhookDeletionResult(success=True)+++def get_external_webhook_info(+ store_url: str, consumer_key: str, consumer_secret: str, team_id: int, webhook_url: str+) -> ExternalWebhookInfo:+ """Report the webhooks currently registered on the store for `webhook_url`."""+ try:+ _assert_host_safe(store_url, team_id)+ except ValueError as e:+ return ExternalWebhookInfo(exists=False, url=webhook_url, error=str(e))++ existing, error = _list_webhooks(store_url, consumer_key, consumer_secret, team_id)+ if error is not None:+ return ExternalWebhookInfo(exists=False, url=webhook_url, error=error)++ matches = _webhooks_for_url(existing, webhook_url)+ if not matches:+ return ExternalWebhookInfo(exists=False, url=webhook_url)++ statuses = [str(webhook.get("status")) for webhook in matches if webhook.get("status")]+ # WooCommerce disables a webhook after five consecutive delivery failures, and each topic has+ # its own webhook, so surface the unhealthy one rather than whichever came back first.+ unhealthy = sorted(status for status in statuses if status != "active")+ created = sorted(str(webhook["date_created_gmt"]) for webhook in matches if webhook.get("date_created_gmt"))++ return ExternalWebhookInfo(+ exists=True,+ url=webhook_url,+ enabled_events=sorted({str(webhook["topic"]) for webhook in matches if webhook.get("topic")}),+ status=unhealthy[0] if unhealthy else "active",+ created_at=created[0] if created else None,+ )++def validate_credentials(store_url: str, consumer_key: str, consumer_secret: str, team_id: int) -> Optional[int]:"""Probe a cheap authenticated endpoint. Returns the HTTP status code, or None on a connection error.