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.

13.8 KB
Raw Blame
from typing import TYPE_CHECKING, Optional, cast

from products.warehouse_sources.sources.sdk import (
    UNVERSIONED_API_VERSION,
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    ExternalWebhookInfo,
    FieldType,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    WebhookCreationResult,
    WebhookDeletionResult,
    WebhookSource,
    WebhookSourceManager,
    WebhookSyncResult,
    build_endpoint_schemas,
    detect,
)
from products.warehouse_sources.sources.whop import whop as api_client
from products.warehouse_sources.sources.whop._config import WhopSourceConfig
from products.warehouse_sources.sources.whop.settings import (
    INCREMENTAL_FIELDS,
    MERGE_ONLY_ENDPOINTS,
    RESOURCE_TO_EVENT_PREFIX,
    SCHEMA_TO_WEBHOOK_EVENTS,
    WHOP_API_KEYS_URL,
    WHOP_API_VERSION_2025_01_01,
    WHOP_API_VERSION_2026_10_29_8,
    WHOP_API_VERSIONS,
    endpoints_for,
    webhook_schema_names_for,
)
from products.warehouse_sources.sources.whop.whop import WhopResumeConfig

if TYPE_CHECKING:
    from products.warehouse_sources.sources.sdk import HogFunctionTemplateDC


