: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
chore(messaging): move the Customer.io webhook behind the facade (#114025)
Harley Alexanderdc9780714a33
diff --git a/products/messaging/backend/facade/customerio.py b/products/messaging/backend/facade/customerio.pyindex 0ea5c0a28eb2..cfab66c1708d 100644--- a/products/messaging/backend/facade/customerio.py+++ b/products/messaging/backend/facade/customerio.py@@ -1,10 +1,11 @@"""Customer.io sync setup: the App API import, the inbound webhook, the outbound Track API, and the CSV import."""+from dataclasses import fieldfrom typing import IO, Anyfrom posthog.dataclasses import frozen-from products.messaging.backend.services import customerio_config+from products.messaging.backend.services import customerio_config, customerio_webhookclass CustomerIOConfigConflict(Exception):@@ -97,3 +98,33 @@ def remove_track_config(team_id: int) -> None:def import_preferences_csv(team_id: int, csv_file: IO[bytes], created_by_id: int | None) -> dict[str, Any]:"""Import recipient preferences from a Customer.io CSV export. Returns the result as the API serves it."""return customerio_config.import_preferences_csv(team_id, csv_file, created_by_id)+++@frozen+class WebhookSigningSecret:+ secret: str | None = field(repr=False)+ integration_id: int+++def webhook_signing_secret(team_id: int) -> WebhookSigningSecret | None:+ """The inbound webhook's signing secret, or None when the team has not enabled the webhook."""+ found = customerio_webhook.signing_secret(team_id)+ if found is None:+ return None+ secret, integration_id = found+ return WebhookSigningSecret(secret=secret, integration_id=integration_id)+++def record_global_unsubscribe(team_id: int, email: str) -> None:+ """Opt the recipient out of all marketing, unless they already are."""+ customerio_webhook.global_unsubscribe(team_id, email)+++def record_global_resubscribe(team_id: int, email: str) -> None:+ """Clear the recipient's global opt-out, when they have one."""+ customerio_webhook.global_resubscribe(team_id, email)+++def record_topic_preferences(team_id: int, email: str, topics: dict[str, Any]) -> None:+ """Map Customer.io topics onto the imported categories and store the changed statuses."""+ customerio_webhook.apply_topic_preferences(team_id, email, topics)diff --git a/products/messaging/backend/presentation/views/customerio_webhook.py b/products/messaging/backend/presentation/views/customerio_webhook.pyindex 70b6eaaf5d76..83a91e01687d 100644--- a/products/messaging/backend/presentation/views/customerio_webhook.py+++ b/products/messaging/backend/presentation/views/customerio_webhook.py@@ -1,5 +1,4 @@import json-import loggingfrom typing import Anyfrom rest_framework.request import Request@@ -9,21 +8,19 @@ from rest_framework.views import APIViewfrom posthog.auth import WebhookSignatureAuthenticationfrom posthog.models.integration import Integration-from products.messaging.backend.models.message_category import MessageCategory-from products.messaging.backend.models.message_preferences import (- ALL_MESSAGE_PREFERENCE_CATEGORY_ID,- MessageRecipientPreference,- PreferenceStatus,+from products.messaging.backend.facade.customerio import (+ record_global_resubscribe,+ record_global_unsubscribe,+ record_topic_preferences,+ webhook_signing_secret,)-from products.messaging.backend.models.optout_sync_config import OptOutSyncConfig--logger = logging.getLogger(__name__)class CustomerIOWebhookAuthentication(WebhookSignatureAuthentication):"""Customer.io HMAC-SHA256 webhook verification."""- _integration: Integration | None = None+ _team_id: int | None = None+ _integration_id: int | None = Nonedef get_signature_header(self) -> str:return "x-cio-signature"@@ -38,17 +35,17 @@ class CustomerIOWebhookAuthentication(WebhookSignatureAuthentication):team_id = self._get_team_id(request)if not team_id:return None- try:- config = OptOutSyncConfig.objects.select_related("webhook_integration").get(team_id=team_id)- except OptOutSyncConfig.DoesNotExist:- return None- if not config.webhook_enabled or not config.webhook_integration:+ found = webhook_signing_secret(team_id)+ if found is None:return None- self._integration = config.webhook_integration- return self._integration.sensitive_config.get("webhook_signing_secret")+ self._team_id = team_id+ self._integration_id = found.integration_id+ return found.secretdef get_auth_context(self, request: Request) -> Any:- return self._integration+ if self._team_id is None or self._integration_id is None:+ return None+ return Integration.objects.filter(team_id=self._team_id, pk=self._integration_id).first()class CustomerIOWebhookView(APIView):@@ -82,17 +79,10 @@ class CustomerIOWebhookView(APIView):return Response(status=200)def _handle_global_unsubscribe(self, team_id: int, email: str) -> None:- recipient, _ = MessageRecipientPreference.objects.get_or_create(team_id=team_id, identifier=email)- if recipient.preferences.get(ALL_MESSAGE_PREFERENCE_CATEGORY_ID) == PreferenceStatus.OPTED_OUT.value:- return- recipient.preferences[ALL_MESSAGE_PREFERENCE_CATEGORY_ID] = PreferenceStatus.OPTED_OUT.value- recipient.save(update_fields=["preferences", "updated_at"])+ record_global_unsubscribe(team_id, email)def _handle_global_resubscribe(self, team_id: int, email: str) -> None:- recipient, _ = MessageRecipientPreference.objects.get_or_create(team_id=team_id, identifier=email)- if ALL_MESSAGE_PREFERENCE_CATEGORY_ID in recipient.preferences:- del recipient.preferences[ALL_MESSAGE_PREFERENCE_CATEGORY_ID]- recipient.save(update_fields=["preferences", "updated_at"])+ record_global_resubscribe(team_id, email)def _handle_preferences_changed(self, team_id: int, email: str, data: dict) -> None:content_str = data.get("content", "")@@ -105,28 +95,4 @@ class CustomerIOWebhookView(APIView):if not topics:return- topic_key_to_category: dict[str, str] = {}- categories = MessageCategory.objects.filter(team_id=team_id, key__startswith="customerio_", deleted=False)- for cat in categories:- topic_key = cat.key.removeprefix("customerio_")- topic_key_to_category[topic_key] = str(cat.id)-- if not topic_key_to_category:- return-- recipient, _ = MessageRecipientPreference.objects.get_or_create(team_id=team_id, identifier=email)-- changed = False- for topic_key, is_subscribed in topics.items():- category_id = topic_key_to_category.get(topic_key)- if not category_id:- logger.warning("customerio_webhook: unknown topic %s for team %s", topic_key, team_id)- continue-- new_status = PreferenceStatus.OPTED_IN.value if is_subscribed else PreferenceStatus.OPTED_OUT.value- if recipient.preferences.get(category_id) != new_status:- recipient.preferences[category_id] = new_status- changed = True-- if changed:- recipient.save(update_fields=["preferences", "updated_at"])+ record_topic_preferences(team_id, email, topics)diff --git a/products/messaging/backend/services/customerio_webhook.py b/products/messaging/backend/services/customerio_webhook.pynew file mode 100644index 000000000000..a6dfb6c733ff--- /dev/null+++ b/products/messaging/backend/services/customerio_webhook.py@@ -0,0 +1,66 @@+import logging+from typing import Any++from products.messaging.backend.models.message_category import MessageCategory+from products.messaging.backend.models.message_preferences import (+ ALL_MESSAGE_PREFERENCE_CATEGORY_ID,+ MessageRecipientPreference,+ PreferenceStatus,+)+from products.messaging.backend.models.optout_sync_config import OptOutSyncConfig++logger = logging.getLogger(__name__)+++def signing_secret(team_id: int) -> tuple[str | None, int] | None:+ try:+ config = OptOutSyncConfig.objects.select_related("webhook_integration").get(team_id=team_id)+ except OptOutSyncConfig.DoesNotExist:+ return None+ if not config.webhook_enabled or not config.webhook_integration:+ return None+ integration = config.webhook_integration+ return integration.sensitive_config.get("webhook_signing_secret"), integration.id+++def global_unsubscribe(team_id: int, email: str) -> None:+ recipient, _ = MessageRecipientPreference.objects.get_or_create(team_id=team_id, identifier=email)+ if recipient.preferences.get(ALL_MESSAGE_PREFERENCE_CATEGORY_ID) == PreferenceStatus.OPTED_OUT.value:+ return+ recipient.preferences[ALL_MESSAGE_PREFERENCE_CATEGORY_ID] = PreferenceStatus.OPTED_OUT.value+ recipient.save(update_fields=["preferences", "updated_at"])+++def global_resubscribe(team_id: int, email: str) -> None:+ recipient, _ = MessageRecipientPreference.objects.get_or_create(team_id=team_id, identifier=email)+ if ALL_MESSAGE_PREFERENCE_CATEGORY_ID in recipient.preferences:+ del recipient.preferences[ALL_MESSAGE_PREFERENCE_CATEGORY_ID]+ recipient.save(update_fields=["preferences", "updated_at"])+++def apply_topic_preferences(team_id: int, email: str, topics: dict[str, Any]) -> None:+ topic_key_to_category: dict[str, str] = {}+ categories = MessageCategory.objects.filter(team_id=team_id, key__startswith="customerio_", deleted=False)+ for cat in categories:+ topic_key = cat.key.removeprefix("customerio_")+ topic_key_to_category[topic_key] = str(cat.id)++ if not topic_key_to_category:+ return++ recipient, _ = MessageRecipientPreference.objects.get_or_create(team_id=team_id, identifier=email)++ changed = False+ for topic_key, is_subscribed in topics.items():+ category_id = topic_key_to_category.get(topic_key)+ if not category_id:+ logger.warning("customerio_webhook: unknown topic %s for team %s", topic_key, team_id)+ continue++ new_status = PreferenceStatus.OPTED_IN.value if is_subscribed else PreferenceStatus.OPTED_OUT.value+ if recipient.preferences.get(category_id) != new_status:+ recipient.preferences[category_id] = new_status+ changed = True++ if changed:+ recipient.save(update_fields=["preferences", "updated_at"])diff --git a/pyproject.toml b/pyproject.tomlindex e2d57dc3831e..f54540001314 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -752,9 +752,6 @@ ignore_imports = [# Lane A: suppression"products.messaging.backend.presentation.views.message_suppression -> products.messaging.backend.models.message_suppression",# Lane B: categories, Customer.io config and the Customer.io webhook- "products.messaging.backend.presentation.views.customerio_webhook -> products.messaging.backend.models.message_category",- "products.messaging.backend.presentation.views.customerio_webhook -> products.messaging.backend.models.message_preferences",- "products.messaging.backend.presentation.views.customerio_webhook -> products.messaging.backend.models.optout_sync_config","products.messaging.backend.presentation.views.message_categories -> products.messaging.backend.models.message_category",# Lane C: preferences and the recipient preferences page"products.messaging.backend.presentation.views.message_preferences -> products.messaging.backend.models.message_category",