: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 Whop source (#77110)
Tom Owersa06e1d0e3e5c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 1a11afab7f64..d4d456054dd9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -643,6 +643,7 @@ the row lists both.| watchmode | HTTP | requests + `rest_source.RESTClient` | ✅ || webflow | HTTP | requests | ✅ || weights_and_biases | HTTP (GraphQL) | requests | ✅ |+| whop | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || wikipedia_pageviews | HTTP | requests | ✅ || windmill | HTTP | requests | ✅ || woocommerce | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -1406,7 +1407,6 @@ doesn't conflict with concurrent PRs.- whatsapp_business_management- when_i_work- who_gho-- whop- wikipedia_pageviews- wiz- wompidiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/whop.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/whop.pyindex fb63dcae4eca..23be5a19228e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/whop.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/whop.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass WhopSourceConfig(config.Config):- pass+ api_key: str+ company_id: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/whop/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/canonical_descriptions.pynew file mode 100644index 000000000000..7ded157f619d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/canonical_descriptions.py@@ -0,0 +1,341 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Table and column descriptions transcribed from Whop's stable REST API reference+# (https://docs.whop.com/api-reference). Columns the vendor does not describe are left out and+# fall back to the LLM enrichment path.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "memberships": {+ "description": "A membership represents an active relationship between a user and a product. It tracks the user's access, billing status, and renewal schedule.",+ "docs_url": "https://docs.whop.com/api-reference/memberships/membership",+ "columns": {+ "cancel_at_period_end": "Whether this membership is set to cancel at the end of the current billing cycle. Only applies to memberships with a recurring plan.",+ "cancel_option": "The category selected for why the member canceled (e.g. too_expensive, switching, missing_features).",+ "cancelation_status": "Whether the customer is canceling, left, or was won back. Null if the membership has no cancellation reason or its cancellation state is indeterminate.",+ "canceled_at": "The time the customer initiated cancellation of this membership. As a Unix timestamp. Null if the membership has not been canceled.",+ "cancellation_reason": "Free-text explanation provided by the customer when canceling. Null if the customer did not provide a reason.",+ "checkout_configuration_id": "The ID of the checkout session/configuration that produced this membership, if any. Use this to map memberships back to the checkout configuration that created them.",+ "company": "The company this membership belongs to.",+ "created_at": "The datetime the membership was created.",+ "currency": "The three-letter ISO currency code for this membership's billing. Null if the membership is free.",+ "formatted_renewal_price": "The recurring renewal price for this membership, formatted with currency symbol and billing interval. Null if the membership is not recurring.",+ "id": "The unique identifier for the membership.",+ "initial_price_paid": "The amount the customer paid when first purchasing this membership, formatted with currency symbol.",+ "joined_at": "The time the user first joined the company associated with this membership. As a Unix timestamp. Null if the member record does not exist.",+ "license_key": "The software license key associated with this membership. Only present if the product includes a Whop Software Licensing experience. Null otherwise.",+ "manage_url": "The URL where the customer can view and manage this membership, including cancellation and plan changes. Null if no member record exists.",+ "member": "The member record linking the user to the company for this membership. Null if the member record has not been created yet.",+ "metadata": "Custom key-value pairs for the membership (commonly used for software licensing, e.g., HWID). Max 50 keys, 100 chars per key, 500 chars per string value.",+ "payment_collection_paused": "Whether recurring payment collection for this membership is temporarily paused by the company.",+ "plan": "The plan the customer purchased to create this membership.",+ "product": "The product this membership grants access to.",+ "promo_code": "The promotional code currently applied to this membership's billing. Null if no promo code is active.",+ "renewal_period_end": "The end of the current billing period for this recurring membership. As a Unix timestamp. Null if the membership is not recurring.",+ "renewal_period_start": "The start of the current billing period for this recurring membership. As a Unix timestamp. Null if the membership is not recurring.",+ "status": "The status of a membership",+ "updated_at": "The datetime the membership was last updated.",+ "user": "The user who owns this membership. Null if the user account has been deleted.",+ },+ },+ "payments": {+ "description": "A payment represents a completed or attempted charge. Payments track the amount, status, currency, and payment method used.",+ "docs_url": "https://docs.whop.com/api-reference/payments/payment",+ "columns": {+ "amount_after_fees": "How much the payment is for after fees",+ "application_fee": "The application fee charged on this payment.",+ "auto_refunded": "Whether this payment was auto refunded or not",+ "billing_address": "The address of the user who made the payment.",+ "billing_reason": "The machine-readable reason this charge was created, such as initial subscription purchase, renewal cycle, or one-time payment.",+ "card_brand": "Card network reported by the processor (e.g., 'visa', 'mastercard', 'amex'). Present only when the payment method type is 'card'.",+ "card_last4": "The last four digits of the card used to make this payment. Null if the payment was not made with a card.",+ "checkout_configuration_id": "The ID of the checkout session/configuration that produced this payment, if any. Use this to map payments back to the checkout configuration that created them.",+ "company": "The company for the payment.",+ "created_at": "The datetime the payment was created.",+ "currency": "The available currencies on the platform",+ "customer_phone": "Phone number the customer provided at checkout, or their verified phone number when your checkout requires phone verification. `null` when no phone number was collected.",+ "dispute_alerted_at": "When an alert came in that this transaction will be disputed",+ "failure_message": "If the payment failed, the reason for the failure.",+ "id": "The unique identifier for the payment.",+ "last_payment_attempt": "The time of the last payment attempt.",+ "member": "The member attached to this payment.",+ "membership": "The membership attached to this payment.",+ "metadata": "The custom metadata stored on this payment. This will be copied over to the checkout configuration for which this payment was made",+ "next_payment_attempt": "The time of the next schedule payment retry.",+ "paid_at": "The time at which this payment was successfully collected. Null if the payment has not yet succeeded. As a Unix timestamp.",+ "payment_method": "The tokenized payment method reference used for this payment. Null if no token was used.",+ "payment_method_type": "The type of payment instrument used for this payment (e.g., card, Cash App, iDEAL, Klarna, crypto). Null when the processor does not supply a type.",+ "payments_failed": "The number of failed payment attempts for the payment.",+ "plan": "The plan attached to this payment.",+ "product": "The product this payment was made for",+ "promo_code": "The promo code used for this payment.",+ "refundable": "True only for payments that are `paid`, have not been fully refunded, and were processed by a payment processor that allows refunds.",+ "refunded_amount": "The payment refund amount(if applicable).",+ "refunded_at": "When the payment was refunded (if applicable).",+ "retryable": "True when the payment status is `open` and its membership is in one of the retry-eligible states (`active`, `trialing`, `completed`, or `past_due`), or when it is a failed initial billing-engine payment on a `drafted` membership with an unlimited-stock plan; otherwise false. Used to decide if Whop can attempt the charge again.",+ "settlement_currency": "The available currencies on the platform",+ "shipping_address": "The shipping address provided by the customer for physical goods. Null if no shipping address was collected.",+ "status": "The current lifecycle state of this payment (e.g., 'draft', 'open', 'paid', 'void').",+ "substatus": "The friendly status of a payment. This is a derived status that provides a human-readable summary of the payment state, combining the underlying status and substatus fields.",+ "subtotal": "The subtotal to show to the creator (excluding buyer fees).",+ "tax_amount": "The calculated amount of the sales/VAT tax (if applicable).",+ "tax_behavior": "The type of tax inclusivity applied to the payment, for determining whether the tax is included in the final price, or paid on top.",+ "total": "The total to show to the creator (excluding buyer fees).",+ "updated_at": "The datetime the payment was last updated.",+ "usd_total": "The total in USD to show to the creator (excluding buyer fees).",+ "user": "The user that made this payment.",+ "voidable": "True when the payment is tied to a membership in `past_due`, the payment status is `open`, and the processor allows voiding payments; otherwise false.",+ },+ },+ "members": {+ "description": "A member represents a user's relationship with a company on Whop, including their access level, status, and spending history.",+ "docs_url": "https://docs.whop.com/api-reference/members/member",+ "columns": {+ "access_level": "The access level a given user (or company) has to a product or company.",+ "company_token_balance": "The member's token balance for this company. Computed live from the ledger, not from a cache.",+ "created_at": "The datetime the company member was created.",+ "id": "The unique identifier for the company member.",+ "joined_at": "When the member joined the company",+ "most_recent_action": "The most recent action the member has taken.",+ "most_recent_action_at": "The time for the most recent action, if applicable.",+ "phone": "The phone number for the member, if available.",+ "status": "The different statuses a Member can have.",+ "updated_at": "The datetime the company member was last updated.",+ "usd_total_spent": "How much money this customer has spent on the company's products and plans",+ "user": "The user for this member, if any.",+ },+ },+ "products": {+ "description": "A product is a digital good or service sold on Whop. Products contain plans for pricing and experiences for content delivery.",+ "docs_url": "https://docs.whop.com/api-reference/products/product",+ "columns": {+ "created_at": "The datetime the product was created.",+ "external_identifier": "External identifier for the product. Providing it on a product creation endpoint updates the existing product with this identifier instead of creating a new one.",+ "gallery_images": "The gallery images for this product, ordered by position.",+ "headline": "A short marketing headline displayed prominently on the product's product page.",+ "id": "The unique identifier for the product.",+ "member_count": "Active memberships for this product. Returns `0` if the account has disabled public member counts.",+ "metadata": "Custom key-value pairs stored on the product and included in payment and membership webhook payloads. Max 50 keys, 100 characters per key, 500 characters per string value.",+ "published_reviews_count": "The total number of published customer reviews for this product's company.",+ "route": "URL slug in the product's public link, e.g. `pickaxe-analytics` in whop.com/company/pickaxe-analytics.",+ "title": "The display name of the product shown to customers on the product page and in search results.",+ "updated_at": "The datetime the product was last updated.",+ "verified": "Whether this company has been verified by Whop's trust and safety team.",+ "visibility": "Visibility of a resource",+ },+ },+ "entries": {+ "description": "An entry represents a user's signup for a waitlisted plan.",+ "docs_url": "https://docs.whop.com/api-reference/entries/entry",+ "columns": {+ "created_at": "The datetime the entry was created.",+ "id": "The unique identifier for the entry.",+ "plan": "The waitlisted plan that this entry is a signup for.",+ "product": "The product associated with this entry's waitlisted plan. Null if the plan is not tied to a product.",+ "status": "The status of an entry to a waitlist.",+ "user": "The user who submitted this waitlist entry.",+ },+ },+ "invoices": {+ "description": "An invoice represents an itemized bill sent by a company to a customer for a specific product and plan, tracking the amount owed, due date, and payment status.",+ "docs_url": "https://docs.whop.com/api-reference/invoices/invoice",+ "columns": {+ "created_at": "The datetime the invoice was created.",+ "current_plan": "The plan that this invoice charges for.",+ "due_date": "The deadline by which payment is expected. Null if the invoice is collected automatically.",+ "email_address": "The email address of the customer this invoice is addressed to. Null if no email is on file.",+ "fetch_invoice_token": "A signed token that allows fetching invoice data publicly without authentication.",+ "id": "The unique identifier for the invoice.",+ "line_items": "Optional line items that break down the invoice total into individual charges.",+ "number": "The sequential invoice number for display purposes.",+ "status": "The different statuses an invoice can be in",+ "user": "The user this invoice is addressed to. Null if the user account has been removed.",+ },+ },+ "refunds": {+ "description": "A refund represents a full or partial reversal of a payment, including the amount, status, and payment provider.",+ "docs_url": "https://docs.whop.com/api-reference/refunds/refund",+ "columns": {+ "amount": "The refunded amount as a decimal in the specified currency, such as 10.43 for $10.43 USD.",+ "created_at": "The datetime the refund was created.",+ "currency": "The available currencies on the platform",+ "id": "The unique identifier for the refund.",+ "payment": "The original payment that this refund was issued against. Null if the payment is no longer available.",+ "provider": "The different payment providers.",+ "provider_created_at": "The timestamp when the refund was created in the payment provider's system. Null if not available from the provider.",+ "reference_status": "The availability status of the refund tracking reference from the payment processor. Null if no reference was provided.",+ "reference_type": "The type of tracking reference provided by the payment processor, such as an acquirer reference number. Null if no reference was provided.",+ "reference_value": "The tracking reference value from the payment processor, used to trace the refund through banking networks. Null if no reference was provided.",+ "status": "The different statuses for a Refund object",+ },+ },+ "disputes": {+ "description": "A dispute is a chargeback or payment challenge filed against a company, including evidence and response status.",+ "docs_url": "https://docs.whop.com/api-reference/disputes/dispute",+ "columns": {+ "amount": "The disputed amount in the specified currency, formatted as a decimal.",+ "company": "The company that the dispute was filed against.",+ "created_at": "The datetime the dispute was created.",+ "currency": "The available currencies on the platform",+ "editable": "Whether the dispute evidence can still be edited and submitted.",+ "id": "The unique identifier for the dispute.",+ "needs_response_by": "The deadline by which dispute evidence must be submitted. Null if no response deadline is set.",+ "payment": "The original payment that was disputed.",+ "plan": "The plan associated with the disputed payment. Null if the dispute is not linked to a specific plan.",+ "product": "The product associated with the disputed payment. Null if the dispute is not linked to a specific product.",+ "reason": "A human-readable reason for the dispute.",+ "reason_code": "The card network reason code for the dispute. Null when the payment processor did not provide one.",+ "status": "The possible statuses of a dispute",+ "visa_rdr": "Whether the dispute was automatically resolved through Visa Rapid Dispute Resolution (RDR).",+ },+ },+ "dispute_alerts": {+ "description": "A dispute alert represents an early warning notification from a payment processor about a potential dispute or chargeback.",+ "docs_url": "https://docs.whop.com/api-reference/dispute-alerts/dispute-alert",+ "columns": {+ "alert_type": "The type of dispute alert.",+ "amount": "The alerted amount in the specified currency.",+ "charge_for_alert": "Whether this alert incurs a charge.",+ "created_at": "The time the dispute alert was created.",+ "currency": "The available currencies on the platform",+ "dispute": "The dispute associated with the dispute alert.",+ "id": "The unique identifier of the dispute alert.",+ "payment": "The payment associated with the dispute alert.",+ "transaction_date": "The date of the original transaction.",+ },+ },+ "setup_intents": {+ "description": "A setup intent allows a user to save a payment method for future use without making an immediate purchase.",+ "docs_url": "https://docs.whop.com/api-reference/setup-intents/setup-intent",+ "columns": {+ "checkout_configuration": "The checkout session configuration associated with this setup intent. Null if no checkout session was used.",+ "company": "The company that initiated this setup intent. Null if the company has been deleted.",+ "created_at": "The datetime the setup intent was created.",+ "error_message": "A human-readable error message explaining why the setup intent failed. Null if no error occurred.",+ "id": "The unique identifier for the setup intent.",+ "member": "The company member associated with this setup intent. Null if the user is not a member.",+ "metadata": "Custom key-value pairs attached to this setup intent. Null if no metadata was provided.",+ "payment_method": "The saved payment method created by this setup intent. Null if the setup has not completed successfully.",+ "status": "The status of the setup intent.",+ },+ },+ "promo_codes": {+ "description": "A promo code applies a discount to a plan during checkout. Promo codes can be percentage-based or fixed-amount, and can have usage limits and expiration dates.",+ "docs_url": "https://docs.whop.com/api-reference/promo-codes/promo-code",+ "columns": {+ "amount_off": "The discount amount. Interpretation depends on promo_type: if 'percentage', this is the percentage (e.g., 20 means 20% off); if 'flat_amount', this is dollars off (e.g., 10.00 means $10.00 off).",+ "churned_users_only": "Restricts promo use to only users who have churned from the company before.",+ "code": "The specific code used to apply the promo at checkout.",+ "created_at": "The datetime the promo code was created.",+ "currency": "The available currencies on the platform",+ "duration": "The duration of the promo.",+ "existing_memberships_only": "Restricts promo use to only be applied to already purchased memberships.",+ "expires_at": "The date/time of when the promo expires.",+ "id": "The unique identifier for the promo code.",+ "new_users_only": "Restricts promo use to only users who have never purchased from the company before.",+ "one_per_customer": "Restricts promo use to only be applied once per customer.",+ "product": "The product this promo code applies to",+ "promo_duration_months": "The number of months the promo is applied for.",+ "promo_type": "The type of promo code used to discount a plan",+ "status": "Statuses for promo codes",+ "stock": "The quantity limit on the number of uses.",+ "unlimited_stock": "Whether or not the promo code has unlimited stock.",+ "uses": "The amount of times the promo codes has been used.",+ },+ },+ "leads": {+ "description": "A prospective customer who has expressed interest in a company or product but has not yet purchased.",+ "docs_url": "https://docs.whop.com/api-reference/leads/lead",+ "columns": {+ "created_at": "The datetime the lead was created.",+ "id": "The unique identifier for the lead.",+ "member": "The company member record if this lead has converted into a paying customer. Null if the lead has not converted.",+ "metadata": "Custom key-value pairs attached to this lead. Null if no metadata was provided.",+ "product": "The product the lead expressed interest in. Null if the lead is not associated with a specific product.",+ "referrer": "The URL of the page that referred this lead to the company. Null if no referrer was captured.",+ "updated_at": "The datetime the lead was last updated.",+ "user": "The user account associated with this lead.",+ },+ },+ "experiences": {+ "description": "An experience is a feature or content module within a product, such as a chat, course, or custom app.",+ "docs_url": "https://docs.whop.com/api-reference/experiences/experience",+ "columns": {+ "app": "The app that powers this experience, defining its interface and behavior.",+ "company": "The company that owns this experience.",+ "created_at": "The datetime the experience was created.",+ "id": "The unique identifier for the experience.",+ "image": "The custom logo image for this experience. Null if no custom logo has been uploaded.",+ "is_public": "Whether this experience is publicly visible to all users, including those without a membership.",+ "name": "The display name of this experience shown to users in the product navigation. Maximum 255 characters.",+ "order": "The sort position of this experience within its section. Lower values appear first. Null if no position has been set.",+ },+ },+ "checkout_configurations": {+ "description": "A checkout configuration is a reusable configuration for a checkout, including the plan, affiliate, and custom metadata. Payments and memberships created from a checkout session inherit its metadata.",+ "docs_url": "https://docs.whop.com/api-reference/checkout-configurations/checkout-configuration",+ "columns": {+ "affiliate_code": "The affiliate code to use for the checkout configuration",+ "company_id": "The ID of the company to use for the checkout configuration",+ "currency": "The currency to use for the configuration when in 'setup' mode. This is used to target which currency specific payment methods are available. If not provided, it will default to 'usd' when in setup mode.",+ "id": "The unique identifier for the checkout session.",+ "metadata": "The metadata to use for the checkout configuration",+ "mode": "The different modes a checkout can be set to.",+ "payment_method_configuration": "The explicit payment method configuration for the session, if any. This currently only works in 'setup' mode. Use the plan's payment_method_configuration for payment method.",+ "plan": "The plan to use for the checkout configuration",+ "purchase_url": "A URL you can send to customers to complete a checkout. It looks like `/checkout/plan_xxxx?session={id}`",+ "redirect_url": "The URL to redirect the user to after the checkout configuration is created",+ },+ },+ "affiliates": {+ "description": "An affiliate tracks a user's referral performance and commission earnings for a company, including retention rates, revenue metrics, and payout configurations.",+ "docs_url": "https://docs.whop.com/api-reference/affiliates/affiliate",+ "columns": {+ "active_members_count": "The total active members of the affiliate",+ "company": "The company attached to this affiliate",+ "created_at": "The datetime the affiliate was created.",+ "customer_retention_rate": "The percentage of referred customers who are still active members",+ "customer_retention_rate_ninety_days": "The percentage of referred customers who remained active over the last 90 days",+ "id": "The unique identifier for the affiliate.",+ "monthly_recurring_revenue_usd": "The monthly recurring revenue generated by this affiliate's referrals, formatted as a USD currency string",+ "status": "The status of the affiliate",+ "total_overrides_count": "The total count of all overrides for this affiliate",+ "total_referral_earnings_usd": "The total commission earnings paid to this affiliate, formatted as a USD currency string",+ "total_referrals_count": "The total referrals of the affiliate",+ "total_revenue_usd": "The total revenue generated from this affiliate's referrals, formatted as a USD currency string",+ "updated_at": "The datetime the affiliate was last updated.",+ "user": "The user attached to this affiliate",+ },+ },+ "shipments": {+ "description": "A physical shipment associated with a payment, including carrier details and tracking information.",+ "docs_url": "https://docs.whop.com/api-reference/shipments/shipment",+ "columns": {+ "created_at": "The datetime the shipment was created.",+ "delivery_estimate": "The estimated delivery date for this shipment. Null if the carrier has not provided an estimate.",+ "id": "The unique identifier for the shipment.",+ "payment": "The payment associated with this shipment. Null if the payment has been deleted or is inaccessible.",+ "service": "The shipping service level used for this shipment. Null if the carrier does not specify a service tier.",+ "status": "The status of a shipment",+ "substatus": "A more granular status providing additional detail about the shipment's current state. Null if no substatus applies.",+ "tracking_code": "The carrier-assigned tracking number used to look up shipment progress.",+ "updated_at": "The datetime the shipment was last updated.",+ },+ },+ "company_token_transactions": {+ "description": "A token transaction records a credit or debit to a member's token balance within a company, including transfers between members.",+ "docs_url": "https://docs.whop.com/api-reference/company-token-transactions/company-token-transaction",+ "columns": {+ "amount": "The token amount for this transaction. Always a positive value regardless of transaction type.",+ "company": "The company whose token balance this transaction affects.",+ "created_at": "The datetime the company token transaction was created.",+ "description": "Free-text description explaining the reason for this token transaction. Null if no description was provided.",+ "id": "The unique identifier for the company token transaction.",+ "idempotency_key": "A unique key used to prevent duplicate transactions when retrying API requests. Null if no idempotency key was provided.",+ "linked_transaction_id": "The ID of the corresponding transaction on the other side of a transfer. Null if this is not a transfer transaction.",+ "member": "The member whose token balance was affected by this transaction.",+ "transaction_type": "The type of token transaction",+ "user": "The user whose token balance was affected by this transaction.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/whop/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/settings.pynew file mode 100644index 000000000000..ba33fcb30b76--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/settings.py@@ -0,0 +1,202 @@+from dataclasses import dataclass++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode+from products.warehouse_sources.backend.types import IncrementalField++BASE_URL = "https://api.whop.com/api/v1"++WHOP_API_KEYS_URL = "https://whop.com/dashboard/developer"++# Whop pages with Relay-style cursors (`first` + `after`). The docs publish no maximum page size,+# so stay on a conservative 100.+PAGE_SIZE = 100+++@dataclass+class WhopEndpointConfig:+ path: str+ # Whether `company_id` is a required query param. The rest accept it as an optional narrowing+ # filter, which we always send so a key reaching several companies stays pinned to the one the+ # user connected.+ company_id_required: bool = False+ # Set when the endpoint's `order` enum contains `created_at`. Only then can we force a known+ # ascending page order and let the pipeline checkpoint the watermark after every batch.+ supports_created_at_order: bool = False+ # Set when the endpoint exposes a `direction` param. Endpoints with `direction` but no `order`+ # sort on an undocumented column, so we pin `direction=desc` and defer the watermark.+ supports_direction: bool = False+ # Set when the endpoint accepts the server-side `created_after` ISO 8601 filter *and* the+ # resource carries a `created_at` column for the pipeline to track.+ supports_created_after: bool = False+ partition_key: str | None = "created_at"+++WHOP_ENDPOINTS: dict[str, WhopEndpointConfig] = {+ "memberships": WhopEndpointConfig(+ path="/memberships",+ supports_created_at_order=True,+ supports_direction=True,+ supports_created_after=True,+ ),+ "payments": WhopEndpointConfig(+ path="/payments",+ supports_created_at_order=True,+ supports_direction=True,+ supports_created_after=True,+ ),+ "members": WhopEndpointConfig(+ path="/members",+ supports_created_at_order=True,+ supports_direction=True,+ supports_created_after=True,+ ),+ "products": WhopEndpointConfig(+ path="/products",+ company_id_required=True,+ supports_created_at_order=True,+ supports_direction=True,+ supports_created_after=True,+ ),+ "entries": WhopEndpointConfig(+ path="/entries",+ company_id_required=True,+ supports_created_at_order=True,+ supports_direction=True,+ supports_created_after=True,+ ),+ "invoices": WhopEndpointConfig(+ path="/invoices",+ supports_created_at_order=True,+ supports_direction=True,+ supports_created_after=True,+ ),+ "refunds": WhopEndpointConfig(+ path="/refunds",+ supports_direction=True,+ supports_created_after=True,+ ),+ "disputes": WhopEndpointConfig(+ path="/disputes",+ company_id_required=True,+ supports_direction=True,+ supports_created_after=True,+ ),+ "dispute_alerts": WhopEndpointConfig(+ path="/dispute_alerts",+ company_id_required=True,+ supports_direction=True,+ supports_created_after=True,+ ),+ "setup_intents": WhopEndpointConfig(+ path="/setup_intents",+ company_id_required=True,+ supports_direction=True,+ supports_created_after=True,+ ),+ "promo_codes": WhopEndpointConfig(+ path="/promo_codes",+ company_id_required=True,+ supports_created_after=True,+ ),+ "leads": WhopEndpointConfig(+ path="/leads",+ company_id_required=True,+ supports_created_after=True,+ ),+ "experiences": WhopEndpointConfig(+ path="/experiences",+ company_id_required=True,+ supports_created_after=True,+ ),+ # `created_after` is accepted here but the resource carries no `created_at` column, so there is+ # nothing to track incrementally or partition on.+ "checkout_configurations": WhopEndpointConfig(+ path="/checkout_configurations",+ company_id_required=True,+ supports_direction=True,+ partition_key=None,+ ),+ "affiliates": WhopEndpointConfig(path="/affiliates", company_id_required=True, supports_direction=True),+ "shipments": WhopEndpointConfig(path="/shipments"),+ "company_token_transactions": WhopEndpointConfig(path="/company_token_transactions", company_id_required=True),+}++ENDPOINTS = tuple(WHOP_ENDPOINTS.keys())++# Every Whop resource we sync exposes `created_at` as an immutable ISO 8601 datetime, and+# `created_after` is the only server-side timestamp filter offered across the catalog. `/payments`+# also takes `updated_after`, but its `order` enum has no `updated_at` column, so an updated_at+# cursor could never be paired with a known page order. Incremental sync therefore tracks+# `created_at` everywhere, which does not re-surface in-place updates - webhooks cover those for the+# resources Whop emits events for.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: [incremental_field("created_at")] for name, config in WHOP_ENDPOINTS.items() if config.supports_created_after+}++INCREMENTAL_ENDPOINTS = tuple(INCREMENTAL_FIELDS.keys())++# Endpoints that can only ship a merge, never an append: where the page order is undocumented we+# page newest-first and stop at the watermark, which re-yields boundary rows only a merge on `id`+# dedupes.+MERGE_ONLY_ENDPOINTS = tuple(+ name for name in INCREMENTAL_ENDPOINTS if not WHOP_ENDPOINTS[name].supports_created_at_order+)+++def sort_mode_for(endpoint: str) -> SortMode:+ """The order rows actually arrive in for `endpoint`.++ Only endpoints with `created_at` in their `order` enum can be forced ascending. For the rest+ Whop documents no sort column, so we declare `desc`: the pipeline then finalizes the incremental+ watermark once, after a fully successful sync, instead of checkpointing per batch against an+ order we cannot verify.+ """+ return "asc" if WHOP_ENDPOINTS[endpoint].supports_created_at_order else "desc"+++# Webhook events per schema, taken from the `WebhookEvent` enum in Whop's stable OpenAPI spec. Each+# delivery carries the full resource under `data` in the same shape the list endpoint returns, so+# webhook rows merge onto the tables the pull path fills.+SCHEMA_TO_WEBHOOK_EVENTS: dict[str, list[str]] = {+ "payments": ["payment.created", "payment.succeeded", "payment.failed", "payment.pending"],+ "memberships": [+ "membership.activated",+ "membership.deactivated",+ "membership.trial_ending_soon",+ "membership.cancel_at_period_end_changed",+ ],+ "members": ["member.created"],+ "products": [+ "product.created",+ "product.updated",+ "product.deleted",+ "product.published",+ "product.unpublished",+ ],+ "entries": ["entry.created", "entry.approved", "entry.denied", "entry.deleted"],+ "invoices": [+ "invoice.created",+ "invoice.paid",+ "invoice.past_due",+ "invoice.voided",+ "invoice.marked_uncollectible",+ ],+ "refunds": ["refund.created", "refund.updated"],+ "disputes": ["dispute.created", "dispute.updated"],+ "dispute_alerts": ["dispute_alert.created"],+ "setup_intents": ["setup_intent.requires_action", "setup_intent.succeeded", "setup_intent.canceled"],+ "shipments": ["shipment.created", "shipment.updated"],+}++WEBHOOK_SCHEMA_NAMES = tuple(SCHEMA_TO_WEBHOOK_EVENTS.keys())++ALL_WEBHOOK_EVENTS = sorted({event for events in SCHEMA_TO_WEBHOOK_EVENTS.values() for event in events})++# Schema name -> the resource prefix shared by its event types. Whop names events+# `<resource>.<action>` (e.g. `payment.succeeded`), so the hog template splits on the first dot and+# looks the prefix up in `schema_mapping`. `dispute` and `dispute_alert` stay distinct because the+# split keeps the whole prefix.+RESOURCE_TO_EVENT_PREFIX: dict[str, str] = {+ name: events[0].split(".", 1)[0] for name, events in SCHEMA_TO_WEBHOOK_EVENTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/whop/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/source.pyindex 6ec19f7d8cb4..47d2dae0993f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/whop/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/source.py@@ -1,19 +1,63 @@-from typing import cast+from typing import TYPE_CHECKING, Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ ExternalWebhookInfo,+ FieldType,+ ResumableSource,+ WebhookCreationResult,+ WebhookDeletionResult,+ WebhookSource,+ WebhookSyncResult,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+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,+ build_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.whop import WhopSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.whop import whop as api_client+from products.warehouse_sources.backend.temporal.data_imports.sources.whop.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ MERGE_ONLY_ENDPOINTS,+ RESOURCE_TO_EVENT_PREFIX,+ SCHEMA_TO_WEBHOOK_EVENTS,+ WEBHOOK_SCHEMA_NAMES,+ WHOP_API_KEYS_URL,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.whop.whop import WhopResumeConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType+if TYPE_CHECKING:+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC+@SourceRegistry.register-class WhopSource(SimpleSource[WhopSourceConfig]):+class WhopSource(+ ResumableSource[WhopSourceConfig, WhopResumeConfig],+ WebhookSource[WhopSourceConfig],+):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # Whop's dated `Api-Version-Date` header pins the Experimental API. The stable `/api/v1`+ # endpoints this source calls are served on the unversioned contract when the header is omitted,+ # so no version is sent and none is declared.+ api_docs_url = "https://docs.whop.com/developer/api/versioning"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.WHOP@@ -24,7 +68,195 @@ class WhopSource(SimpleSource[WhopSourceConfig]):name=SchemaExternalDataSourceType.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",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ 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` and "+ "`invoice:basic: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.ALPHA,+ 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 to **v1**\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."+ ),+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.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.+ return build_endpoint_schemas(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names,+ merge_only=MERGE_ONLY_ENDPOINTS,+ supports_webhooks=WEBHOOK_SCHEMA_NAMES,+ )++ 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)+ if is_valid:+ return True, None+ # 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 on it.+ if status == 403 and schema_name is None:+ return True, None+ if status == 404:+ return False, "Whop could not find that company. Check the company ID and try again."+ return False, "Invalid Whop API key or company ID."++ @property+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:+ from products.warehouse_sources.backend.temporal.data_imports.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)++ 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)++ 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)++ 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)++ 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,+ 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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/whop/tests/test_whop.py b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/tests/test_whop.pynew file mode 100644index 000000000000..dd032a638209--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/tests/test_whop.py@@ -0,0 +1,518 @@+import json+from datetime import UTC, datetime+from typing import Any++import pytest+from unittest import mock++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.whop.settings import (+ ALL_WEBHOOK_EVENTS,+ BASE_URL,+ ENDPOINTS,+ PAGE_SIZE,+ WHOP_ENDPOINTS,+ sort_mode_for,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.whop.whop import (+ WhopCursorPaginator,+ WhopResumeConfig,+ _list_params,+ _parse_datetime,+ _to_iso8601,+ create_webhook,+ delete_webhook,+ get_external_webhook_info,+ sync_webhook_events,+ validate_credentials,+ webhook_table_transformer,+ whop_source,+)++# The source builds its own capture-disabled tracked session for the sync client, the credential+# probe, and the webhook management helpers.+WHOP_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.whop.whop.make_tracked_session"+REST_RESOURCE_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.whop.whop.rest_api_resource"++COMPANY_ID = "biz_test"+++def _page(items: list[dict[str, Any]], end_cursor: str | None, has_next_page: bool) -> Response:+ body = {+ "data": items,+ "page_info": {+ "end_cursor": end_cursor,+ "start_cursor": None,+ "has_next_page": has_next_page,+ "has_previous_page": False,+ },+ "total_count": len(items),+ }+ response = Response()+ response.status_code = 200+ response._content = json.dumps(body).encode()+ return response+++def _make_manager(resume_state: WhopResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session, snapshotting each request at prepare time (params mutate across pages)."""+ session.headers = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append({"url": request.url, "params": dict(request.params or {})})+ prepared = mock.MagicMock()+ prepared.url = request.url+ return prepared++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any):+ return whop_source(+ "test-api-key",+ COMPANY_ID,+ endpoint,+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ **kwargs,+ )+++def _rows(source_response) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++class TestParseDatetime:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (None, None),+ (True, None),+ ("2024-05-01T10:00:00.401Z", datetime(2024, 5, 1, 10, 0, 0, 401000, tzinfo=UTC)),+ ("2024-05-01T10:00:00+02:00", datetime(2024, 5, 1, 8, tzinfo=UTC)),+ (datetime(2024, 5, 1, 10), datetime(2024, 5, 1, 10, tzinfo=UTC)),+ (1714557600, datetime(2024, 5, 1, 10, tzinfo=UTC)),+ ("not-a-date", None),+ ],+ )+ def test_values(self, value, expected):+ assert _parse_datetime(value) == expected++ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2024, 5, 1, 10, tzinfo=UTC), "2024-05-01T10:00:00.000Z"),+ (datetime(2024, 5, 1, 10, 0, 0, 401000, tzinfo=UTC), "2024-05-01T10:00:00.401Z"),+ ],+ )+ def test_iso8601_uses_z_suffix(self, value, expected):+ # Whop's timestamp filters document a `Z`-suffixed ISO 8601 value; `+00:00` is not accepted+ # by every vendor and there is no reason to risk it.+ assert _to_iso8601(value) == expected+++class TestListParams:+ def test_ordered_endpoint_forces_ascending_created_at(self):+ # Only a forced sort column makes the arrival order knowable, which is what lets these+ # endpoints declare sort_mode="asc" and checkpoint the watermark per batch.+ params = _list_params("payments", COMPANY_ID, None)+ assert params["order"] == "created_at"+ assert params["direction"] == "asc"++ def test_direction_only_endpoint_pins_descending_and_sends_no_order(self):+ # `/refunds` has no `order` enum, so sending one would 400; the sort column is undocumented+ # so the endpoint is declared desc and the watermark deferred.+ params = _list_params("refunds", COMPANY_ID, None)+ assert params["direction"] == "desc"+ assert "order" not in params++ def test_endpoint_without_sort_params_sends_neither(self):+ params = _list_params("promo_codes", COMPANY_ID, None)+ assert "order" not in params+ assert "direction" not in params++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_company_and_page_size_always_sent(self, endpoint):+ params = _list_params(endpoint, COMPANY_ID, None)+ assert params["company_id"] == COMPANY_ID+ assert params["first"] == PAGE_SIZE++ def test_watermark_becomes_server_side_created_after(self):+ params = _list_params("payments", COMPANY_ID, datetime(2024, 5, 1, 10, tzinfo=UTC))+ assert params["created_after"] == "2024-05-01T10:00:00.000Z"++ def test_full_refresh_sends_no_created_after(self):+ assert "created_after" not in _list_params("payments", COMPANY_ID, None)++ @pytest.mark.parametrize(+ "endpoint",+ [name for name, config in WHOP_ENDPOINTS.items() if not config.supports_created_after],+ )+ def test_endpoints_without_the_filter_never_send_created_after(self, endpoint):+ # These resources carry no trackable `created_at`; sending the filter would silently drop+ # rows the pipeline would then never backfill.+ assert "created_after" not in _list_params(endpoint, COMPANY_ID, datetime(2024, 5, 1, tzinfo=UTC))+++class TestPagination:+ @mock.patch(WHOP_SESSION_PATCH)+ def test_follows_end_cursor_and_saves_resume_state(self, MockSession):+ session = MockSession.return_value+ requests_seen = _wire(+ session,+ [+ _page([{"id": "pay_1"}], end_cursor="cursor-1", has_next_page=True),+ _page([{"id": "pay_2"}], end_cursor="cursor-2", has_next_page=False),+ ],+ )++ manager = _make_manager()+ rows = _rows(_source("payments", manager))++ assert [row["id"] for row in rows] == ["pay_1", "pay_2"]+ assert "after" not in requests_seen[0]["params"]+ assert requests_seen[1]["params"]["after"] == "cursor-1"+ # State is persisted only while a next page remains, after the page was yielded.+ manager.save_state.assert_called_once_with(WhopResumeConfig(cursor="cursor-1"))++ @mock.patch(WHOP_SESSION_PATCH)+ def test_stops_when_has_next_page_is_false_despite_a_populated_cursor(self, MockSession):+ # Relay keeps `end_cursor` set on the last page, so a cursor-only stop condition would+ # re-request the final page forever.+ session = MockSession.return_value+ requests_seen = _wire(session, [_page([{"id": "pay_1"}], end_cursor="cursor-1", has_next_page=False)])++ manager = _make_manager()+ rows = _rows(_source("payments", manager))++ assert len(requests_seen) == 1+ assert [row["id"] for row in rows] == ["pay_1"]+ manager.save_state.assert_not_called()++ @mock.patch(WHOP_SESSION_PATCH)+ def test_resumes_from_saved_cursor(self, MockSession):+ session = MockSession.return_value+ requests_seen = _wire(session, [_page([{"id": "pay_9"}], end_cursor="cursor-9", has_next_page=False)])++ rows = _rows(_source("payments", _make_manager(WhopResumeConfig(cursor="cursor-8"))))++ assert [row["id"] for row in rows] == ["pay_9"]+ assert requests_seen[0]["params"]["after"] == "cursor-8"++ @pytest.mark.parametrize(+ "page_info, expected_has_next",+ [+ ({"end_cursor": "c", "has_next_page": True}, True),+ ({"end_cursor": "c", "has_next_page": False}, False),+ ({"end_cursor": None, "has_next_page": True}, False),+ ({}, False),+ ],+ )+ def test_paginator_termination(self, page_info, expected_has_next):+ response = Response()+ response.status_code = 200+ response._content = json.dumps({"data": [], "page_info": page_info}).encode()++ paginator = WhopCursorPaginator()+ paginator.update_state(response, [])++ assert paginator.has_next_page is expected_has_next++ def test_paginator_stops_on_unparseable_body(self):+ # Nothing to page with, so stopping beats re-requesting the same cursor forever.+ response = Response()+ response.status_code = 200+ response._content = b"not json"++ paginator = WhopCursorPaginator()+ paginator.update_state(response, [])++ assert paginator.has_next_page is False+++class TestSourceResponseMetadata:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ @mock.patch(WHOP_SESSION_PATCH)+ def test_response_metadata_per_endpoint(self, MockSession, endpoint):+ response = _source(endpoint, _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.sort_mode == sort_mode_for(endpoint)++ partition_key = WHOP_ENDPOINTS[endpoint].partition_key+ if partition_key is None:+ # Partitioning on a column the resource does not return would key every row to null.+ assert response.partition_mode is None+ assert response.partition_keys is None+ else:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [partition_key]++ @pytest.mark.parametrize(+ "should_use_incremental_field, expected_disposition",+ [+ (True, {"disposition": "merge", "strategy": "upsert"}),+ (False, "replace"),+ ],+ )+ @mock.patch(REST_RESOURCE_PATCH)+ @mock.patch(WHOP_SESSION_PATCH)+ def test_write_disposition_follows_incremental_mode(+ self, MockSession, mock_rest_api_resource, should_use_incremental_field, expected_disposition+ ):+ _source("payments", _make_manager(), should_use_incremental_field=should_use_incremental_field)++ config = mock_rest_api_resource.call_args.args[0]+ assert config["resources"][0]["write_disposition"] == expected_disposition++ @mock.patch(REST_RESOURCE_PATCH)+ @mock.patch(WHOP_SESSION_PATCH)+ def test_framework_incremental_injection_is_not_used(self, MockSession, mock_rest_api_resource):+ # `created_after` is baked into the request params; letting the framework also inject the+ # watermark would add a second, wrongly-named filter param.+ _source(+ "payments",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-05-01T10:00:00Z",+ )++ assert mock_rest_api_resource.call_args.kwargs["db_incremental_field_last_value"] is None+ params = mock_rest_api_resource.call_args.args[0]["resources"][0]["endpoint"]["params"]+ assert params["created_after"] == "2024-05-01T10:00:00.000Z"+++class TestWebhookTableTransformer:+ def test_hoists_data_and_keeps_latest_delivery_per_id(self):+ table = table_from_py_list(+ [+ {+ "id": "msg_1",+ "type": "payment.pending",+ "timestamp": "2024-05-01T00:00:00Z",+ "data": {"id": "pay_1", "status": "open"},+ },+ {+ "id": "msg_2",+ "type": "payment.succeeded",+ "timestamp": "2024-05-02T00:00:00Z",+ "data": {"id": "pay_1", "status": "paid"},+ },+ {+ "id": "msg_3",+ "type": "payment.succeeded",+ "timestamp": "2024-05-01T00:00:00Z",+ "data": {"id": "pay_2", "status": "paid"},+ },+ ]+ )++ rows = webhook_table_transformer(table).to_pylist()++ assert sorted(rows, key=lambda row: row["id"]) == [+ {"id": "pay_1", "status": "paid"},+ {"id": "pay_2", "status": "paid"},+ ]++ def test_accepts_payloads_serialized_back_to_json_strings(self):+ table = table_from_py_list(+ [{"id": "msg_1", "timestamp": "2024-05-01T00:00:00Z", "data": json.dumps({"id": "pay_1", "total": 10})}]+ )++ assert webhook_table_transformer(table).to_pylist() == [{"id": "pay_1", "total": 10}]++ def test_skips_rows_without_a_resource_id(self):+ table = table_from_py_list(+ [+ {"id": "msg_1", "timestamp": "2024-05-01T00:00:00Z", "data": {"status": "paid"}},+ {"id": "msg_2", "timestamp": "2024-05-01T00:00:00Z", "data": {"id": "pay_1"}},+ ]+ )++ assert webhook_table_transformer(table).to_pylist() == [{"id": "pay_1"}]++ def test_empty_when_deliveries_carry_no_data_column(self):+ table = table_from_py_list([{"id": "msg_1", "type": "payment.succeeded"}])++ assert webhook_table_transformer(table).num_rows == 0+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected",+ [(200, (True, 200)), (401, (False, 401)), (403, (False, 403)), (404, (False, 404)), (500, (False, 500))],+ )+ @mock.patch(WHOP_SESSION_PATCH)+ def test_status_mapping(self, MockSession, status_code, expected):+ MockSession.return_value.get.return_value = mock.MagicMock(status_code=status_code)+ assert validate_credentials("key", COMPANY_ID) == expected++ @mock.patch(WHOP_SESSION_PATCH)+ def test_probes_the_connected_company_with_a_bearer_token(self, MockSession):+ MockSession.return_value.get.return_value = mock.MagicMock(status_code=200)++ validate_credentials("key", COMPANY_ID)++ call = MockSession.return_value.get.call_args+ assert call.args[0] == f"{BASE_URL}/companies/{COMPANY_ID}"+ assert call.kwargs["headers"]["Authorization"] == "Bearer key"++ @mock.patch(WHOP_SESSION_PATCH)+ def test_transport_failure_never_raises(self, MockSession):+ MockSession.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("key", COMPANY_ID) == (False, None)+++def _json_response(status_code: int, body: Any) -> mock.MagicMock:+ response = mock.MagicMock(status_code=status_code)+ response.json.return_value = body+ return response+++class TestCreateWebhook:+ @mock.patch(WHOP_SESSION_PATCH)+ def test_returns_the_generated_signing_secret(self, MockSession):+ session = MockSession.return_value+ session.post.return_value = _json_response(201, {"id": "hook_1", "webhook_secret": "whsec_abc"})++ result = create_webhook("key", COMPANY_ID, "https://ph.example/webhook")++ assert result.success is True+ assert result.extra_inputs == {"signing_secret": "whsec_abc"}+ payload = session.post.call_args.kwargs["json"]+ assert payload["url"] == "https://ph.example/webhook"+ assert payload["resource_id"] == COMPANY_ID+ # Deliveries must use the v1 payload envelope the transformer unwraps.+ assert payload["api_version"] == "v1"+ assert payload["events"] == ALL_WEBHOOK_EVENTS++ @pytest.mark.parametrize("status_code", [401, 403, 422, 500])+ @mock.patch(WHOP_SESSION_PATCH)+ def test_non_success_falls_back_to_manual_setup(self, MockSession, status_code):+ MockSession.return_value.post.return_value = _json_response(status_code, {})++ result = create_webhook("key", COMPANY_ID, "https://ph.example/webhook")++ assert result.success is False+ assert result.error is not None++ @mock.patch(WHOP_SESSION_PATCH)+ def test_missing_secret_is_a_failure(self, MockSession):+ # Without a secret the hog function cannot verify deliveries, so reporting success would+ # silently leave the webhook rejecting every payload.+ MockSession.return_value.post.return_value = _json_response(201, {"id": "hook_1"})++ result = create_webhook("key", COMPANY_ID, "https://ph.example/webhook")++ assert result.success is False++ @mock.patch(WHOP_SESSION_PATCH)+ def test_transport_failure_is_reported_not_raised(self, MockSession):+ MockSession.return_value.post.side_effect = Exception("boom")+ assert create_webhook("key", COMPANY_ID, "https://ph.example/webhook").success is False+++def _webhook_list_page(items: list[dict[str, Any]], end_cursor: str | None, has_next_page: bool) -> mock.MagicMock:+ return _json_response(200, {"data": items, "page_info": {"end_cursor": end_cursor, "has_next_page": has_next_page}})+++class TestWebhookManagement:+ @mock.patch(WHOP_SESSION_PATCH)+ def test_lookup_pages_through_every_webhook(self, MockSession):+ session = MockSession.return_value+ session.get.side_effect = [+ _webhook_list_page([{"id": "hook_1", "url": "https://other.example"}], "cursor-1", True),+ _webhook_list_page(+ [+ {+ "id": "hook_2",+ "url": "https://ph.example/webhook",+ "events": ["payment.succeeded"],+ "enabled": True,+ }+ ],+ None,+ False,+ ),+ ]++ info = get_external_webhook_info("key", COMPANY_ID, "https://ph.example/webhook")++ assert info.exists is True+ assert info.enabled_events == ["payment.succeeded"]+ assert info.status == "enabled"+ assert "after=cursor-1" in session.get.call_args_list[1].args[0]++ @mock.patch(WHOP_SESSION_PATCH)+ def test_lookup_reports_absence(self, MockSession):+ MockSession.return_value.get.return_value = _webhook_list_page([], None, False)++ assert get_external_webhook_info("key", COMPANY_ID, "https://ph.example/webhook").exists is False++ @mock.patch(WHOP_SESSION_PATCH)+ def test_sync_merges_missing_events_and_keeps_existing_ones(self, MockSession):+ session = MockSession.return_value+ session.get.return_value = _webhook_list_page(+ [{"id": "hook_1", "url": "https://ph.example/webhook", "events": ["payment.created", "custom.event"]}],+ None,+ False,+ )++ result = sync_webhook_events("key", COMPANY_ID, "https://ph.example/webhook", ["payment.succeeded"])++ assert result.success is True+ assert session.patch.call_args.kwargs["json"] == {+ "events": ["custom.event", "payment.created", "payment.succeeded"]+ }++ @mock.patch(WHOP_SESSION_PATCH)+ def test_sync_skips_the_write_when_events_already_match(self, MockSession):+ session = MockSession.return_value+ session.get.return_value = _webhook_list_page(+ [{"id": "hook_1", "url": "https://ph.example/webhook", "events": ["payment.succeeded"]}], None, False+ )++ assert sync_webhook_events("key", COMPANY_ID, "https://ph.example/webhook", ["payment.succeeded"]).success+ session.patch.assert_not_called()++ @mock.patch(WHOP_SESSION_PATCH)+ def test_delete_removes_only_matching_webhooks(self, MockSession):+ session = MockSession.return_value+ session.get.return_value = _webhook_list_page(+ [+ {"id": "hook_1", "url": "https://other.example"},+ {"id": "hook_2", "url": "https://ph.example/webhook"},+ ],+ None,+ False,+ )+ session.delete.return_value = mock.MagicMock(status_code=204)++ result = delete_webhook("key", COMPANY_ID, "https://ph.example/webhook")++ assert result.success is True+ assert session.delete.call_args.args[0].endswith("/webhooks/hook_2")++ @mock.patch(WHOP_SESSION_PATCH)+ def test_delete_surfaces_a_rejected_removal(self, MockSession):+ session = MockSession.return_value+ session.get.return_value = _webhook_list_page(+ [{"id": "hook_2", "url": "https://ph.example/webhook"}], None, False+ )+ session.delete.return_value = mock.MagicMock(status_code=403)++ assert delete_webhook("key", COMPANY_ID, "https://ph.example/webhook").success is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/whop/tests/test_whop_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/tests/test_whop_source.pynew file mode 100644index 000000000000..b925991c0033--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/tests/test_whop_source.py@@ -0,0 +1,234 @@+import pytest+from unittest import mock++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.generated_configs.whop import WhopSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.whop.settings import (+ ALL_WEBHOOK_EVENTS,+ ENDPOINTS,+ INCREMENTAL_ENDPOINTS,+ MERGE_ONLY_ENDPOINTS,+ SCHEMA_TO_WEBHOOK_EVENTS,+ WEBHOOK_SCHEMA_NAMES,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.whop.source import WhopSource+from products.warehouse_sources.backend.temporal.data_imports.sources.whop.whop import WhopResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++API_CLIENT_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.whop.source.api_client"++WEBHOOK_URL = "https://ph.example/webhook"+++class TestWhopSource:+ def setup_method(self):+ self.source = WhopSource()+ self.team_id = 123+ self.config = WhopSourceConfig(api_key="test-api-key", company_id="biz_test")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.WHOP++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Whop"+ assert config.label == "Whop"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # The source must ship visible: unreleasedSource hides it from every user.+ assert not config.unreleasedSource+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/whop"++ @pytest.mark.parametrize(+ "field_name, expected_type, expected_secret",+ [+ ("api_key", SourceFieldInputConfigType.PASSWORD, True),+ ("company_id", SourceFieldInputConfigType.TEXT, False),+ ],+ )+ def test_credential_fields(self, field_name, expected_type, expected_secret):+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == field_name)++ assert field.type == expected_type+ assert field.secret is expected_secret+ assert field.required is True++ def test_webhook_fields_include_a_secret_signing_secret(self):+ config = self.source.get_source_config+ assert config.webhookFields is not None+ field = next(+ f for f in config.webhookFields if isinstance(f, SourceFieldInputConfig) and f.name == "signing_secret"+ )+ assert field.secret is True++ def test_get_schemas_lists_every_endpoint(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert [schema.name for schema in schemas] == list(ENDPOINTS)++ def test_get_schemas_filters_by_name(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["payments"])+ assert [schema.name for schema in schemas] == ["payments"]++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_incremental_support_matches_the_endpoint_catalog(self, endpoint):+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)++ assert schema.supports_incremental is (endpoint in INCREMENTAL_ENDPOINTS)+ if schema.supports_incremental:+ assert [f["field"] for f in schema.incremental_fields] == ["created_at"]+ else:+ assert schema.incremental_fields == []+ # Endpoints paged newest-first re-yield watermark boundary rows, which append would+ # duplicate; only a merge on `id` dedupes them.+ assert schema.supports_append is (endpoint in INCREMENTAL_ENDPOINTS and endpoint not in MERGE_ONLY_ENDPOINTS)++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_webhook_support_matches_the_event_catalog(self, endpoint):+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)+ assert schema.supports_webhooks is (endpoint in WEBHOOK_SCHEMA_NAMES)++ def test_canonical_descriptions_only_describe_real_schemas(self):+ # A key that doesn't match a schema name is silently ignored, so the descriptions would+ # never reach the table they were written for.+ assert set(self.source.get_canonical_descriptions()) <= set(ENDPOINTS)++ def test_webhook_resource_map_routes_by_distinct_event_prefix(self):+ mapping = self.source.webhook_resource_map++ assert set(mapping) == set(WEBHOOK_SCHEMA_NAMES)+ # `dispute` and `dispute_alert` share a prefix boundary; collapsing them would file every+ # dispute alert into the disputes table.+ assert len(set(mapping.values())) == len(mapping)+ assert mapping["disputes"] == "dispute"+ assert mapping["dispute_alerts"] == "dispute_alert"++ @pytest.mark.parametrize("schema_name, events", list(SCHEMA_TO_WEBHOOK_EVENTS.items()))+ def test_every_event_starts_with_its_schema_routing_prefix(self, schema_name, events):+ # The hog template routes on the event's prefix, so an event whose prefix doesn't match its+ # schema's mapping key would be dropped as unroutable.+ prefix = self.source.webhook_resource_map[schema_name]+ assert all(event.split(".", 1)[0] == prefix for event in events)++ def test_desired_webhook_events_are_deduped_and_within_the_catalog(self):+ events = self.source.get_desired_webhook_events(self.config, ["payments", "payments", "refunds"])++ assert events == sorted(set(SCHEMA_TO_WEBHOOK_EVENTS["payments"] + SCHEMA_TO_WEBHOOK_EVENTS["refunds"]))+ assert set(events) <= set(ALL_WEBHOOK_EVENTS)++ def test_desired_webhook_events_ignores_schemas_with_no_events(self):+ assert self.source.get_desired_webhook_events(self.config, ["affiliates"]) == []++ def test_webhook_template_exposes_the_signing_secret_input(self):+ template = self.source.webhook_template+ assert template is not None+ assert {field["key"] for field in template.inputs_schema} >= {+ "signing_secret",+ "schema_mapping",+ "source_id",+ }++ @pytest.mark.parametrize(+ "company_id, probe_result, schema_name, expected_valid",+ [+ ("biz_test", (True, 200), None, True),+ # A 403 means a genuine key without company:basic:read; users may only grant the scopes+ # for the tables they sync, so source creation must not be blocked on it.+ ("biz_test", (False, 403), None, True),+ ("biz_test", (False, 403), "payments", False),+ ("biz_test", (False, 401), None, False),+ ("biz_test", (False, 404), None, False),+ ("biz_test", (False, None), None, False),+ ("company-1", (True, 200), None, False),+ ],+ )+ def test_validate_credentials(self, company_id, probe_result, schema_name, expected_valid):+ config = WhopSourceConfig(api_key="test-api-key", company_id=company_id)++ with mock.patch(API_CLIENT_PATCH) as api_client:+ api_client.validate_credentials.return_value = probe_result+ is_valid, message = self.source.validate_credentials(config, self.team_id, schema_name=schema_name)++ assert is_valid is expected_valid+ assert (message is None) is expected_valid++ def test_validate_credentials_skips_the_probe_for_a_malformed_company_id(self):+ config = WhopSourceConfig(api_key="test-api-key", company_id="acme")++ with mock.patch(API_CLIENT_PATCH) as api_client:+ self.source.validate_credentials(config, self.team_id)++ api_client.validate_credentials.assert_not_called()++ def test_resumable_manager_is_bound_to_the_cursor_dataclass(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is WhopResumeConfig++ @pytest.mark.parametrize(+ "method_name, client_method",+ [+ ("create_webhook", "create_webhook"),+ ("delete_webhook", "delete_webhook"),+ ("get_external_webhook_info", "get_external_webhook_info"),+ ],+ )+ def test_webhook_management_passes_the_connected_company(self, method_name, client_method):+ # The webhook endpoints require company_id; dropping it would 400 every registration.+ with mock.patch(API_CLIENT_PATCH) as api_client:+ getattr(self.source, method_name)(self.config, WEBHOOK_URL, self.team_id)++ assert getattr(api_client, client_method).call_args.args == ("test-api-key", "biz_test", WEBHOOK_URL)++ def test_sync_webhook_events_forwards_the_events_for_the_selected_schemas(self):+ with mock.patch(API_CLIENT_PATCH) as api_client:+ self.source.sync_webhook_events(self.config, WEBHOOK_URL, self.team_id, ["refunds"])++ assert api_client.sync_webhook_events.call_args.args == (+ "test-api-key",+ "biz_test",+ WEBHOOK_URL,+ sorted(SCHEMA_TO_WEBHOOK_EVENTS["refunds"]),+ )++ def test_source_for_pipeline_plumbs_the_sync_inputs(self):+ inputs = mock.MagicMock()+ inputs.schema_name = "payments"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-05-01T00:00:00Z"+ manager = mock.MagicMock()++ with mock.patch(API_CLIENT_PATCH) as api_client:+ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = api_client.whop_source.call_args.kwargs+ assert kwargs["api_key"] == "test-api-key"+ assert kwargs["company_id"] == "biz_test"+ assert kwargs["endpoint"] == "payments"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-05-01T00:00:00Z"++ def test_source_for_pipeline_withholds_the_watermark_on_a_full_refresh(self):+ # Passing a stale watermark through on a full refresh would filter out every row that+ # predates it, quietly shrinking the table the user asked to rebuild.+ inputs = mock.MagicMock()+ inputs.schema_name = "payments"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-05-01T00:00:00Z"++ with mock.patch(API_CLIENT_PATCH) as api_client:+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert api_client.whop_source.call_args.kwargs["db_incremental_field_last_value"] is None++ @pytest.mark.parametrize("status", ["401", "403"])+ def test_auth_failures_are_non_retryable(self, status):+ errors = self.source.get_non_retryable_errors()+ assert any(key.startswith(status) for key in errors)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/whop/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/webhook_template.pynew file mode 100644index 000000000000..b4b798f8afee--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/webhook_template.py@@ -0,0 +1,144 @@+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC++# Whop follows the Standard Webhooks spec: `webhook-id`, `webhook-timestamp` (Unix seconds) and+# `webhook-signature` (a space-separated list of `v<version>,<base64 HMAC-SHA256>` entries) signing+# "{id}.{timestamp}.{raw body}". Whop's own SDK snippets base64-encode the dashboard secret before+# handing it to the verifier, which decodes it straight back, so the HMAC key is the secret string+# exactly as Whop displays it.+#+# The payload envelope is {id, type, timestamp, company_id, data}; `type` is `<resource>.<action>`+# (e.g. `payment.succeeded`), so the resource prefix is the schema routing key.+template: HogFunctionTemplateDC = HogFunctionTemplateDC(+ status="alpha",+ free=False,+ type="warehouse_source_webhook",+ id="template-warehouse-source-whop",+ name="Whop warehouse source webhook",+ description="Receive Whop webhook events for data warehouse ingestion",+ icon_url="/static/services/whop.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 webhookId := request.headers['webhook-id']+ let timestamp := request.headers['webhook-timestamp']+ let signatureHeader := request.headers['webhook-signature']++ if (empty(webhookId) or empty(timestamp) or empty(signatureHeader)) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Missing signature',+ }+ }+ }++ let signedPayload := concat(webhookId, '.', timestamp, '.', request.stringBody)+ let computedSignature := sha256HmacChain([inputs.signing_secret, signedPayload], 'base64')++ // The header can carry several `v1,<signature>` entries, so match on containment rather than+ // equality; the signature is base64 and long enough that a substring hit is the real one.+ if (position(signatureHeader, computedSignature) == 0) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Bad signature',+ }+ }+ }++ let timestampDelta := toInt(toUnixTimestamp(now())) - toInt(timestamp)+ if (timestampDelta > 300 or timestampDelta < -300) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Timestamp outside tolerance',+ }+ }+ }+}++let eventType := request.body.type++if (empty(eventType)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'No event type found, skipping'+ }+ }+}++let resourceType := splitByString('.', eventType)[1]+let schemaId := inputs.schema_mapping?.[resourceType]++if (empty(schemaId)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': f'No schema mapping for resource type: {resourceType}, skipping'+ }+ }+}++produceToWarehouseWebhooks(request.body, schemaId)""",+ inputs_schema=[+ {+ "type": "string",+ "key": "signing_secret",+ "label": "Signing secret",+ "required": False,+ "secret": True,+ "hidden": False,+ "description": (+ "The webhook's signing secret from Whop. Used to verify the webhook-signature header "+ "so deliveries provably come from Whop."+ ),+ },+ {+ "type": "boolean",+ "key": "bypass_signature_check",+ "label": "Bypass signature check",+ "description": "If set, the 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 Whop resource types 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/whop/whop.py b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/whop.pynew file mode 100644index 000000000000..142c86a104c4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/whop/whop.py@@ -0,0 +1,395 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++import orjson+import pyarrow as pa+from asgiref.sync import async_to_sync+from requests import 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,+ WebhookSyncResult,+)+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 (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponseCursorPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+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.whop.settings import (+ ALL_WEBHOOK_EVENTS,+ BASE_URL,+ PAGE_SIZE,+ WEBHOOK_SCHEMA_NAMES,+ WHOP_ENDPOINTS,+ sort_mode_for,+)++REQUEST_TIMEOUT = 30+++class WhopResumeConfig:+ cursor: str+++def _parse_datetime(value: Any) -> Optional[datetime]:+ """Coerce a persisted watermark to an aware UTC datetime.++ Whop timestamps are ISO 8601 strings (e.g. "2023-12-01T05:00:00.401Z"), so the stored value is a+ string or datetime; epoch numbers are accepted defensively.+ """+ if value is None or isinstance(value, bool):+ return None+ if isinstance(value, datetime):+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ if isinstance(value, int | float):+ try:+ return datetime.fromtimestamp(value, tz=UTC)+ except (OverflowError, OSError, ValueError):+ return None+ if isinstance(value, str):+ try:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)+ return None+++def _to_iso8601(value: datetime) -> str:+ """Render a watermark the way Whop's timestamp filters expect (UTC, `Z` suffix)."""+ return value.astimezone(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z")+++class WhopCursorPaginator(JSONResponseCursorPaginator):+ """Relay-style cursor paginator for Whop list endpoints.++ Whop returns `{"data": [...], "page_info": {"end_cursor", "has_next_page", ...}}`. Relay keeps+ `end_cursor` populated on the final page, so paging must terminate on `has_next_page` rather+ than on a missing cursor.+ """++ def __init__(self) -> None:+ super().__init__(cursor_path="page_info.end_cursor", cursor_param="after")++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ super().update_state(response, data)+ if not self._has_next_page:+ return+ try:+ page_info = response.json().get("page_info") or {}+ except Exception:+ # An unparseable body means the framework has nothing to page with either; stop rather+ # than re-requesting the same cursor forever.+ self._has_next_page = False+ return+ self._has_next_page = bool(page_info.get("has_next_page"))+++def _list_params(+ endpoint: str,+ company_id: str,+ watermark: Optional[datetime],+) -> dict[str, Any]:+ config = WHOP_ENDPOINTS[endpoint]+ params: dict[str, Any] = {"first": PAGE_SIZE, "company_id": company_id}++ if config.supports_created_at_order:+ # Forcing the sort column makes the arrival order knowable, which is what lets this endpoint+ # declare sort_mode="asc" and checkpoint the watermark per batch.+ params["order"] = "created_at"+ params["direction"] = "asc"+ elif config.supports_direction:+ params["direction"] = "desc"++ if watermark is not None and config.supports_created_after:+ params["created_after"] = _to_iso8601(watermark)++ return params+++def whop_source(+ api_key: str,+ company_id: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[WhopResumeConfig],+ webhook_source_manager: Optional[WebhookSourceManager] = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = WHOP_ENDPOINTS[endpoint]+ watermark = _parse_datetime(db_incremental_field_last_value) if should_use_incremental_field else None++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": BASE_URL,+ "auth": {"type": "bearer", "token": api_key},+ "paginator": WhopCursorPaginator(),+ # capture=False: Whop list responses carry buyer PII (emails, phone numbers, billing and+ # shipping addresses) and signed invoice tokens the name-based scrubbers can't+ # recognise, so keep the raw bodies out of HTTP sample capture.+ "session": make_tracked_session(capture=False, redact_values=(api_key,)),+ },+ "resources": [+ {+ "name": endpoint,+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ }+ if should_use_incremental_field+ else "replace",+ "table_format": "delta",+ "endpoint": {+ "path": config.path,+ "params": _list_params(endpoint, company_id, watermark),+ "data_selector": "data",+ },+ }+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ initial_paginator_state = {"cursor": resume.cursor}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # The hook fires AFTER a page is yielded, so a crash re-yields the last page (merge dedupes+ # on `id`) rather than skipping it. Only persist while a next page remains.+ if state and state.get("cursor"):+ resumable_source_manager.save_state(WhopResumeConfig(cursor=str(state["cursor"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ # The `created_after` filter is already baked into the request params, so the framework's+ # own incremental param injection is intentionally unused.+ db_incremental_field_last_value=None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ webhook_enabled = False+ if webhook_source_manager is not None and endpoint in WEBHOOK_SCHEMA_NAMES:+ webhook_enabled = async_to_sync(webhook_source_manager.webhook_enabled)(webhook_only=False)++ 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=endpoint,+ items=items,+ primary_keys=["id"],+ sort_mode=sort_mode_for(endpoint),+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def webhook_table_transformer(table: pa.Table) -> pa.Table:+ """Reshape raw webhook deliveries into rows matching the pull-API table shape.++ Deliveries land as the full POST body `{"id", "type", "timestamp", "company_id", "data": {...}}`+ where `data` is the resource in the same shape the list endpoint returns. We hoist `data` to the+ row root and keep only the newest version per resource id within the batch - delta merge only+ dedupes across syncs, so a batch carrying e.g. `payment.pending` then `payment.succeeded` for+ one payment must collapse to the latest row here.+ """+ if "data" not in table.column_names:+ return table_from_py_list([])++ has_timestamp = "timestamp" in table.column_names+ payloads = table.column("data").to_pylist()+ timestamps = table.column("timestamp").to_pylist() if has_timestamp else [None] * len(payloads)++ latest_by_id: dict[Any, tuple[Optional[datetime], dict[str, Any]]] = {}+ for payload, delivered_at in zip(payloads, timestamps):+ # The buffering layer may serialize nested structures back to JSON strings.+ if isinstance(payload, str | bytes):+ try:+ payload = orjson.loads(payload)+ except orjson.JSONDecodeError:+ continue+ if not isinstance(payload, dict) or payload.get("id") is None:+ continue+ sent_at = _parse_datetime(delivered_at)+ existing = latest_by_id.get(payload["id"])+ # Later rows win ties so batch arrival order breaks equal or missing timestamps.+ if existing is None or existing[0] is None or (sent_at is not None and sent_at >= existing[0]):+ latest_by_id[payload["id"]] = (sent_at, payload)++ return table_from_py_list([row for _, row in latest_by_id.values()])+++def _make_session(api_key: str) -> Session:+ return make_tracked_session(+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ redact_values=(api_key,),+ # Webhook responses carry the signing secret, so keep them out of HTTP sample capture.+ capture=False,+ )+++def validate_credentials(api_key: str, company_id: str) -> tuple[bool, Optional[int]]:+ """Probe the credential against the connected company, returning `(is_valid, status_code)`.++ `GET /companies/{id}` is the cheapest call that proves both the key and the company id. A 403+ means the key is genuine but lacks `company:basic:read`, which the caller accepts at+ source-create time.+ """+ return validate_via_probe(+ lambda: make_tracked_session(capture=False, redact_values=(api_key,)),+ f"{BASE_URL}/companies/{company_id}",+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ )+++def _iterate_webhooks(session: Session, company_id: str) -> Iterator[dict[str, Any]]:+ """Walk `GET /webhooks` with Whop's cursor pagination, yielding each webhook object."""+ cursor: Optional[str] = None+ while True:+ params: dict[str, Any] = {"company_id": company_id, "first": PAGE_SIZE}+ if cursor:+ params["after"] = cursor+ response = session.get(f"{BASE_URL}/webhooks?{urlencode(params)}", timeout=REQUEST_TIMEOUT)+ response.raise_for_status()+ body = response.json()+ yield from (item for item in body.get("data") or [] if isinstance(item, dict))++ page_info = body.get("page_info") or {}+ if not page_info.get("has_next_page"):+ return+ cursor = page_info.get("end_cursor")+ if not cursor:+ return+++def _webhooks_matching(session: Session, company_id: str, webhook_url: str) -> list[dict[str, Any]]:+ return [item for item in _iterate_webhooks(session, company_id) if item.get("url") == webhook_url]+++def create_webhook(api_key: str, company_id: str, webhook_url: str) -> WebhookCreationResult:+ """Register a v1 webhook on the company, returning Whop's generated signing secret.++ `api_version_date` is deliberately left unset: unpinned v1 deliveries use the payload shape this+ source's transformer expects, and pinning would opt the webhook into the dated Experimental+ contract instead.+ """+ try:+ session = _make_session(api_key)+ response = session.post(+ f"{BASE_URL}/webhooks",+ json={+ "url": webhook_url,+ "events": ALL_WEBHOOK_EVENTS,+ "resource_id": company_id,+ "api_version": "v1",+ "enabled": True,+ },+ timeout=REQUEST_TIMEOUT,+ )+ if response.status_code not in (200, 201):+ return WebhookCreationResult(+ success=False,+ error=(+ f"Whop rejected the webhook registration (HTTP {response.status_code}). The API key needs the "+ "developer:manage_webhook permission. Please create the webhook manually below."+ ),+ )++ secret = (response.json() or {}).get("webhook_secret")+ if not secret:+ return WebhookCreationResult(+ success=False,+ error="Whop created the webhook but did not return a signing secret. Please create it manually below.",+ )+ return WebhookCreationResult(success=True, extra_inputs={"signing_secret": secret})+ except Exception as e:+ return WebhookCreationResult(+ success=False,+ error=f"Failed to create the Whop webhook: {e}. Please create it manually below.",+ )+++def sync_webhook_events(+ api_key: str, company_id: str, webhook_url: str, desired_events: list[str]+) -> WebhookSyncResult:+ """Add any missing `desired_events` to the company's webhooks pointing at `webhook_url`.++ Events are merged, never removed, so a manually broadened webhook keeps its extra events.+ """+ try:+ session = _make_session(api_key)+ for webhook in _webhooks_matching(session, company_id, webhook_url):+ current = webhook.get("events") or []+ merged = sorted(set(current) | set(desired_events))+ if merged == sorted(current):+ continue+ response = session.patch(+ f"{BASE_URL}/webhooks/{webhook.get('id')}",+ json={"events": merged},+ timeout=REQUEST_TIMEOUT,+ )+ response.raise_for_status()+ return WebhookSyncResult(success=True)+ except Exception as e:+ return WebhookSyncResult(success=False, error=f"Failed to update Whop webhook events: {e}")+++def get_external_webhook_info(api_key: str, company_id: str, webhook_url: str) -> ExternalWebhookInfo:+ try:+ session = _make_session(api_key)+ matching = _webhooks_matching(session, company_id, webhook_url)+ if not matching:+ return ExternalWebhookInfo(exists=False)++ webhook = matching[0]+ return ExternalWebhookInfo(+ exists=True,+ url=webhook.get("url"),+ enabled_events=webhook.get("events"),+ status="enabled" if webhook.get("enabled") else "disabled",+ created_at=webhook.get("created_at"),+ )+ except Exception as e:+ return ExternalWebhookInfo(exists=False, error=str(e))+++def delete_webhook(api_key: str, company_id: str, webhook_url: str) -> WebhookDeletionResult:+ try:+ session = _make_session(api_key)+ errors: list[str] = []+ for webhook in _webhooks_matching(session, company_id, webhook_url):+ response = session.delete(f"{BASE_URL}/webhooks/{webhook.get('id')}", timeout=REQUEST_TIMEOUT)+ if response.status_code not in (200, 202, 204):+ errors.append(f"webhook {webhook.get('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))