@SourceRegistry.register
class WhopSource(
    ResumableSource[WhopSourceConfig, WhopResumeConfig],
    WebhookSource[WhopSourceConfig],
):
    codebase_detection = detect(
        env=("^WHOP_", "^NEXT_PUBLIC_WHOP_"),
        script_hosts=("cdn.whop.com",),
        npm=(
            "@whop/api",
            "@whop-apps/sdk",
            "@whop/sdk",
            "@whop/react",
            "@whop/checkout",
            "@whop/embedded-components-react-js",
            "@whop/elements",
            "@whop/elements-react",
        ),
        pypi=("whop-sdk", "whop"),
        go=("github.com/whopio/whopsdk-go",),
        swiftpm=(
            "github.com/whopio/whop-ios-react-native-kit",
            "github.com/whopio/whopsdk-checkout-swift",
            "github.com/whopio/whopsdk-elements-swift",
        ),
    )

    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs
    supported_versions = WHOP_API_VERSIONS
    default_version = WHOP_API_VERSION_2026_10_29_8
    api_docs_url = "https://docs.whop.com/developer/api/versioning"

    @property
    def source_type(self) -> ExternalDataSourceType:
        return ExternalDataSourceType.WHOP

    def _api_version_date(self, api_version: str | None) -> str:
        pinned = self.resolve_api_version(api_version)
        # Rows created before the source declared versions carry the unversioned label until the
        # pinning migration moves them. They always ran on Whop's original contract.
        return WHOP_API_VERSION_2025_01_01 if pinned == UNVERSIONED_API_VERSION else pinned

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.WHOP,
            category=DataWarehouseSourceCategory.PAYMENTS___BILLING,
            label="Whop",
            caption=(
                "Connect your Whop company to sync payments, memberships, members, products, promo codes, "
                "invoices, refunds, and disputes into PostHog. Create a company API key in the "
                f"[Developer tab]({WHOP_API_KEYS_URL}) of your Whop dashboard."
            ),
            iconPath="/static/services/whop.png",
            docsUrl="https://posthog.com/docs/cdp/sources/whop",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_key",
                        label="API key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="",
                        caption=(
                            f"Create a company API key in the [Developer tab]({WHOP_API_KEYS_URL}) of your Whop "
                            "dashboard. Grant it read access to the resources you want to sync: "
                            "`company:basic:read`, `member:basic:read`, `payment:basic:read`, "
                            "`access_pass:basic:read`, `plan:basic:read`, `promo_code:basic:read`, "
                            "`invoice:basic:read` and `social_account:read`, plus `developer:manage_webhook` if "
                            "you want PostHog to register the webhook for you."
                        ),
                        secret=True,
                    ),
                    SourceFieldInputConfig(
                        name="company_id",
                        label="Company ID",
                        type=SourceFieldInputConfigType.TEXT,
                        required=True,
                        placeholder="biz_xxxxxxxxxxxxxx",
                        caption="The ID of the Whop company to sync, shown in your Whop dashboard URL.",
                        secret=False,
                    ),
                ],
            ),
            releaseStatus=ReleaseStatus.GA,
            webhookSetupCaption=(
                "PostHog tries to register a Whop webhook for you using your API key, which needs the "
                "`developer:manage_webhook` permission.\n\n"
                "**Manual setup** (only needed if automatic registration failed):\n\n"
                f"1. Go to the [Developer tab]({WHOP_API_KEYS_URL}) in your Whop dashboard\n"
                "2. Click **Create Webhook** and paste the webhook URL shown below\n"
                "3. Set the API version date to the version this source syncs with. It is shown as the source "
                "default under **Vendor API version** on any table's **Configuration** tab. For "
                f"{WHOP_API_VERSION_2025_01_01}, leave the API version date empty\n"
                "4. Select the payment, membership, member, product, entry, invoice, refund, dispute, "
                "setup intent, and shipment events matching the tables you sync\n"
                "5. Copy the webhook secret into the field below so PostHog can verify deliveries"
            ),
            webhookFields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="signing_secret",
                        label="Signing secret",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="",
                        caption=(
                            "The webhook secret shown in your Whop dashboard. PostHog uses it to verify the "
                            "webhook-signature header on every delivery."
                        ),
                        secret=True,
                    ),
                ],
            ),
        )

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            "401 Client Error: Unauthorized for url: https://api.whop.com": (
                "Whop rejected the API key. Create a new company API key in your Whop dashboard and reconnect."
            ),
            "403 Client Error: Forbidden for url: https://api.whop.com": (
                "Your Whop API key does not have permission to read this resource. Grant the missing read "
                "permission in your Whop dashboard and reconnect."
            ),
            # Whop answers `code=bad_request` when it refuses the list query this source builds for a
            # table. The query is derived from the endpoint catalog and the connected company, so every
            # run reissues the identical request and re-fails. Whop reports a missing permission as 403
            # and an overload as 429/5xx, so a 400 is never a transient blip. Without this the schema
            # keeps its schedule and burns a job on every run while showing the raw HTTP error.
            "400 Client Error: Bad Request for url: https://api.whop.com": (
                "Whop rejected the request for this table, so it can't sync. Turn off syncing for this "
                "table, then re-enable the sync."
            ),
            "is not available on API version": (
                "This table isn't available on the Whop API version this source uses. Turn off syncing for this table."
            ),
        }

    def get_canonical_descriptions(self) -> CanonicalDescriptions:
        from products.warehouse_sources.sources.whop.canonical_descriptions import CANONICAL_DESCRIPTIONS

        return CANONICAL_DESCRIPTIONS

    def get_schemas(
        self,
        config: WhopSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        # Endpoints with no `created_at` sort option page newest-first and stop at the watermark,
        # which re-yields boundary rows that only a merge on `id` can dedupe.
        pinned = self._api_version_date(api_version)
        return build_endpoint_schemas(
            endpoints_for(pinned),
            INCREMENTAL_FIELDS,
            names,
            merge_only=MERGE_ONLY_ENDPOINTS,
            supports_webhooks=webhook_schema_names_for(pinned),
        )

    def validate_credentials(
        self,
        config: WhopSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        if not config.company_id.startswith("biz_"):
            return False, "Whop company IDs start with `biz_`. Copy the ID from your Whop dashboard URL."

        is_valid, status = api_client.validate_credentials(
            config.api_key, config.company_id, self._api_version_date(api_version)
        )
        if is_valid:
            return True, None
        if status == 403:
            # A 403 means the key is genuine but lacks `company:basic:read`. Users may deliberately
            # grant only the permissions for the tables they sync, so don't block source creation.
            if schema_name is None:
                return True, None
            return False, (
                "Your Whop API key does not have permission to read this resource. Grant the missing read "
                "permission in your Whop dashboard and reconnect."
            )
        if status == 404:
            return False, "Whop could not find that company. Check the company ID and try again."
        if status is None or status == 429 or status >= 500:
            return False, "Couldn't reach Whop to check your API key. Try again in a moment."
        return False, (
            "Whop rejected your API key. Create a new company API key in your Whop dashboard, then reconnect."
        )

    @property
    def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:
        from products.warehouse_sources.sources.whop.webhook_template import template

        return template

    @property
    def webhook_resource_map(self) -> dict[str, str]:
        return RESOURCE_TO_EVENT_PREFIX

    def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[WhopResumeConfig]:
        return ResumableSourceManager[WhopResumeConfig](inputs, WhopResumeConfig)

    def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:
        return WebhookSourceManager(inputs, inputs.logger)

    def create_webhook(
        self, config: WhopSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
    ) -> WebhookCreationResult:
        return api_client.create_webhook(
            config.api_key, config.company_id, webhook_url, self._api_version_date(api_version)
        )

    def get_desired_webhook_events(
        self, config: WhopSourceConfig, 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, [])})

    def sync_webhook_events(
        self,
        config: WhopSourceConfig,
        webhook_url: str,
        team_id: int,
        eligible_schema_names: list[str],
        api_version: str | None = None,
    ) -> WebhookSyncResult:
        desired_events = self.get_desired_webhook_events(config, eligible_schema_names) or []
        return api_client.sync_webhook_events(
            config.api_key, config.company_id, webhook_url, desired_events, self._api_version_date(api_version)
        )

    def get_external_webhook_info(
        self, config: WhopSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
    ) -> ExternalWebhookInfo | None:
        return api_client.get_external_webhook_info(
            config.api_key, config.company_id, webhook_url, self._api_version_date(api_version)
        )

    def delete_webhook(
        self, config: WhopSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
    ) -> WebhookDeletionResult:
        return api_client.delete_webhook(
            config.api_key, config.company_id, webhook_url, self._api_version_date(api_version)
        )

    def source_for_pipeline(
        self,
        config: WhopSourceConfig,
        resumable_source_manager: ResumableSourceManager[WhopResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return api_client.whop_source(
            api_key=config.api_key,
            company_id=config.company_id,
            api_version=self._api_version_date(inputs.api_version),
            endpoint=inputs.schema_name,
            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),
            should_use_incremental_field=inputs.should_use_incremental_field,
            db_incremental_field_last_value=inputs.db_incremental_field_last_value
            if inputs.should_use_incremental_field
            else None,
        )