Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement lemon_squeezy import source (#72657)

Tom Owersced1a6aff121
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index b7f7f70c517c..db2d2c079891 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -327,6 +327,7 @@ the row lists both.
| leadfeeder | HTTP | requests | ✅ |
| leexi | HTTP | requests + `rest_source.RESTClient` | ✅ |
| lemlist | HTTP | requests | ✅ |
+| lemon_squeezy | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| less_annoying_crm | HTTP | requests | ✅ |
| lightfield | HTTP | requests + `rest_source.RESTClient` | ✅ |
| lightspeed_retail | HTTP | requests | ✅ |
@@ -816,7 +817,6 @@ doesn't conflict with concurrent PRs.
- koyeb
- kyve
- lambda_labs
-- lemon_squeezy
- lever
- liana
- lingo_dev
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/lemonsqueezy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/lemonsqueezy.py
index 0ad41b324800..7f94b553b95d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/lemonsqueezy.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/lemonsqueezy.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class LemonSqueezySourceConfig(config.Config):
- pass
+ api_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/canonical_descriptions.py
new file mode 100644
index 000000000000..f4fd2fa3d82d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/canonical_descriptions.py
@@ -0,0 +1,325 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "stores": {
+ "description": "A store you sell products from, including its plan, currency, and lifetime sales totals.",
+ "docs_url": "https://docs.lemonsqueezy.com/api/stores",
+ "columns": {
+ "id": "Unique identifier for the store.",
+ "name": "The name of the store.",
+ "slug": "The store's subdomain slug on lemonsqueezy.com.",
+ "domain": "The full domain of the store, e.g. my-store.lemonsqueezy.com.",
+ "url": "The fully-qualified URL of the store.",
+ "plan": "The store's current billing plan, e.g. fresh or sweet.",
+ "country": "The ISO 3166-1 two-letter country code of the store, e.g. US.",
+ "currency": "The ISO 4217 currency code of the store, e.g. USD.",
+ "total_sales": "The total number of sales made by this store.",
+ "total_revenue": "The total revenue of the store in the smallest currency unit (e.g. cents).",
+ "thirty_day_sales": "The number of sales made by this store in the last 30 days.",
+ "thirty_day_revenue": "The revenue of the store in the last 30 days, in the smallest currency unit.",
+ "created_at": "When the store was created (ISO 8601).",
+ "updated_at": "When the store was last updated (ISO 8601).",
+ },
+ },
+ "customers": {
+ "description": "A customer of your store, with their contact details, marketing status, and revenue metrics.",
+ "docs_url": "https://docs.lemonsqueezy.com/api/customers",
+ "columns": {
+ "id": "Unique identifier for the customer.",
+ "store_id": "The ID of the store this customer belongs to.",
+ "name": "The full name of the customer.",
+ "email": "The email address of the customer.",
+ "status": "The email marketing status of the customer, e.g. subscribed, unsubscribed, archived.",
+ "city": "The city of the customer.",
+ "region": "The region/state of the customer.",
+ "country": "The ISO 3166-1 two-letter country code of the customer.",
+ "total_revenue_currency": "The lifetime value of the customer in the store's currency, in the smallest unit.",
+ "mrr": "The monthly recurring revenue attributed to the customer, in the smallest currency unit.",
+ "created_at": "When the customer was created (ISO 8601).",
+ "updated_at": "When the customer was last updated (ISO 8601).",
+ "test_mode": "Whether the customer was created in test mode.",
+ },
+ },
+ "products": {
+ "description": "A sellable product in a store; each product has one or more variants.",
+ "docs_url": "https://docs.lemonsqueezy.com/api/products",
+ "columns": {
+ "id": "Unique identifier for the product.",
+ "store_id": "The ID of the store this product belongs to.",
+ "name": "The name of the product.",
+ "slug": "The URL slug of the product.",
+ "description": "The description of the product in HTML.",
+ "status": "The status of the product, e.g. draft or published.",
+ "price": "The price of the product's cheapest variant, in the smallest currency unit.",
+ "pay_what_you_want": "Whether the product uses pay-what-you-want pricing.",
+ "buy_now_url": "A checkout URL for the product.",
+ "created_at": "When the product was created (ISO 8601).",
+ "updated_at": "When the product was last updated (ISO 8601).",
+ "test_mode": "Whether the product was created in test mode.",
+ },
+ },
+ "variants": {
+ "description": "A purchasable variant of a product, carrying subscription, trial, and license key settings.",
+ "docs_url": "https://docs.lemonsqueezy.com/api/variants",
+ "columns": {
+ "id": "Unique identifier for the variant.",
+ "product_id": "The ID of the product this variant belongs to.",
+ "name": "The name of the variant.",
+ "slug": "The URL slug of the variant.",
+ "price": "The price of the variant in the smallest currency unit.",
+ "is_subscription": "Whether the variant is a subscription.",
+ "interval": "The billing interval for subscription variants, e.g. month or year.",
+ "interval_count": "The number of intervals between subscription billings.",
+ "has_free_trial": "Whether the subscription variant has a free trial.",
+ "has_license_keys": "Whether the variant generates license keys when purchased.",
+ "status": "The status of the variant, e.g. pending, draft, published.",
+ "created_at": "When the variant was created (ISO 8601).",
+ "updated_at": "When the variant was last updated (ISO 8601).",
+ },
+ },
+ "prices": {
+ "description": "A price attached to a variant, including historical prices kept after a variant's price changes.",
+ "docs_url": "https://docs.lemonsqueezy.com/api/prices",
+ "columns": {
+ "id": "Unique identifier for the price.",
+ "variant_id": "The ID of the variant this price belongs to.",
+ "category": "The type of purchase the price is for, e.g. one_time, subscription, lead_magnet, pwyw.",
+ "scheme": "The pricing scheme, e.g. standard, package, graduated, volume.",
+ "usage_aggregation": "How usage is aggregated for usage-based billing, e.g. sum or last_during_period.",
+ "unit_price": "The price in the smallest currency unit.",
+ "renewal_interval_unit": "The renewal interval unit for subscription prices, e.g. day, week, month, year.",
+ "renewal_interval_quantity": "The number of renewal interval units between billings.",
+ "tax_code": "The product tax category code, e.g. eservice, ebook, saas.",
+ "created_at": "When the price was created (ISO 8601).",
+ "updated_at": "When the price was last updated (ISO 8601).",
+ },
+ },
+ "files": {
+ "description": "A downloadable file attached to a variant, delivered to customers after purchase.",
+ "docs_url": "https://docs.lemonsqueezy.com/api/files",
+ "columns": {
+ "id": "Unique identifier for the file.",
+ "variant_id": "The ID of the variant this file belongs to.",
+ "identifier": "The unique identifier (UUID) of the file.",
+ "name": "The filename.",
+ "extension": "The file extension, e.g. pdf.",
+ "download_url": "The unique, signed URL to download the file (expires after 1 hour).",
+ "size": "The size of the file in bytes.",
+ "version": "The software version of this file, if set.",
+ "status": "The status of the file, e.g. draft or published.",
+ "created_at": "When the file was created (ISO 8601).",
+ "updated_at": "When the file was last updated (ISO 8601).",
+ },
+ },
+ "orders": {
+ "description": "A completed order, created every time a customer purchases from your store.",
+ "docs_url": "https://docs.lemonsqueezy.com/api/orders",
+ "columns": {
+ "id": "Unique identifier for the order.",
+ "store_id": "The ID of the store this order belongs to.",
+ "customer_id": "The ID of the customer this order belongs to.",
+ "identifier": "The unique identifier (UUID) of the order.",
+ "order_number": "An incrementing integer order number unique to the store.",
+ "user_name": "The full name of the customer at time of purchase.",
+ "user_email": "The email address of the customer at time of purchase.",
+ "currency": "The ISO 4217 currency code the order was paid in.",
+ "currency_rate": "The exchange rate from the order currency to the store currency at purchase time.",
+ "subtotal": "The order subtotal in the smallest currency unit, before discounts and tax.",
+ "discount_total": "The total discount applied, in the smallest currency unit.",
+ "tax": "The tax charged, in the smallest currency unit.",
+ "total": "The order total in the smallest currency unit.",
+ "subtotal_usd": "The order subtotal converted to USD, in cents.",
+ "total_usd": "The order total converted to USD, in cents.",
+ "status": "The status of the order, e.g. pending, paid, refunded, partial_refund, fraudulent.",
+ "refunded": "Whether the order has been fully refunded.",
+ "refunded_at": "When the order was refunded, if it was (ISO 8601).",
+ "created_at": "When the order was created (ISO 8601).",
+ "updated_at": "When the order was last updated (ISO 8601).",
+ "test_mode": "Whether the order was made in test mode.",
+ },
+ },
+ "order_items": {
+ "description": "A line item of an order, recording the product and variant purchased and the price paid.",
+ "docs_url": "https://docs.lemonsqueezy.com/api/order-items",
+ "columns": {
+ "id": "Unique identifier for the order item.",
+ "order_id": "The ID of the order this item belongs to.",
+ "product_id": "The ID of the product purchased.",
+ "variant_id": "The ID of the variant purchased.",
+ "product_name": "The name of the product at time of purchase.",
+ "variant_name": "The name of the variant at time of purchase.",
+ "price": "The price of the item in the smallest currency unit, in the order currency.",
+ "quantity": "The quantity purchased.",
+ "created_at": "When the order item was created (ISO 8601).",
+ "updated_at": "When the order item was last updated (ISO 8601).",
+ },
+ },
+ "subscriptions": {
+ "description": "A recurring subscription created when a customer purchases a subscription variant.",
+ "docs_url": "https://docs.lemonsqueezy.com/api/subscriptions",
+ "columns": {
+ "id": "Unique identifier for the subscription.",
+ "store_id": "The ID of the store this subscription belongs to.",
+ "customer_id": "The ID of the customer this subscription belongs to.",
+ "order_id": "The ID of the order that created this subscription.",
+ "order_item_id": "The ID of the order item that created this subscription.",
+ "product_id": "The ID of the subscribed product.",
+ "variant_id": "The ID of the subscribed variant.",
+ "product_name": "The name of the subscribed product.",
+ "variant_name": "The name of the subscribed variant.",
+ "user_name": "The full name of the customer.",
+ "user_email": "The email address of the customer.",
+ "status": "The status of the subscription, e.g. on_trial, active, paused, past_due, unpaid, cancelled, expired.",
+ "card_brand": "The brand of the card used to pay, e.g. visa.",
+ "card_last_four": "The last four digits of the card used to pay.",
+ "cancelled": "Whether the subscription has been cancelled (still active until the period ends).",
+ "trial_ends_at": "When the trial period ends, if on trial (ISO 8601).",
+ "billing_anchor": "The day of the month on which the subscription renews.",
+ "renews_at": "When the next subscription renewal is due (ISO 8601).",
+ "ends_at": "When the subscription ends or ended, for cancelled/expired subscriptions (ISO 8601).",
+ "created_at": "When the subscription was created (ISO 8601).",
+ "updated_at": "When the subscription was last updated (ISO 8601).",
+ "test_mode": "Whether the subscription was made in test mode.",
+ },
+ },
+ "subscription_invoices": {
+ "description": "An invoice generated each time a subscription payment is attempted, successful or not.",
+ "docs_url": "https://docs.lemonsqueezy.com/api/subscription-invoices",
+ "columns": {
+ "id": "Unique identifier for the subscription invoice.",
+ "store_id": "The ID of the store this invoice belongs to.",
+ "subscription_id": "The ID of the subscription this invoice belongs to.",
+ "customer_id": "The ID of the customer this invoice belongs to.",
+ "user_name": "The full name of the customer.",
+ "user_email": "The email address of the customer.",
+ "billing_reason": "Why the invoice was created, e.g. initial, renewal, updated.",
+ "currency": "The ISO 4217 currency code the invoice was billed in.",
+ "status": "The status of the invoice, e.g. pending, paid, void, refunded, partial_refund.",
+ "refunded": "Whether the invoice has been fully refunded.",
+ "refunded_at": "When the invoice was refunded, if it was (ISO 8601).",
+ "subtotal": "The invoice subtotal in the smallest currency unit.",
+ "discount_total": "The total discount applied, in the smallest currency unit.",
+ "tax": "The tax charged, in the smallest currency unit.",
+ "total": "The invoice total in the smallest currency unit.",
+ "total_usd": "The invoice total converted to USD, in cents.",
+ "created_at": "When the invoice was created (ISO 8601).",
+ "updated_at": "When the invoice was last updated (ISO 8601).",
+ "test_mode": "Whether the invoice was created in test mode.",
+ },
+ },
+ "subscription_items": {
+ "description": "The link between a subscription and the price it is billed at, with the quantity purchased.",
+ "docs_url": "https://docs.lemonsqueezy.com/api/subscription-items",
+ "columns": {
+ "id": "Unique identifier for the subscription item.",
+ "subscription_id": "The ID of the subscription this item belongs to.",
+ "price_id": "The ID of the price this item is billed at.",
+ "quantity": "The unit quantity of the subscription item.",
+ "is_usage_based": "Whether the item is billed on reported usage rather than a fixed quantity.",
+ "created_at": "When the subscription item was created (ISO 8601).",
+ "updated_at": "When the subscription item was last updated (ISO 8601).",
+ },
+ },
+ "usage_records": {
+ "description": "A unit-usage report against a usage-based subscription item, used to calculate the next bill.",
+ "docs_url": "https://docs.lemonsqueezy.com/api/usage-records",
+ "columns": {
+ "id": "Unique identifier for the usage record.",
+ "subscription_item_id": "The ID of the subscription item this record reports usage for.",
+ "quantity": "The number of units reported.",
+ "action": "How the quantity applies: increment adds to period usage, set overrides it.",
+ "created_at": "When the usage record was created (ISO 8601).",
+ "updated_at": "When the usage record was last updated (ISO 8601).",
+ },
+ },
+ "discounts": {
+ "description": "A discount code that customers can apply at checkout.",
+ "docs_url": "https://docs.lemonsqueezy.com/api/discounts",
+ "columns": {
+ "id": "Unique identifier for the discount.",
+ "store_id": "The ID of the store this discount belongs to.",
+ "name": "The name of the discount.",
+ "code": "The code customers enter at checkout to redeem the discount.",
+ "amount": "The discount amount: a fixed amount in the smallest currency unit, or a percentage.",
+ "amount_type": "Whether `amount` is a fixed value or a percent.",
+ "is_limited_redemptions": "Whether the discount has a maximum number of redemptions.",
+ "max_redemptions": "The maximum number of redemptions allowed, if limited.",
+ "starts_at": "When the discount becomes valid (ISO 8601).",
+ "expires_at": "When the discount expires (ISO 8601).",
+ "duration": "For subscriptions, how long the discount applies: once, repeating, or forever.",
+ "duration_in_months": "How many renewals the discount applies to when duration is repeating.",
+ "status": "The status of the discount, e.g. draft or published.",
+ "created_at": "When the discount was created (ISO 8601).",
+ "updated_at": "When the discount was last updated (ISO 8601).",
+ "test_mode": "Whether the discount was created in test mode.",
+ },
+ },
+ "discount_redemptions": {
+ "description": "A single redemption of a discount code against an order.",
+ "docs_url": "https://docs.lemonsqueezy.com/api/discount-redemptions",
+ "columns": {
+ "id": "Unique identifier for the discount redemption.",
+ "discount_id": "The ID of the discount that was redeemed.",
+ "order_id": "The ID of the order the discount was redeemed on.",
+ "discount_name": "The name of the discount at time of redemption.",
+ "discount_code": "The discount code that was used.",
+ "discount_amount": "The discount value: a fixed amount in the smallest currency unit, or a percentage.",
+ "discount_amount_type": "Whether `discount_amount` is a fixed value or a percent.",
+ "amount": "The amount deducted from the order, in the smallest currency unit.",
+ "created_at": "When the redemption occurred (ISO 8601).",
+ "updated_at": "When the redemption was last updated (ISO 8601).",
+ },
+ },
+ "license_keys": {
+ "description": "A software license key generated when a customer purchases a license-enabled variant.",
+ "docs_url": "https://docs.lemonsqueezy.com/api/license-keys",
+ "columns": {
+ "id": "Unique identifier for the license key.",
+ "store_id": "The ID of the store this license key belongs to.",
+ "customer_id": "The ID of the customer this license key belongs to.",
+ "order_id": "The ID of the order that generated this license key.",
+ "order_item_id": "The ID of the order item that generated this license key.",
+ "product_id": "The ID of the product this license key is for.",
+ "user_name": "The full name of the customer.",
+ "user_email": "The email address of the customer.",
+ "key": "The full license key.",
+ "key_short": "A prefix-shortened version of the license key for display.",
+ "activation_limit": "The maximum number of activations allowed for this key.",
+ "instances_count": "The number of instances this key has been activated on.",
+ "disabled": "Whether the key has been disabled.",
+ "status": "The status of the key, e.g. inactive, active, expired, disabled.",
+ "expires_at": "When the license key expires (ISO 8601).",
+ "created_at": "When the license key was created (ISO 8601).",
+ "updated_at": "When the license key was last updated (ISO 8601).",
+ },
+ },
+ "license_key_instances": {
+ "description": "A device/instance activation of a license key, created via the License API activate endpoint.",
+ "docs_url": "https://docs.lemonsqueezy.com/api/license-key-instances",
+ "columns": {
+ "id": "Unique identifier for the license key instance.",
+ "license_key_id": "The ID of the license key this instance activates.",
+ "identifier": "The unique identifier (UUID) of this instance, returned at activation.",
+ "name": "The label given to the instance at activation.",
+ "created_at": "When the instance was activated (ISO 8601).",
+ "updated_at": "When the instance was last updated (ISO 8601).",
+ },
+ },
+ "checkouts": {
+ "description": "A custom checkout created via the API, with its product options and prefilled customer data.",
+ "docs_url": "https://docs.lemonsqueezy.com/api/checkouts",
+ "columns": {
+ "id": "Unique identifier (UUID) for the checkout.",
+ "store_id": "The ID of the store this checkout belongs to.",
+ "variant_id": "The ID of the variant being sold in this checkout.",
+ "custom_price": "A custom price for the checkout in the smallest currency unit, overriding the variant price.",
+ "expires_at": "When the checkout link expires (ISO 8601).",
+ "url": "The unique URL of the checkout.",
+ "created_at": "When the checkout was created (ISO 8601).",
+ "updated_at": "When the checkout was last updated (ISO 8601).",
+ "test_mode": "Whether the checkout was created in test mode.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/lemon_squeezy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/lemon_squeezy.py
new file mode 100644
index 000000000000..e8e3946fb974
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/lemon_squeezy.py
@@ -0,0 +1,427 @@
+import secrets
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlsplit
+
+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.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.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 (
+ JSONResponsePaginator,
+)
+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.webhook_s3 import WebhookSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.lemon_squeezy.settings import (
+ ALL_WEBHOOK_EVENTS,
+ BASE_URL,
+ JSON_API_HEADERS,
+ LEMON_SQUEEZY_ENDPOINTS,
+ PAGE_SIZE,
+ WEBHOOK_SCHEMA_NAMES,
+)
+
+
+class LemonSqueezyResumeConfig:
+ next_url: str
+
+
+def _parse_datetime(value: Any) -> Optional[datetime]:
+ """Coerce a cursor value to an aware UTC datetime.
+
+ Lemon Squeezy timestamps are ISO-8601 strings (e.g. "2024-01-01T12:00:00.000000Z"), so the
+ persisted watermark is a string/datetime; epoch ints 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 _flatten_json_api_item(item: dict[str, Any]) -> dict[str, Any]:
+ """Hoist a JSON:API resource's `attributes` to the row root, keeping the top-level `id`.
+
+ Lemon Squeezy attributes never contain an `id` key, so the merge/primary key stays the
+ resource id. `relationships`/`links` are dropped — attributes already carry the foreign
+ keys (`store_id`, `order_id`, ...) as plain columns.
+ """
+ attributes = item.get("attributes")
+ if not isinstance(attributes, dict):
+ return {"id": item.get("id")}
+ return {"id": item.get("id"), **attributes}
+
+
+class LemonSqueezyPaginator(JSONResponsePaginator):
+ """Follows the JSON:API `links.next` URL, stopping early on incremental syncs.
+
+ Lemon Squeezy list endpoints return rows newest-first (`created_at` descending, no sort
+ param) and expose no server-side timestamp filter, so an incremental sync pages from the
+ newest row and halts once an entire page predates the watermark. Boundary-page rows older
+ than the watermark are re-yielded; the merge on `id` dedupes them.
+ """
+
+ def __init__(self, watermark: Optional[datetime] = None) -> None:
+ super().__init__(next_url_path="links.next")
+ self._watermark = watermark
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ if self._watermark is not None and data:
+ timestamps = [
+ parsed
+ for parsed in (
+ _parse_datetime((item.get("attributes") or {}).get("created_at"))
+ for item in data
+ if isinstance(item, dict)
+ )
+ if parsed is not None
+ ]
+ # Only stop when every row on the page predates the watermark; unparseable pages
+ # keep paging so an upstream format change degrades to a full walk, not data loss.
+ if timestamps and max(timestamps) < self._watermark:
+ self._next_url = None
+ self._has_next_page = False
+ return
+ super().update_state(response, data)
+
+
+def validate_credentials(api_key: str) -> bool:
+ """Confirm the API key is valid. `/v1/users/me` is a cheap authenticated probe."""
+ ok, _status = validate_via_probe(
+ # capture=False: `/v1/users/me` returns account data; allow_redirects=False keeps the
+ # probe (and its bearer token) pinned to the Lemon Squeezy origin.
+ lambda: make_tracked_session(capture=False, allow_redirects=False, redact_values=(api_key,)),
+ f"{BASE_URL}/v1/users/me",
+ headers={**JSON_API_HEADERS, "Authorization": f"Bearer {api_key}"},
+ )
+ return ok
+
+
+def lemon_squeezy_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[LemonSqueezyResumeConfig],
+ webhook_source_manager: Optional[WebhookSourceManager] = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = LEMON_SQUEEZY_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,
+ "headers": dict(JSON_API_HEADERS),
+ "auth": {"type": "bearer", "token": api_key},
+ "paginator": LemonSqueezyPaginator(watermark),
+ # capture=False: list responses carry customer PII, redeemable `license_keys.key`
+ # values, and signed file/checkout URLs the name-based scrubbers can't recognise, so
+ # keep the raw bodies out of HTTP sample capture even when an operator enables it.
+ "session": make_tracked_session(capture=False, redact_values=(api_key,)),
+ # `links.next` is response-controlled, so pin every paginated and resumed request to
+ # the Lemon Squeezy origin and refuse redirects — a poisoned next link can't retarget
+ # the bearer token at an attacker-controlled host.
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ },
+ "resources": [
+ {
+ "name": endpoint,
+ "write_disposition": {
+ "disposition": "merge",
+ "strategy": "upsert",
+ }
+ if should_use_incremental_field
+ else "replace",
+ "table_format": "delta",
+ "endpoint": {
+ "path": config.path,
+ "params": {"page[size]": PAGE_SIZE},
+ "data_selector": "data",
+ },
+ "data_map": _flatten_json_api_item,
+ }
+ ],
+ }
+
+ 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 = {"next_url": resume.next_url}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Persist only while a next page remains; the hook fires AFTER a page is yielded so a
+ # crash re-yields the last page (merge dedupes on primary key) rather than skipping it.
+ if state and state.get("next_url"):
+ resumable_source_manager.save_state(LemonSqueezyResumeConfig(next_url=str(state["next_url"])))
+
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ # The watermark is enforced client-side by the paginator (no server-side timestamp
+ # filter exists), so the framework's 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"],
+ # List endpoints return newest-first, so the incremental watermark is finalized only
+ # after a fully successful sync.
+ sort_mode="desc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=[config.partition_key],
+ )
+
+
+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 `{"meta": {...}, "data": {<JSON:API resource>}}`.
+ We flatten `data` the same way the pull path does ({"id", **attributes}) and keep only
+ the newest version per id within the batch — delta merge only dedupes across syncs, so a
+ batch carrying e.g. `subscription_created` then `subscription_updated` for the same id
+ must collapse to the latest row here.
+ """
+ if "data" not in table.column_names:
+ return table_from_py_list([])
+
+ latest_by_id: dict[Any, tuple[Optional[datetime], dict[str, Any]]] = {}
+ for data in table.column("data").to_pylist():
+ # The buffering layer may serialize nested structures to JSON strings.
+ if isinstance(data, str | bytes):
+ try:
+ data = orjson.loads(data)
+ except orjson.JSONDecodeError:
+ continue
+ if not isinstance(data, dict):
+ continue
+ row = _flatten_json_api_item(data)
+ if row.get("id") is None:
+ continue
+ updated_at = _parse_datetime(row.get("updated_at"))
+ existing = latest_by_id.get(row["id"])
+ # Later rows win ties so batch arrival order breaks equal/missing timestamps.
+ if existing is None or existing[0] is None or (updated_at is not None and updated_at >= existing[0]):
+ latest_by_id[row["id"]] = (updated_at, row)
+
+ return table_from_py_list([row for _, row in latest_by_id.values()])
+
+
+class LemonSqueezyUntrustedURLError(Exception):
+ pass
+
+
+# Host and scheme of the Lemon Squeezy API, pinned so a response-controlled `links.next` can't
+# retarget a credentialed webhook-management request at another origin.
+_API_NETLOC = urlsplit(BASE_URL).netloc
+
+
+def _assert_lemon_squeezy_origin(url: str) -> None:
+ """Reject a webhook-pagination URL that points off the Lemon Squeezy API origin.
+
+ `links.next` is response-controlled and the webhook-management session sends the bearer
+ token on every request, so a poisoned next link (off-host, downgraded to http, or on a
+ non-default port — netloc carries the port) would otherwise exfiltrate the key. Redirects
+ are separately refused by the no-redirect session `_make_session` builds.
+ """
+ split = urlsplit(url)
+ if not (split.scheme == "https" and split.netloc == _API_NETLOC and split.path.startswith("/v1/")):
+ raise LemonSqueezyUntrustedURLError(f"Refusing to follow a Lemon Squeezy URL outside {BASE_URL}/v1/")
+
+
+def _make_session(api_key: str) -> Session:
+ return make_tracked_session(
+ headers={**JSON_API_HEADERS, "Authorization": f"Bearer {api_key}"},
+ redact_values=(api_key,),
+ # Webhook responses carry the signing secret and store/customer data, so keep them out of
+ # HTTP sample capture; no-redirect pins the credentialed request to the origin it validated.
+ capture=False,
+ allow_redirects=False,
+ )
+
+
+def _iterate_list(session: Session, url: str) -> Iterator[dict[str, Any]]:
+ """Walk a JSON:API list endpoint via `links.next`, yielding each `data[]` item."""
+ next_url: Optional[str] = url
+ while next_url:
+ _assert_lemon_squeezy_origin(next_url)
+ response = session.get(next_url, timeout=30)
+ response.raise_for_status()
+ body = response.json()
+ yield from (item for item in body.get("data") or [] if isinstance(item, dict))
+ next_url = (body.get("links") or {}).get("next")
+
+
+def _list_webhooks_matching(session: Session, webhook_url: str) -> list[dict[str, Any]]:
+ return [
+ item
+ for item in _iterate_list(session, f"{BASE_URL}/v1/webhooks?page[size]={PAGE_SIZE}")
+ if (item.get("attributes") or {}).get("url") == webhook_url
+ ]
+
+
+def create_webhook(api_key: str, webhook_url: str) -> WebhookCreationResult:
+ """Register a webhook pointing at `webhook_url` on every store in the account.
+
+ Lemon Squeezy webhooks are store-scoped, so one is created per store, all sharing a single
+ generated signing secret (the hog function only stores one).
+ """
+ # Lemon Squeezy accepts a 6-40 character signing secret; token_hex(20) is exactly 40.
+ secret = secrets.token_hex(20)
+
+ try:
+ session = _make_session(api_key)
+ stores = list(_iterate_list(session, f"{BASE_URL}/v1/stores?page[size]={PAGE_SIZE}"))
+ if not stores:
+ return WebhookCreationResult(
+ success=False,
+ error="No Lemon Squeezy stores found for this API key. Please create the webhook manually.",
+ )
+
+ errors: list[str] = []
+ created = 0
+ for store in stores:
+ payload = {
+ "data": {
+ "type": "webhooks",
+ "attributes": {
+ "url": webhook_url,
+ "events": ALL_WEBHOOK_EVENTS,
+ "secret": secret,
+ },
+ "relationships": {"store": {"data": {"type": "stores", "id": str(store.get("id"))}}},
+ }
+ }
+ response = session.post(f"{BASE_URL}/v1/webhooks", json=payload, timeout=30)
+ if response.status_code in (200, 201):
+ created += 1
+ else:
+ errors.append(f"store {store.get('id')}: HTTP {response.status_code}")
+
+ if created == 0:
+ return WebhookCreationResult(
+ success=False,
+ error=(
+ "Failed to create the Lemon Squeezy webhook "
+ f"({'; '.join(errors)}). 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 Lemon Squeezy webhook: {e}. Please create it manually below.",
+ )
+
+
+def sync_webhook_events(api_key: str, webhook_url: str, desired_events: list[str]) -> WebhookSyncResult:
+ """Add any missing `desired_events` to the account'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 _list_webhooks_matching(session, webhook_url):
+ current = (webhook.get("attributes") or {}).get("events") or []
+ merged = sorted(set(current) | set(desired_events))
+ if merged == sorted(current):
+ continue
+ payload = {
+ "data": {
+ "type": "webhooks",
+ "id": str(webhook.get("id")),
+ "attributes": {"events": merged},
+ }
+ }
+ response = session.patch(f"{BASE_URL}/v1/webhooks/{webhook.get('id')}", json=payload, timeout=30)
+ response.raise_for_status()
+ return WebhookSyncResult(success=True)
+ except Exception as e:
+ return WebhookSyncResult(success=False, error=f"Failed to update Lemon Squeezy webhook events: {e}")
+
+
+def get_external_webhook_info(api_key: str, webhook_url: str) -> ExternalWebhookInfo:
+ try:
+ session = _make_session(api_key)
+ matching = _list_webhooks_matching(session, webhook_url)
+ if not matching:
+ return ExternalWebhookInfo(exists=False)
+
+ attributes = matching[0].get("attributes") or {}
+ return ExternalWebhookInfo(
+ exists=True,
+ url=attributes.get("url"),
+ enabled_events=attributes.get("events"),
+ status="enabled",
+ created_at=attributes.get("created_at"),
+ )
+ except Exception as e:
+ return ExternalWebhookInfo(exists=False, error=str(e))
+
+
+def delete_webhook(api_key: str, webhook_url: str) -> WebhookDeletionResult:
+ try:
+ session = _make_session(api_key)
+ matching = _list_webhooks_matching(session, webhook_url)
+ errors: list[str] = []
+ for webhook in matching:
+ response = session.delete(f"{BASE_URL}/v1/webhooks/{webhook.get('id')}", timeout=30)
+ if response.status_code not in (200, 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))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/settings.py
new file mode 100644
index 000000000000..4e7ad24e82aa
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/settings.py
@@ -0,0 +1,115 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
+
+BASE_URL = "https://api.lemonsqueezy.com"
+
+# Lemon Squeezy caps list pages at 100 items (default is 10).
+PAGE_SIZE = 100
+
+# JSON:API headers Lemon Squeezy requires on every request.
+JSON_API_HEADERS = {
+ "Accept": "application/vnd.api+json",
+ "Content-Type": "application/vnd.api+json",
+}
+
+
+@dataclass
+class LemonSqueezyEndpointConfig:
+ path: str
+ # JSON:API resource type carried in `data[].type` — also the routing key for webhook
+ # deliveries of this resource.
+ json_api_type: str
+ # Set only on append-mostly endpoints: list endpoints return rows created_at-descending
+ # with no server-side timestamp filter, so incremental sync is a stop-early cursor —
+ # pagination halts once an entire page predates the watermark. Mutable resources
+ # (subscriptions, customers, license keys) are full refresh (+ webhooks where offered)
+ # because a created_at cursor would never re-surface in-place updates.
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Every Lemon Squeezy resource carries a stable `created_at`; used for datetime partitioning.
+ partition_key: str = "created_at"
+
+
+LEMON_SQUEEZY_ENDPOINTS: dict[str, LemonSqueezyEndpointConfig] = {
+ "stores": LemonSqueezyEndpointConfig(path="/v1/stores", json_api_type="stores"),
+ "customers": LemonSqueezyEndpointConfig(path="/v1/customers", json_api_type="customers"),
+ "products": LemonSqueezyEndpointConfig(path="/v1/products", json_api_type="products"),
+ "variants": LemonSqueezyEndpointConfig(path="/v1/variants", json_api_type="variants"),
+ "prices": LemonSqueezyEndpointConfig(path="/v1/prices", json_api_type="prices"),
+ "files": LemonSqueezyEndpointConfig(path="/v1/files", json_api_type="files"),
+ "orders": LemonSqueezyEndpointConfig(
+ path="/v1/orders",
+ json_api_type="orders",
+ incremental_fields=[incremental_field("created_at")],
+ ),
+ "order_items": LemonSqueezyEndpointConfig(
+ path="/v1/order-items",
+ json_api_type="order-items",
+ incremental_fields=[incremental_field("created_at")],
+ ),
+ "subscriptions": LemonSqueezyEndpointConfig(path="/v1/subscriptions", json_api_type="subscriptions"),
+ "subscription_invoices": LemonSqueezyEndpointConfig(
+ path="/v1/subscription-invoices",
+ json_api_type="subscription-invoices",
+ incremental_fields=[incremental_field("created_at")],
+ ),
+ "subscription_items": LemonSqueezyEndpointConfig(path="/v1/subscription-items", json_api_type="subscription-items"),
+ "usage_records": LemonSqueezyEndpointConfig(
+ path="/v1/usage-records",
+ json_api_type="usage-records",
+ incremental_fields=[incremental_field("created_at")],
+ ),
+ "discounts": LemonSqueezyEndpointConfig(path="/v1/discounts", json_api_type="discounts"),
+ "discount_redemptions": LemonSqueezyEndpointConfig(
+ path="/v1/discount-redemptions",
+ json_api_type="discount-redemptions",
+ incremental_fields=[incremental_field("created_at")],
+ ),
+ "license_keys": LemonSqueezyEndpointConfig(path="/v1/license-keys", json_api_type="license-keys"),
+ "license_key_instances": LemonSqueezyEndpointConfig(
+ path="/v1/license-key-instances", json_api_type="license-key-instances"
+ ),
+ "checkouts": LemonSqueezyEndpointConfig(path="/v1/checkouts", json_api_type="checkouts"),
+}
+
+ENDPOINTS = tuple(LEMON_SQUEEZY_ENDPOINTS.keys())
+
+INCREMENTAL_ENDPOINTS = tuple(name for name, config in LEMON_SQUEEZY_ENDPOINTS.items() if config.incremental_fields)
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in LEMON_SQUEEZY_ENDPOINTS.items() if config.incremental_fields
+}
+
+# Webhook events per schema. Every delivery carries the full resource in JSON:API shape,
+# so webhook rows merge onto the same tables the pull API fills.
+SCHEMA_TO_WEBHOOK_EVENTS: dict[str, list[str]] = {
+ "orders": ["order_created", "order_refunded"],
+ "subscriptions": [
+ "subscription_created",
+ "subscription_updated",
+ "subscription_cancelled",
+ "subscription_resumed",
+ "subscription_expired",
+ "subscription_paused",
+ "subscription_unpaused",
+ "subscription_plan_changed",
+ ],
+ "subscription_invoices": [
+ "subscription_payment_success",
+ "subscription_payment_failed",
+ "subscription_payment_recovered",
+ "subscription_payment_refunded",
+ ],
+ "license_keys": ["license_key_created", "license_key_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 -> JSON:API resource type: the key incoming webhook deliveries are routed by
+# (the hog template looks up `request.body.data.type` in `schema_mapping`).
+RESOURCE_TO_JSON_API_TYPE: dict[str, str] = {
+ name: LEMON_SQUEEZY_ENDPOINTS[name].json_api_type for name in WEBHOOK_SCHEMA_NAMES
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/source.py
index d96215a47d94..a0233a8fe3f0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/source.py
@@ -1,32 +1,242 @@
-from typing import cast
+from typing import TYPE_CHECKING, Optional, cast
from 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.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+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.webhook_s3 import WebhookSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.lemonsqueezy import (
LemonSqueezySourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.lemon_squeezy import lemon_squeezy as api_client
+from products.warehouse_sources.backend.temporal.data_imports.sources.lemon_squeezy.lemon_squeezy import (
+ LemonSqueezyResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.lemon_squeezy.settings import (
+ ENDPOINTS,
+ INCREMENTAL_ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ RESOURCE_TO_JSON_API_TYPE,
+ SCHEMA_TO_WEBHOOK_EVENTS,
+ WEBHOOK_SCHEMA_NAMES,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+if TYPE_CHECKING:
+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
+
+LEMON_SQUEEZY_API_SETTINGS_URL = "https://app.lemonsqueezy.com/settings/api"
+
@SourceRegistry.register
-class LemonSqueezySource(SimpleSource[LemonSqueezySourceConfig]):
+class LemonSqueezySource(
+ ResumableSource[LemonSqueezySourceConfig, LemonSqueezyResumeConfig],
+ WebhookSource[LemonSqueezySourceConfig],
+):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://docs.lemonsqueezy.com/api"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.LEMONSQUEEZY
+ @property
+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.lemon_squeezy.webhook_template import (
+ template,
+ )
+
+ return template
+
+ @property
+ def webhook_resource_map(self) -> dict[str, str]:
+ return RESOURCE_TO_JSON_API_TYPE
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.LEMON_SQUEEZY,
category=DataWarehouseSourceCategory.PAYMENTS___BILLING,
label="Lemon Squeezy",
+ caption=(
+ "Connect your Lemon Squeezy account to sync stores, orders, subscriptions, "
+ "customers, license keys, and more into PostHog. Create an API key under "
+ f"[Settings > API]({LEMON_SQUEEZY_API_SETTINGS_URL}) in your Lemon Squeezy dashboard. "
+ "Note that Lemon Squeezy API keys expire after one year, and test-mode keys return "
+ "test-mode data only."
+ ),
iconPath="/static/services/lemon_squeezy.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/lemon-squeezy",
+ keywords=["lemonsqueezy"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ caption=(
+ f"Create an API key under [Settings > API]({LEMON_SQUEEZY_API_SETTINGS_URL}). "
+ "Keys expire after one year — you'll need to reconnect with a fresh key when it does."
+ ),
+ secret=True,
+ ),
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
+ webhookSetupCaption=(
+ "PostHog tries to register a webhook on each of your Lemon Squeezy stores using "
+ "your API key, with a generated signing secret used to verify deliveries.\n\n"
+ "**Manual setup** (only needed if automatic registration failed):\n\n"
+ "1. Go to [Settings > Webhooks](https://app.lemonsqueezy.com/settings/webhooks) in "
+ "your Lemon Squeezy dashboard\n"
+ "2. Click **+** to add a webhook and paste the webhook URL shown below into the "
+ "**Callback URL** field\n"
+ "3. Set a **Signing secret** (6-40 characters) and paste the same value into the "
+ "field below so PostHog can verify deliveries\n"
+ "4. Select the order, subscription, subscription payment, and license key events "
+ "matching the tables you sync\n"
+ "5. Click **Save webhook**, repeating for each store you want to sync"
+ ),
+ webhookFields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="signing_secret",
+ label="Signing secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ caption=(
+ "The signing secret configured on the Lemon Squeezy webhook. PostHog "
+ "uses it to verify the X-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.lemonsqueezy.com": (
+ "Lemon Squeezy rejected the API key. Keys expire after one year — generate a new "
+ "key under Settings > API and reconnect."
+ ),
+ "403 Client Error: Forbidden for url: https://api.lemonsqueezy.com": (
+ "Your Lemon Squeezy API key does not have access to this resource. Check the key "
+ "in your Lemon Squeezy dashboard and reconnect."
+ ),
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.lemon_squeezy.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: LemonSqueezySourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Incremental endpoints are merge-only: the stop-early cursor re-yields watermark
+ # boundary rows, which only a merge on `id` can dedupe (append would duplicate them).
+ return build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ merge_only=INCREMENTAL_ENDPOINTS,
+ supports_webhooks=WEBHOOK_SCHEMA_NAMES,
+ )
+
+ def validate_credentials(
+ self, config: LemonSqueezySourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if api_client.validate_credentials(config.api_key):
+ return True, None
+ return False, "Invalid Lemon Squeezy API key. Note that keys expire after one year."
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LemonSqueezyResumeConfig]:
+ return ResumableSourceManager[LemonSqueezyResumeConfig](inputs, LemonSqueezyResumeConfig)
+
+ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:
+ return WebhookSourceManager(inputs, inputs.logger)
+
+ def create_webhook(self, config: LemonSqueezySourceConfig, webhook_url: str, team_id: int) -> WebhookCreationResult:
+ return api_client.create_webhook(config.api_key, webhook_url)
+
+ def get_desired_webhook_events(
+ self, config: LemonSqueezySourceConfig, 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: LemonSqueezySourceConfig,
+ webhook_url: str,
+ team_id: int,
+ eligible_schema_names: list[str],
+ ) -> WebhookSyncResult:
+ desired_events = self.get_desired_webhook_events(config, eligible_schema_names) or []
+ return api_client.sync_webhook_events(config.api_key, webhook_url, desired_events)
+
+ def get_external_webhook_info(
+ self, config: LemonSqueezySourceConfig, webhook_url: str, team_id: int
+ ) -> ExternalWebhookInfo | None:
+ return api_client.get_external_webhook_info(config.api_key, webhook_url)
+
+ def delete_webhook(self, config: LemonSqueezySourceConfig, webhook_url: str, team_id: int) -> WebhookDeletionResult:
+ return api_client.delete_webhook(config.api_key, webhook_url)
+
+ def source_for_pipeline(
+ self,
+ config: LemonSqueezySourceConfig,
+ resumable_source_manager: ResumableSourceManager[LemonSqueezyResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return api_client.lemon_squeezy_source(
+ api_key=config.api_key,
+ 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/lemon_squeezy/tests/test_lemon_squeezy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/tests/test_lemon_squeezy.py
new file mode 100644
index 000000000000..f8ca90ccc6c2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/tests/test_lemon_squeezy.py
@@ -0,0 +1,566 @@
+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.pipeline.utils import table_from_py_list
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import TrackedHTTPAdapter
+from products.warehouse_sources.backend.temporal.data_imports.sources.lemon_squeezy.lemon_squeezy import (
+ LemonSqueezyPaginator,
+ LemonSqueezyResumeConfig,
+ LemonSqueezyUntrustedURLError,
+ _assert_lemon_squeezy_origin,
+ _flatten_json_api_item,
+ _make_session,
+ _parse_datetime,
+ _webhook_table_transformer,
+ create_webhook,
+ delete_webhook,
+ get_external_webhook_info,
+ lemon_squeezy_source,
+ sync_webhook_events,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.lemon_squeezy.settings import (
+ ALL_WEBHOOK_EVENTS,
+ BASE_URL,
+ INCREMENTAL_ENDPOINTS,
+ LEMON_SQUEEZY_ENDPOINTS,
+)
+
+# The source builds its own tracked session (capture-disabled, host-pinned) for the sync client,
+# validate_credentials, and the webhook management helpers.
+LEMON_SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.lemon_squeezy.lemon_squeezy.make_tracked_session"
+)
+
+
+def _json_api_item(resource_id: str, created_at: str, **attributes: Any) -> dict[str, Any]:
+ return {
+ "type": "orders",
+ "id": resource_id,
+ "attributes": {"created_at": created_at, **attributes},
+ }
+
+
+def _response(items: list[dict[str, Any]], next_link: str | None) -> Response:
+ body = {"data": items, "links": {"next": next_link} if next_link else {}}
+ resp = Response()
+ resp.status_code = 200
+ resp._content = json.dumps(body).encode()
+ return resp
+
+
+def _make_manager(resume_state: LemonSqueezyResumeConfig | 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/url 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 {}), "headers": request.headers or {}})
+ # The prepared URL must be a real string: the client host-pins every request URL, so a
+ # MagicMock here would blow up `urlsplit` in the allowed-host check.
+ 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 lemon_squeezy_source(
+ "test-api-key", endpoint, team_id=1, job_id="j", 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.000000Z", datetime(2024, 5, 1, 10, 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
+
+
+class TestFlatten:
+ def test_hoists_attributes_and_keeps_id(self):
+ row = _flatten_json_api_item(
+ {
+ "type": "orders",
+ "id": "17",
+ "attributes": {"total": 999, "created_at": "2024-05-01T10:00:00Z"},
+ "relationships": {"store": {}},
+ "links": {"self": "https://api.lemonsqueezy.com/v1/orders/17"},
+ }
+ )
+ assert row == {"id": "17", "total": 999, "created_at": "2024-05-01T10:00:00Z"}
+
+ def test_missing_attributes_still_yields_id(self):
+ assert _flatten_json_api_item({"type": "orders", "id": "17"}) == {"id": "17"}
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize("status_code, expected", [(200, True), (401, False), (403, False), (500, False)])
+ @mock.patch(LEMON_SESSION_PATCH)
+ def test_status_mapping(self, mock_session, status_code, expected):
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)
+ assert validate_credentials("key") is expected
+
+ @mock.patch(LEMON_SESSION_PATCH)
+ def test_probes_users_me_with_json_api_headers(self, mock_session):
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
+
+ validate_credentials("key")
+
+ call = mock_session.return_value.get.call_args
+ assert call.args[0] == "https://api.lemonsqueezy.com/v1/users/me"
+ assert call.kwargs["headers"]["Authorization"] == "Bearer key"
+ assert call.kwargs["headers"]["Accept"] == "application/vnd.api+json"
+
+ @mock.patch(LEMON_SESSION_PATCH)
+ def test_swallows_exceptions(self, mock_session):
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("key") is False
+
+
+class TestPagination:
+ @mock.patch(LEMON_SESSION_PATCH)
+ def test_follows_links_next_and_drops_original_params(self, MockSession):
+ session = MockSession.return_value
+ requests_seen = _wire(
+ session,
+ [
+ _response(
+ [_json_api_item("1", "2024-05-02T00:00:00Z"), _json_api_item("2", "2024-05-01T00:00:00Z")],
+ "https://api.lemonsqueezy.com/v1/orders?page%5Bnumber%5D=2",
+ ),
+ _response([_json_api_item("3", "2024-04-30T00:00:00Z")], None),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source("orders", manager))
+
+ assert [row["id"] for row in rows] == ["1", "2", "3"]
+ assert requests_seen[0]["url"] == "https://api.lemonsqueezy.com/v1/orders"
+ assert requests_seen[0]["params"] == {"page[size]": 100}
+ # The next-page URL is self-contained; original params are dropped.
+ assert requests_seen[1]["url"] == "https://api.lemonsqueezy.com/v1/orders?page%5Bnumber%5D=2"
+ assert requests_seen[1]["params"] == {}
+ # State is saved only while a next page exists.
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0] == LemonSqueezyResumeConfig(
+ next_url="https://api.lemonsqueezy.com/v1/orders?page%5Bnumber%5D=2"
+ )
+
+ @mock.patch(LEMON_SESSION_PATCH)
+ def test_rows_are_flattened(self, MockSession):
+ session = MockSession.return_value
+ _wire(session, [_response([_json_api_item("1", "2024-05-02T00:00:00Z", total=999)], None)])
+
+ rows = _rows(_source("orders", _make_manager()))
+
+ assert rows == [{"id": "1", "created_at": "2024-05-02T00:00:00Z", "total": 999}]
+
+ @mock.patch(LEMON_SESSION_PATCH)
+ def test_resumes_from_saved_state(self, MockSession):
+ session = MockSession.return_value
+ requests_seen = _wire(session, [_response([_json_api_item("9", "2024-05-01T00:00:00Z")], None)])
+
+ resume_url = "https://api.lemonsqueezy.com/v1/orders?page%5Bnumber%5D=5"
+ rows = _rows(_source("orders", _make_manager(LemonSqueezyResumeConfig(next_url=resume_url))))
+
+ assert [row["id"] for row in rows] == ["9"]
+ assert requests_seen[0]["url"] == resume_url
+ assert requests_seen[0]["params"] == {}
+
+ @mock.patch(LEMON_SESSION_PATCH)
+ def test_incremental_stops_once_page_predates_watermark(self, MockSession):
+ session = MockSession.return_value
+ requests_seen = _wire(
+ session,
+ [
+ # Page 1 straddles the watermark: keep paging.
+ _response(
+ [_json_api_item("3", "2024-05-03T00:00:00Z"), _json_api_item("2", "2024-04-30T00:00:00Z")],
+ "https://api.lemonsqueezy.com/v1/orders?page%5Bnumber%5D=2",
+ ),
+ # Page 2 is entirely older than the watermark: stop despite a next link.
+ _response(
+ [_json_api_item("1", "2024-04-29T00:00:00Z")],
+ "https://api.lemonsqueezy.com/v1/orders?page%5Bnumber%5D=3",
+ ),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(
+ _source(
+ "orders",
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-05-01T00:00:00Z",
+ )
+ )
+
+ assert len(requests_seen) == 2
+ # Boundary rows older than the watermark are re-yielded; merge on id dedupes them.
+ assert [row["id"] for row in rows] == ["3", "2", "1"]
+
+ @mock.patch(LEMON_SESSION_PATCH)
+ def test_full_refresh_walks_past_old_pages(self, MockSession):
+ session = MockSession.return_value
+ requests_seen = _wire(
+ session,
+ [
+ _response(
+ [_json_api_item("2", "2024-04-30T00:00:00Z")],
+ "https://api.lemonsqueezy.com/v1/orders?page%5Bnumber%5D=2",
+ ),
+ _response([_json_api_item("1", "2024-04-29T00:00:00Z")], None),
+ ],
+ )
+
+ rows = _rows(_source("orders", _make_manager()))
+
+ assert len(requests_seen) == 2
+ assert [row["id"] for row in rows] == ["2", "1"]
+
+ def test_paginator_keeps_paging_when_created_at_unparseable(self):
+ # An upstream format change must degrade to a full walk, not silently stop the sync.
+ paginator = LemonSqueezyPaginator(watermark=datetime(2024, 5, 1, tzinfo=UTC))
+ response = _response([_json_api_item("1", "not-a-date")], "https://api.lemonsqueezy.com/v1/orders?page=2")
+
+ paginator.update_state(response, response.json()["data"])
+
+ assert paginator.has_next_page is True
+
+
+class TestSourceResponseMetadata:
+ @pytest.mark.parametrize("endpoint", list(LEMON_SQUEEZY_ENDPOINTS.keys()))
+ @mock.patch(LEMON_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"]
+ # Lists arrive newest-first, so the watermark must only finalize after a full sync.
+ assert response.sort_mode == "desc"
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["created_at"]
+
+ @pytest.mark.parametrize(
+ "endpoint, should_use_incremental_field, expected_disposition",
+ [
+ ("orders", True, {"disposition": "merge", "strategy": "upsert"}),
+ ("orders", False, "replace"),
+ ("stores", False, "replace"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.lemon_squeezy.lemon_squeezy.rest_api_resource"
+ )
+ def test_write_disposition_follows_incremental_mode(
+ self, mock_rest_api_resource, endpoint, should_use_incremental_field, expected_disposition
+ ):
+ _source(endpoint, _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
+
+ def test_incremental_endpoints_use_created_at(self):
+ for endpoint in INCREMENTAL_ENDPOINTS:
+ fields = LEMON_SQUEEZY_ENDPOINTS[endpoint].incremental_fields
+ assert [f["field"] for f in fields] == ["created_at"]
+
+
+class TestWebhookTableTransformer:
+ def test_flattens_and_keeps_latest_version_per_id(self):
+ table = table_from_py_list(
+ [
+ {
+ "meta": {"event_name": "subscription_created"},
+ "data": {
+ "type": "subscriptions",
+ "id": "1",
+ "attributes": {"status": "on_trial", "updated_at": "2024-05-01T00:00:00Z"},
+ },
+ },
+ {
+ "meta": {"event_name": "subscription_updated"},
+ "data": {
+ "type": "subscriptions",
+ "id": "1",
+ "attributes": {"status": "active", "updated_at": "2024-05-02T00:00:00Z"},
+ },
+ },
+ {
+ "meta": {"event_name": "subscription_created"},
+ "data": {
+ "type": "subscriptions",
+ "id": "2",
+ "attributes": {"status": "active", "updated_at": "2024-05-01T00:00:00Z"},
+ },
+ },
+ ]
+ )
+
+ result = _webhook_table_transformer(table).to_pylist()
+
+ by_id = {row["id"]: row for row in result}
+ assert set(by_id) == {"1", "2"}
+ assert by_id["1"]["status"] == "active"
+
+ def test_out_of_order_batch_keeps_newest(self):
+ table = table_from_py_list(
+ [
+ {
+ "data": {
+ "type": "orders",
+ "id": "1",
+ "attributes": {"status": "refunded", "updated_at": "2024-05-02T00:00:00Z"},
+ }
+ },
+ {
+ "data": {
+ "type": "orders",
+ "id": "1",
+ "attributes": {"status": "paid", "updated_at": "2024-05-01T00:00:00Z"},
+ }
+ },
+ ]
+ )
+
+ result = _webhook_table_transformer(table).to_pylist()
+
+ assert len(result) == 1
+ assert result[0]["status"] == "refunded"
+
+ def test_missing_data_column_yields_empty_table(self):
+ table = table_from_py_list([{"meta": {"event_name": "order_created"}}])
+ assert _webhook_table_transformer(table).num_rows == 0
+
+
+def _webhook_api_response(status_code: int, body: dict[str, Any] | None = None) -> mock.MagicMock:
+ response = mock.MagicMock(status_code=status_code)
+ response.json.return_value = body or {}
+ response.raise_for_status.return_value = None
+ return response
+
+
+def _list_response(items: list[dict[str, Any]]) -> mock.MagicMock:
+ return _webhook_api_response(200, {"data": items, "links": {}})
+
+
+class TestWebhookManagement:
+ @mock.patch(LEMON_SESSION_PATCH)
+ def test_create_webhook_creates_one_per_store_with_shared_secret(self, mock_session):
+ session = mock_session.return_value
+ session.get.return_value = _list_response(
+ [
+ {"type": "stores", "id": "1", "attributes": {}},
+ {"type": "stores", "id": "2", "attributes": {}},
+ ]
+ )
+ session.post.return_value = _webhook_api_response(201)
+
+ result = create_webhook("key", "https://us.posthog.com/webhooks/abc")
+
+ assert result.success is True
+ secret = result.extra_inputs["signing_secret"]
+ assert 6 <= len(secret) <= 40
+
+ assert session.post.call_count == 2
+ payloads = [call.kwargs["json"] for call in session.post.call_args_list]
+ assert {p["data"]["relationships"]["store"]["data"]["id"] for p in payloads} == {"1", "2"}
+ for payload in payloads:
+ attributes = payload["data"]["attributes"]
+ assert attributes["url"] == "https://us.posthog.com/webhooks/abc"
+ assert attributes["events"] == ALL_WEBHOOK_EVENTS
+ # A single secret across stores — the hog function only stores one.
+ assert attributes["secret"] == secret
+
+ @mock.patch(LEMON_SESSION_PATCH)
+ def test_create_webhook_fails_without_stores(self, mock_session):
+ mock_session.return_value.get.return_value = _list_response([])
+
+ result = create_webhook("key", "https://us.posthog.com/webhooks/abc")
+
+ assert result.success is False
+ assert "manually" in (result.error or "")
+
+ @mock.patch(LEMON_SESSION_PATCH)
+ def test_create_webhook_succeeds_when_any_store_succeeds(self, mock_session):
+ session = mock_session.return_value
+ session.get.return_value = _list_response(
+ [
+ {"type": "stores", "id": "1", "attributes": {}},
+ {"type": "stores", "id": "2", "attributes": {}},
+ ]
+ )
+ session.post.side_effect = [_webhook_api_response(201), _webhook_api_response(422)]
+
+ result = create_webhook("key", "https://us.posthog.com/webhooks/abc")
+
+ assert result.success is True
+ assert "signing_secret" in result.extra_inputs
+
+ @mock.patch(LEMON_SESSION_PATCH)
+ def test_delete_webhook_removes_only_matching_urls(self, mock_session):
+ session = mock_session.return_value
+ session.get.return_value = _list_response(
+ [
+ {"type": "webhooks", "id": "10", "attributes": {"url": "https://us.posthog.com/webhooks/abc"}},
+ {"type": "webhooks", "id": "11", "attributes": {"url": "https://elsewhere.example.com"}},
+ ]
+ )
+ session.delete.return_value = _webhook_api_response(204)
+
+ result = delete_webhook("key", "https://us.posthog.com/webhooks/abc")
+
+ assert result.success is True
+ session.delete.assert_called_once()
+ assert "/v1/webhooks/10" in session.delete.call_args.args[0]
+
+ @mock.patch(LEMON_SESSION_PATCH)
+ def test_get_external_webhook_info(self, mock_session):
+ session = mock_session.return_value
+ session.get.return_value = _list_response(
+ [
+ {
+ "type": "webhooks",
+ "id": "10",
+ "attributes": {
+ "url": "https://us.posthog.com/webhooks/abc",
+ "events": ["order_created"],
+ "created_at": "2024-05-01T00:00:00Z",
+ },
+ },
+ ]
+ )
+
+ info = get_external_webhook_info("key", "https://us.posthog.com/webhooks/abc")
+
+ assert info.exists is True
+ assert info.enabled_events == ["order_created"]
+
+ @mock.patch(LEMON_SESSION_PATCH)
+ def test_get_external_webhook_info_not_found(self, mock_session):
+ mock_session.return_value.get.return_value = _list_response([])
+
+ info = get_external_webhook_info("key", "https://us.posthog.com/webhooks/abc")
+
+ assert info.exists is False
+
+ @mock.patch(LEMON_SESSION_PATCH)
+ def test_sync_webhook_events_merges_missing_events(self, mock_session):
+ session = mock_session.return_value
+ session.get.return_value = _list_response(
+ [
+ {
+ "type": "webhooks",
+ "id": "10",
+ "attributes": {
+ "url": "https://us.posthog.com/webhooks/abc",
+ "events": ["order_created", "custom_extra_event"],
+ },
+ },
+ ]
+ )
+ session.patch.return_value = _webhook_api_response(200)
+
+ result = sync_webhook_events("key", "https://us.posthog.com/webhooks/abc", ["order_created", "order_refunded"])
+
+ assert result.success is True
+ payload = session.patch.call_args.kwargs["json"]
+ # Desired events are added; manually-added extras are preserved.
+ assert payload["data"]["attributes"]["events"] == ["custom_extra_event", "order_created", "order_refunded"]
+
+ @mock.patch(LEMON_SESSION_PATCH)
+ def test_sync_webhook_events_skips_patch_when_already_subscribed(self, mock_session):
+ session = mock_session.return_value
+ session.get.return_value = _list_response(
+ [
+ {
+ "type": "webhooks",
+ "id": "10",
+ "attributes": {"url": "https://us.posthog.com/webhooks/abc", "events": ["order_created"]},
+ },
+ ]
+ )
+
+ result = sync_webhook_events("key", "https://us.posthog.com/webhooks/abc", ["order_created"])
+
+ assert result.success is True
+ session.patch.assert_not_called()
+
+
+class TestCredentialLeakHardening:
+ """Guards the SSRF / credential-exposure controls: pinning credentialed requests to the
+ Lemon Squeezy origin and keeping secret-bearing responses out of HTTP sample capture."""
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "https://evil.example.com/v1/orders", # off-host
+ "http://api.lemonsqueezy.com/v1/orders", # scheme downgrade to http
+ "https://api.lemonsqueezy.com:8443/v1/orders", # non-default port
+ "https://api.lemonsqueezy.com.evil.com/v1/orders", # look-alike host
+ "https://api.lemonsqueezy.com/internal/orders", # off the /v1/ prefix
+ ],
+ )
+ def test_iterate_list_refuses_off_origin_next_url(self, url):
+ with pytest.raises(LemonSqueezyUntrustedURLError):
+ _assert_lemon_squeezy_origin(url)
+
+ def test_iterate_list_allows_api_origin(self):
+ # A legitimate next link must not be rejected.
+ _assert_lemon_squeezy_origin(f"{BASE_URL}/v1/webhooks?page%5Bnumber%5D=2")
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.lemon_squeezy.lemon_squeezy.rest_api_resource"
+ )
+ def test_source_pins_host_and_disables_capture(self, mock_rest_api_resource):
+ _source("orders", _make_manager())
+
+ client = mock_rest_api_resource.call_args.args[0]["client"]
+ # Off-host next/resume URLs and redirects are rejected before the bearer token is sent.
+ assert client["allowed_hosts"] == []
+ assert client["allow_redirects"] is False
+ # Response bodies carry PII, license keys, and signed URLs — never captured as samples.
+ assert _adapter_capture(client["session"]) is False
+
+ def test_make_session_disables_capture(self):
+ # Webhook responses carry the signing secret and store/customer data.
+ assert _adapter_capture(_make_session("key")) is False
+
+
+def _adapter_capture(session: Any) -> bool:
+ adapter = session.get_adapter(BASE_URL)
+ assert isinstance(adapter, TrackedHTTPAdapter)
+ return adapter._capture
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/tests/test_lemon_squeezy_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/tests/test_lemon_squeezy_source.py
new file mode 100644
index 000000000000..118484bc44cd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/tests/test_lemon_squeezy_source.py
@@ -0,0 +1,188 @@
+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.lemonsqueezy import (
+ LemonSqueezySourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.lemon_squeezy.lemon_squeezy import (
+ LemonSqueezyResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.lemon_squeezy.settings import (
+ ENDPOINTS,
+ INCREMENTAL_ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ SCHEMA_TO_WEBHOOK_EVENTS,
+ WEBHOOK_SCHEMA_NAMES,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.lemon_squeezy.source import LemonSqueezySource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+API_CLIENT_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.lemon_squeezy.source.api_client"
+
+
+class TestLemonSqueezySource:
+ def setup_method(self):
+ self.source = LemonSqueezySource()
+ self.team_id = 123
+ self.config = LemonSqueezySourceConfig(api_key="test-api-key")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.LEMONSQUEEZY
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "LemonSqueezy"
+ assert config.label == "Lemon Squeezy"
+ 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/lemon-squeezy"
+
+ def test_api_key_field_is_secret_password(self):
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_webhook_fields_include_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
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.lemonsqueezy.com/v1/orders?page%5Bsize%5D=100",
+ "403 Client Error: Forbidden for url: https://api.lemonsqueezy.com/v1/stores",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.lemonsqueezy.com/v1/orders",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_error):
+ assert not any(key in other_error for key in self.source.get_non_retryable_errors())
+
+ def test_get_schemas(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ incremental = {schema.name for schema in schemas if schema.supports_incremental}
+ # Only append-mostly endpoints get the stop-early created_at cursor; mutable
+ # resources stay full refresh so in-place updates aren't silently missed.
+ assert incremental == set(INCREMENTAL_ENDPOINTS)
+
+ def test_incremental_schemas_are_merge_only(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+ for name in INCREMENTAL_ENDPOINTS:
+ # The stop-early cursor re-yields watermark boundary rows, which only merge dedupes.
+ assert schemas[name].supports_append is False
+ assert schemas[name].incremental_fields == INCREMENTAL_FIELDS[name]
+
+ def test_webhook_capable_schemas(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+ webhook_capable = {name for name, schema in schemas.items() if schema.supports_webhooks}
+ assert webhook_capable == set(WEBHOOK_SCHEMA_NAMES)
+ assert all(not schema.webhook_only for schema in schemas.values())
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["orders"])
+ assert [schema.name for schema in schemas] == ["orders"]
+
+ @pytest.mark.parametrize("mock_return, expected_valid", [(True, True), (False, False)])
+ @mock.patch(f"{API_CLIENT_PATCH}.validate_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert (error_message is None) is expected_valid
+ mock_validate.assert_called_once_with("test-api-key")
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is LemonSqueezyResumeConfig
+
+ @mock.patch(f"{API_CLIENT_PATCH}.lemon_squeezy_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "orders"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-05-01T00:00:00Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "test-api-key"
+ assert kwargs["endpoint"] == "orders"
+ assert kwargs["team_id"] is inputs.team_id
+ assert kwargs["job_id"] is inputs.job_id
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["webhook_source_manager"] is not None
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-05-01T00:00:00Z"
+
+ @mock.patch(f"{API_CLIENT_PATCH}.lemon_squeezy_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "stores"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2024-05-01T00:00:00Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_webhook_resource_map_routes_by_json_api_type(self):
+ assert self.source.webhook_resource_map == {
+ "orders": "orders",
+ "subscriptions": "subscriptions",
+ "subscription_invoices": "subscription-invoices",
+ "license_keys": "license-keys",
+ }
+
+ def test_webhook_template_routes_on_schema_mapping(self):
+ template = self.source.webhook_template
+ assert template is not None
+ assert template.type == "warehouse_source_webhook"
+ input_keys = {input_schema["key"] for input_schema in template.inputs_schema}
+ assert {"signing_secret", "schema_mapping", "source_id"} <= input_keys
+
+ def test_get_desired_webhook_events_covers_eligible_schemas_only(self):
+ events = self.source.get_desired_webhook_events(self.config, ["orders", "license_keys"])
+ assert events == sorted(SCHEMA_TO_WEBHOOK_EVENTS["orders"] + SCHEMA_TO_WEBHOOK_EVENTS["license_keys"])
+
+ @mock.patch(f"{API_CLIENT_PATCH}.create_webhook")
+ def test_create_webhook_delegates(self, mock_create):
+ self.source.create_webhook(self.config, "https://us.posthog.com/webhooks/abc", self.team_id)
+ mock_create.assert_called_once_with("test-api-key", "https://us.posthog.com/webhooks/abc")
+
+ @mock.patch(f"{API_CLIENT_PATCH}.delete_webhook")
+ def test_delete_webhook_delegates(self, mock_delete):
+ self.source.delete_webhook(self.config, "https://us.posthog.com/webhooks/abc", self.team_id)
+ mock_delete.assert_called_once_with("test-api-key", "https://us.posthog.com/webhooks/abc")
+
+ @mock.patch(f"{API_CLIENT_PATCH}.sync_webhook_events")
+ def test_sync_webhook_events_passes_desired_events(self, mock_sync):
+ self.source.sync_webhook_events(self.config, "https://us.posthog.com/webhooks/abc", self.team_id, ["orders"])
+ mock_sync.assert_called_once_with(
+ "test-api-key", "https://us.posthog.com/webhooks/abc", sorted(SCHEMA_TO_WEBHOOK_EVENTS["orders"])
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/webhook_template.py
new file mode 100644
index 000000000000..53f40196e3b2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/webhook_template.py
@@ -0,0 +1,120 @@
+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
+
+template: HogFunctionTemplateDC = HogFunctionTemplateDC(
+ status="alpha",
+ free=False,
+ type="warehouse_source_webhook",
+ id="template-warehouse-source-lemon-squeezy",
+ name="Lemon Squeezy warehouse source webhook",
+ description="Receive Lemon Squeezy webhook events for data warehouse ingestion",
+ icon_url="/static/services/lemon_squeezy.png",
+ category=["Data warehouse"],
+ code_language="hog",
+ code="""\
+if (request.method != 'POST') {
+ return {
+ 'httpResponse': {
+ 'status': 405,
+ 'body': 'Method not allowed'
+ }
+ }
+}
+
+if (not inputs.bypass_signature_check) {
+ if (empty(inputs.signing_secret)) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Signing secret not configured',
+ }
+ }
+ }
+
+ let signature := request.headers['x-signature']
+
+ if (empty(signature)) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Missing signature',
+ }
+ }
+ }
+
+ let computedSignature := sha256HmacChainHex([inputs.signing_secret, request.stringBody])
+
+ if (computedSignature != signature) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Bad signature',
+ }
+ }
+ }
+}
+
+let resourceType := request.body.data?.type
+
+if (empty(resourceType)) {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': 'No resource type found, skipping'
+ }
+ }
+}
+
+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. Used to verify the X-Signature header "
+ "(HMAC-SHA256 of the raw request body) so deliveries provably come from Lemon Squeezy."
+ ),
+ },
+ {
+ "type": "boolean",
+ "key": "bypass_signature_check",
+ "label": "Bypass signature check",
+ "description": "If set, the X-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 Lemon Squeezy 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,
+ },
+ ],
+)