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 checkout.com import source (#62955)

Tom Owers0cc97ddeb39d
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index c33710c08cba..cad2650a8d2b 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -67,6 +67,7 @@ the row lists both.
| calendly | HTTP | requests | ✅ |
| campaign_monitor | HTTP | requests | ✅ |
| chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| checkout_com | HTTP | requests | ✅ |
| coda | HTTP | requests | ✅ |
| commercetools | HTTP | requests | ✅ |
| confluence | HTTP | requests | ✅ |
@@ -245,7 +246,6 @@ doesn't conflict with concurrent PRs.
- box
- branch
- campaign_manager_360
-- checkout_com
- chorus
- cloudflare
- cockroachdb
diff --git a/posthog/temporal/data_imports/sources/checkout_com/checkout_com.py b/posthog/temporal/data_imports/sources/checkout_com/checkout_com.py
new file mode 100644
index 000000000000..c7640928acea
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/checkout_com/checkout_com.py
@@ -0,0 +1,194 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+CHECKOUT_HOSTS = {
+ "production": {"api": "https://api.checkout.com", "auth": "https://access.checkout.com/connect/token"},
+ "sandbox": {
+ "api": "https://api.sandbox.checkout.com",
+ "auth": "https://access.sandbox.checkout.com/connect/token",
+ },
+}
+# Disputes list pages cap at 250.
+PAGE_SIZE = 250
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRY_ATTEMPTS = 5
+
+# Checkout.com has no list-all-payments endpoint — bulk payment data only
+# exists via report files. Disputes are the one honest list surface.
+ENDPOINTS = ("disputes",)
+
+
+class CheckoutComRetryableError(Exception):
+ pass
+
+
+class CheckoutComResumeConfig:
+ # Disputes paginate with limit/skip; static params are rebuilt from job
+ # inputs on resume.
+ skip: int
+
+
+def _get_session(client_secret: str) -> requests.Session:
+ return make_tracked_session(redact_values=(client_secret,))
+
+
+def _hosts(environment: str) -> dict[str, str]:
+ hosts = CHECKOUT_HOSTS.get(environment)
+ if hosts is None:
+ raise ValueError(f"Invalid Checkout.com environment: {environment}")
+ return hosts
+
+
+@retry(
+ retry=retry_if_exception_type((CheckoutComRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+)
+def _mint_token(session: requests.Session, environment: str, client_id: str, client_secret: str) -> str:
+ """Exchange client credentials for a bearer token (~1h lifetime)."""
+ response = session.post(
+ _hosts(environment)["auth"],
+ data={"grant_type": "client_credentials"},
+ auth=(client_id, client_secret),
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ # A transient auth-host blip (429/5xx) during an in-flight re-mint must not
+ # kill the whole sync — retry it like any other retryable API error.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise CheckoutComRetryableError(f"Checkout.com auth error (retryable): status={response.status_code}")
+ response.raise_for_status()
+ return response.json()["access_token"]
+
+
+def _format_timestamp(value: Any) -> str:
+ """Format an incremental cursor for the disputes `from` filter (ISO 8601 UTC)."""
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return value.strftime("%Y-%m-%dT00:00:00Z")
+ return str(value)
+
+
+def validate_credentials(environment: str, client_id: str, client_secret: str) -> bool:
+ """Confirm the API credentials are valid by minting a token."""
+ try:
+ _mint_token(_get_session(client_secret), environment, client_id, client_secret)
+ return True
+ except Exception:
+ return False
+
+
+def get_rows(
+ environment: str,
+ client_id: str,
+ client_secret: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CheckoutComResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ session = _get_session(client_secret)
+ api_base = _hosts(environment)["api"]
+ token = _mint_token(session, environment, client_id, client_secret)
+
+ @retry(
+ retry=retry_if_exception_type((CheckoutComRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+ )
+ def fetch(params: dict[str, Any]) -> dict[str, Any]:
+ nonlocal token
+ url = f"{api_base}/{endpoint}?{urlencode(params)}"
+ response = session.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # Tokens last ~1h; re-mint once if the sync outlives one.
+ if response.status_code == 401:
+ token = _mint_token(session, environment, client_id, client_secret)
+ response = session.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise CheckoutComRetryableError(
+ f"Checkout.com API error (retryable): status={response.status_code}, url={url}"
+ )
+
+ if not response.ok:
+ logger.error(f"Checkout.com API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ skip = resume_config.skip if resume_config is not None else 0
+ if resume_config is not None:
+ logger.debug(f"Checkout.com: resuming {endpoint} from skip {skip}")
+
+ base_params: dict[str, Any] = {"limit": PAGE_SIZE}
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ # `from` filters on a dispute's last_update timestamp.
+ base_params["from"] = _format_timestamp(db_incremental_field_last_value)
+
+ while True:
+ data = fetch({**base_params, "skip": skip})
+ items = data.get("data", []) or []
+
+ if items:
+ yield items
+
+ total = data.get("total_count")
+ skip += len(items)
+ if not items or (isinstance(total, int) and skip >= total):
+ break
+
+ # Save state AFTER yielding the page so a crash re-yields the last page
+ # (merge dedupes on primary key) rather than skipping it.
+ resumable_source_manager.save_state(CheckoutComResumeConfig(skip=skip))
+
+
+def checkout_com_source(
+ environment: str,
+ client_id: str,
+ client_secret: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CheckoutComResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ environment=environment,
+ client_id=client_id,
+ client_secret=client_secret,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=["id"],
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=["received_on"],
+ # Disputes are returned newest-first; the pipeline commits desc
+ # watermarks only when a run completes.
+ sort_mode="desc",
+ )
diff --git a/posthog/temporal/data_imports/sources/checkout_com/source.py b/posthog/temporal/data_imports/sources/checkout_com/source.py
index 81b01b6aeddd..73ddae6a4e2a 100644
--- a/posthog/temporal/data_imports/sources/checkout_com/source.py
+++ b/posthog/temporal/data_imports/sources/checkout_com/source.py
@@ -1,29 +1,151 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.checkout_com.checkout_com import (
+ ENDPOINTS,
+ CheckoutComResumeConfig,
+ checkout_com_source,
+ validate_credentials as validate_checkout_credentials,
+)
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import CheckoutComSourceConfig
-from products.data_warehouse.backend.types import ExternalDataSourceType
+from products.data_warehouse.backend.types import ExternalDataSourceType, IncrementalField, IncrementalFieldType
+
+_DISPUTES_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "last_update",
+ "type": IncrementalFieldType.DateTime,
+ "field": "last_update",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
@SourceRegistry.register
-class CheckoutComSource(SimpleSource[CheckoutComSourceConfig]):
+class CheckoutComSource(ResumableSource[CheckoutComSourceConfig, CheckoutComResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CHECKOUTCOM
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://access.checkout.com": "Checkout.com authentication failed. Please check your access key ID and secret.",
+ "401 Client Error: Unauthorized for url: https://access.sandbox.checkout.com": "Checkout.com authentication failed. Please check your access key ID and secret (and that they match the selected environment).",
+ "400 Client Error: Bad Request for url: https://access.checkout.com": "Checkout.com authentication failed. Please check your access key ID and secret.",
+ "400 Client Error: Bad Request for url: https://access.sandbox.checkout.com": "Checkout.com authentication failed. Please check your access key ID and secret.",
+ "403 Client Error: Forbidden for url: https://api.checkout.com": "Checkout.com denied access. Please check that your access key has the disputes scope.",
+ "403 Client Error: Forbidden for url: https://api.sandbox.checkout.com": "Checkout.com denied access. Please check that your access key has the disputes scope.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.CHECKOUT_COM,
label="Checkout.com",
+ caption="""Enter your Checkout.com API access keys to pull your disputes data into the PostHog Data warehouse.
+
+Create an access key in the [Checkout.com dashboard](https://dashboard.checkout.com/) under Settings > Access keys with the `disputes` scope. Bulk payment data isn't listable via the API (it ships as report files), so this source currently syncs disputes.""",
iconPath="/static/services/checkout_com.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/checkout-com",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="environment",
+ label="Environment",
+ required=True,
+ defaultValue="production",
+ options=[
+ SourceFieldSelectConfigOption(label="Production", value="production"),
+ SourceFieldSelectConfigOption(label="Sandbox", value="sandbox"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="client_id",
+ label="Access key ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="ack_...",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="client_secret",
+ label="Access key secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: CheckoutComSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Disputes support a server-side `from` filter on last_update.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=True,
+ supports_append=True,
+ incremental_fields=list(_DISPUTES_INCREMENTAL_FIELDS),
+ )
+ for endpoint in ENDPOINTS
+ ]
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+
+ return schemas
+
+ def validate_credentials(
+ self, config: CheckoutComSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_checkout_credentials(config.environment, config.client_id, config.client_secret):
+ return True, None
+
+ return False, "Invalid Checkout.com access keys"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CheckoutComResumeConfig]:
+ return ResumableSourceManager[CheckoutComResumeConfig](inputs, CheckoutComResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: CheckoutComSourceConfig,
+ resumable_source_manager: ResumableSourceManager[CheckoutComResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return checkout_com_source(
+ environment=config.environment,
+ client_id=config.client_id,
+ client_secret=config.client_secret,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ 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/posthog/temporal/data_imports/sources/checkout_com/tests/test_checkout_com.py b/posthog/temporal/data_imports/sources/checkout_com/tests/test_checkout_com.py
new file mode 100644
index 000000000000..dd731d67b7b4
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/checkout_com/tests/test_checkout_com.py
@@ -0,0 +1,195 @@
+from datetime import UTC, date, datetime
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+import requests
+
+from posthog.temporal.data_imports.sources.checkout_com.checkout_com import (
+ PAGE_SIZE,
+ CheckoutComResumeConfig,
+ _format_timestamp,
+ _hosts,
+ checkout_com_source,
+ get_rows,
+ validate_credentials,
+)
+
+_MODULE = "posthog.temporal.data_imports.sources.checkout_com.checkout_com"
+
+
+def _make_manager(resume_state: CheckoutComResumeConfig | 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 _token_response() -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = {"access_token": "the-token", "expires_in": 3600}
+ resp.status_code = 200
+ resp.ok = True
+ return resp
+
+
+def _disputes_response(items: list[dict[str, Any]], total: int | None = None) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = {
+ "limit": PAGE_SIZE,
+ "total_count": total if total is not None else len(items),
+ "data": items,
+ }
+ resp.status_code = 200
+ resp.ok = True
+ return resp
+
+
+class TestHosts:
+ def test_production_and_sandbox_hosts(self):
+ assert _hosts("production")["api"] == "https://api.checkout.com"
+ assert _hosts("sandbox")["auth"] == "https://access.sandbox.checkout.com/connect/token"
+
+ def test_invalid_environment_raises(self):
+ with pytest.raises(ValueError):
+ _hosts("evil")
+
+
+class TestFormatTimestamp:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "2024-01-02T03:04:05Z"),
+ (datetime(2024, 1, 2, 3, 4, 5), "2024-01-02T03:04:05Z"),
+ (date(2024, 1, 2), "2024-01-02T00:00:00Z"),
+ ("2024-01-02T03:04:05Z", "2024-01-02T03:04:05Z"),
+ ],
+ )
+ def test_format_values(self, value, expected):
+ assert _format_timestamp(value) == expected
+
+
+class TestValidateCredentials:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_valid_when_token_mints(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response()
+ assert validate_credentials("production", "ack_id", "secret") is True
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_invalid_when_token_mint_fails(self, mock_session):
+ resp = mock.MagicMock()
+ resp.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=resp)
+ mock_session.return_value.post.return_value = resp
+ assert validate_credentials("production", "ack_id", "secret") is False
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_invalid_on_exception(self, mock_session):
+ mock_session.return_value.post.side_effect = Exception("boom")
+ assert validate_credentials("production", "ack_id", "secret") is False
+
+
+class TestGetRows:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_paginates_via_skip_until_total(self, mock_session):
+ full_page = [{"id": f"dsp_{i}"} for i in range(PAGE_SIZE)]
+ mock_session.return_value.post.return_value = _token_response()
+ mock_session.return_value.get.side_effect = [
+ _disputes_response(full_page, total=PAGE_SIZE + 1),
+ _disputes_response([{"id": "dsp_last"}], total=PAGE_SIZE + 1),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("production", "ack_id", "secret", "disputes", mock.MagicMock(), manager))
+
+ assert len(batches) == 2
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0].skip == PAGE_SIZE
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert parse_qs(urlparse(urls[0]).query)["skip"] == ["0"]
+ assert parse_qs(urlparse(urls[1]).query)["skip"] == [str(PAGE_SIZE)]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_incremental_request_includes_from_filter(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response()
+ mock_session.return_value.get.return_value = _disputes_response([], total=0)
+
+ manager = _make_manager()
+ list(
+ get_rows(
+ "production",
+ "ack_id",
+ "secret",
+ "disputes",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),
+ )
+ )
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert parse_qs(urlparse(url).query)["from"] == ["2024-01-02T00:00:00Z"]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_remints_token_on_401(self, mock_session):
+ expired = mock.MagicMock()
+ expired.status_code = 401
+ expired.ok = False
+ mock_session.return_value.post.return_value = _token_response()
+ mock_session.return_value.get.side_effect = [expired, _disputes_response([{"id": "dsp_1"}])]
+
+ manager = _make_manager()
+ batches = list(get_rows("production", "ack_id", "secret", "disputes", mock.MagicMock(), manager))
+
+ assert batches == [[{"id": "dsp_1"}]]
+ # One mint at start + one re-mint after the 401.
+ assert mock_session.return_value.post.call_count == 2
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_resumes_from_saved_skip(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response()
+ mock_session.return_value.get.return_value = _disputes_response([], total=0)
+
+ manager = _make_manager(CheckoutComResumeConfig(skip=500))
+ list(get_rows("production", "ack_id", "secret", "disputes", mock.MagicMock(), manager))
+
+ url = mock_session.return_value.get.call_args.args[0]
+ assert parse_qs(urlparse(url).query)["skip"] == ["500"]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_sandbox_uses_sandbox_hosts(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response()
+ mock_session.return_value.get.return_value = _disputes_response([], total=0)
+
+ manager = _make_manager()
+ list(get_rows("sandbox", "ack_id", "secret", "disputes", mock.MagicMock(), manager))
+
+ token_url = mock_session.return_value.post.call_args.args[0]
+ assert urlparse(token_url).netloc == "access.sandbox.checkout.com"
+ api_url = mock_session.return_value.get.call_args.args[0]
+ assert urlparse(api_url).netloc == "api.sandbox.checkout.com"
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_empty_response_stops_without_saving_state(self, mock_session):
+ mock_session.return_value.post.return_value = _token_response()
+ mock_session.return_value.get.return_value = _disputes_response([], total=0)
+
+ manager = _make_manager()
+ batches = list(get_rows("production", "ack_id", "secret", "disputes", mock.MagicMock(), manager))
+
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+
+class TestCheckoutComSourceResponse:
+ def test_response_metadata(self):
+ response = checkout_com_source("production", "ack_id", "secret", "disputes", mock.MagicMock(), _make_manager())
+
+ assert response.name == "disputes"
+ assert response.primary_keys == ["id"]
+ # Disputes return newest-first — watermark commits only at run end.
+ assert response.sort_mode == "desc"
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["received_on"]
diff --git a/posthog/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_source.py b/posthog/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_source.py
new file mode 100644
index 000000000000..66cdeaa655e6
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/checkout_com/tests/test_checkout_com_source.py
@@ -0,0 +1,138 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+from posthog.temporal.data_imports.sources.checkout_com.checkout_com import CheckoutComResumeConfig
+from posthog.temporal.data_imports.sources.checkout_com.source import CheckoutComSource
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import CheckoutComSourceConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestCheckoutComSource:
+ def setup_method(self):
+ self.source = CheckoutComSource()
+ self.team_id = 123
+ self.config = CheckoutComSourceConfig(environment="production", client_id="ack_id", client_secret="secret")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.CHECKOUTCOM
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "CheckoutCom"
+ assert config.label == "Checkout.com"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/checkout_com.png"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["environment", "client_id", "client_secret"]
+
+ def test_environment_field_is_a_select_with_default(self):
+ config = self.source.get_source_config
+ env_field = next(f for f in config.fields if f.name == "environment")
+ assert isinstance(env_field, SourceFieldSelectConfig)
+ assert env_field.defaultValue == "production"
+ assert {option.value for option in env_field.options} == {"production", "sandbox"}
+
+ def test_client_secret_field_is_secret_password(self):
+ config = self.source.get_source_config
+ secret_field = next(
+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "client_secret"
+ )
+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD
+ assert secret_field.secret is True
+ assert secret_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://access.checkout.com/connect/token",
+ "400 Client Error: Bad Request for url: https://access.sandbox.checkout.com/connect/token",
+ "403 Client Error: Forbidden for url: https://api.checkout.com/disputes?limit=250",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "500 Server Error for url: https://api.checkout.com/disputes",
+ # Mid-sync 401s on the API host are handled by token re-mint.
+ "401 Client Error: Unauthorized for url: https://api.checkout.com/disputes",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert [s.name for s in schemas] == ["disputes"]
+ assert all(schema.supports_incremental for schema in schemas)
+ assert [f["field"] for f in schemas[0].incremental_fields] == ["last_update"]
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid Checkout.com access keys"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.checkout_com.source.validate_checkout_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ 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 == expected_message
+ mock_validate.assert_called_once_with("production", "ack_id", "secret")
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is CheckoutComResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.checkout_com.source.checkout_com_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_co_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "disputes"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_co_source.assert_called_once()
+ kwargs = mock_co_source.call_args.kwargs
+ assert kwargs["environment"] == "production"
+ assert kwargs["client_id"] == "ack_id"
+ assert kwargs["client_secret"] == "secret"
+ assert kwargs["endpoint"] == "disputes"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-01-02T03:04:05Z"
+
+ @mock.patch("posthog.temporal.data_imports.sources.checkout_com.source.checkout_com_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_co_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "disputes"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_co_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 51450652e35b..a0272e5ef5b0 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -352,7 +352,9 @@ class ChartMogulSourceConfig(config.Config):
@config.config
class CheckoutComSourceConfig(config.Config):
- pass
+ client_id: str
+ client_secret: str
+ environment: Literal["production", "sandbox"] = config.value(default="production")
@config.config