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 paystack import source (#65629)

Tom Owers9f085a7bcda9
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 62615d0ad2e7..6b3444abab15 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -155,6 +155,7 @@ the row lists both.
| optimizely | HTTP | requests | ✅ |
| pagerduty | HTTP | requests | ✅ |
| pandadoc | HTTP | requests | ✅ |
+| paystack | HTTP | requests + `rest_source.RESTClient` | ✅ |
| pendo | HTTP | requests | ✅ |
| personio | HTTP | requests | ✅ |
| pingdom | HTTP | requests | ✅ |
@@ -546,7 +547,6 @@ doesn't conflict with concurrent PRs.
- payfit
- paylocity
- paypal
-- paystack
- pendo
- pennylane
- perigon
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 775461ce6ff3..a4412b755336 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -2276,7 +2276,7 @@ class PaylocitySourceConfig(config.Config):
@config.config
class PaystackSourceConfig(config.Config):
- pass
+ secret_api_key: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/paystack/canonical_descriptions.py b/posthog/temporal/data_imports/sources/paystack/canonical_descriptions.py
new file mode 100644
index 000000000000..fec867853b83
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/paystack/canonical_descriptions.py
@@ -0,0 +1,178 @@
+"""Canonical, documentation-sourced descriptions for Paystack endpoints and columns.
+
+Sourced from the official Paystack API reference (https://paystack.com/docs/api/). Keyed by the
+schema names in `settings.py` `PAYSTACK_ENDPOINTS`, which match the `ExternalDataSchema.name` of a
+synced Paystack table. Coverage is partial — any endpoint, column, or table-level description absent
+here falls back to LLM enrichment.
+"""
+
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Transactions": {
+ "description": "Payments collected on your integration, including status, amount, channel and customer.",
+ "docs_url": "https://paystack.com/docs/api/transaction/",
+ "columns": {
+ "id": "Unique integer identifier for the transaction.",
+ "reference": "Unique transaction reference you or Paystack assigned.",
+ "amount": "Amount of the transaction in the smallest currency unit (e.g. kobo for NGN).",
+ "currency": "Currency the transaction was carried out in (e.g. NGN, GHS, ZAR, USD).",
+ "status": "Transaction outcome — typically 'success', 'failed' or 'abandoned'.",
+ "channel": "Channel the payment was made through (e.g. card, bank, ussd, apple_pay).",
+ "gateway_response": "Human-readable response from the payment gateway.",
+ "paid_at": "Time the transaction was paid, as an ISO 8601 timestamp.",
+ "created_at": "Time the transaction was created, as an ISO 8601 timestamp.",
+ "createdAt": "Time the transaction was created, as an ISO 8601 timestamp.",
+ "customer": "The customer object associated with the transaction.",
+ },
+ },
+ "Customers": {
+ "description": "Customers created on your integration that you can charge and attach subscriptions to.",
+ "docs_url": "https://paystack.com/docs/api/customer/",
+ "columns": {
+ "id": "Unique integer identifier for the customer.",
+ "customer_code": "Paystack customer code (format CUS_xxxxxxxx) used across the API.",
+ "email": "Customer's email address.",
+ "first_name": "Customer's first name.",
+ "last_name": "Customer's last name.",
+ "phone": "Customer's phone number.",
+ "createdAt": "Time the customer was created, as an ISO 8601 timestamp.",
+ },
+ },
+ "Subscriptions": {
+ "description": "Recurring billing arrangements linking a customer to a plan.",
+ "docs_url": "https://paystack.com/docs/api/subscription/",
+ "columns": {
+ "id": "Unique integer identifier for the subscription.",
+ "subscription_code": "Paystack subscription code (format SUB_xxxxxxxx).",
+ "status": "Subscription status (e.g. active, non-renewing, cancelled, complete).",
+ "amount": "Amount billed per cycle, in the smallest currency unit.",
+ "next_payment_date": "Date the next charge is scheduled, as an ISO 8601 timestamp.",
+ "createdAt": "Time the subscription was created, as an ISO 8601 timestamp.",
+ },
+ },
+ "Plans": {
+ "description": "Recurring billing templates defining amount, interval and currency.",
+ "docs_url": "https://paystack.com/docs/api/plan/",
+ "columns": {
+ "id": "Unique integer identifier for the plan.",
+ "plan_code": "Paystack plan code (format PLN_xxxxxxxx).",
+ "name": "Name of the plan.",
+ "amount": "Amount charged per interval, in the smallest currency unit.",
+ "interval": "Billing interval (e.g. daily, weekly, monthly, annually).",
+ "currency": "Currency of the plan.",
+ "createdAt": "Time the plan was created, as an ISO 8601 timestamp.",
+ },
+ },
+ "Products": {
+ "description": "Products in the Paystack Storefront that customers can purchase.",
+ "docs_url": "https://paystack.com/docs/api/product/",
+ "columns": {
+ "id": "Unique integer identifier for the product.",
+ "product_code": "Paystack product code (format PROD_xxxxxxxx).",
+ "name": "Name of the product.",
+ "price": "Price of the product, in the smallest currency unit.",
+ "currency": "Currency of the product price.",
+ "createdAt": "Time the product was created, as an ISO 8601 timestamp.",
+ },
+ },
+ "PaymentRequests": {
+ "description": "Payment requests (formerly invoices) issued to customers for collection.",
+ "docs_url": "https://paystack.com/docs/api/payment-request/",
+ "columns": {
+ "id": "Unique integer identifier for the payment request.",
+ "request_code": "Paystack payment request code (format PRQ_xxxxxxxx).",
+ "amount": "Amount requested, in the smallest currency unit.",
+ "currency": "Currency of the request.",
+ "status": "Status of the payment request (e.g. pending, success).",
+ "due_date": "Date payment is due, as an ISO 8601 timestamp.",
+ "createdAt": "Time the payment request was created, as an ISO 8601 timestamp.",
+ },
+ },
+ "Settlements": {
+ "description": "Payouts of collected funds settled to your bank account or subaccount.",
+ "docs_url": "https://paystack.com/docs/api/settlement/",
+ "columns": {
+ "id": "Unique integer identifier for the settlement.",
+ "total_amount": "Total amount settled, in the smallest currency unit.",
+ "status": "Settlement status (e.g. success, pending).",
+ "settled_by": "Identifier of the entity that processed the settlement.",
+ "settlement_date": "Date the settlement was made, as an ISO 8601 timestamp.",
+ "createdAt": "Time the settlement was created, as an ISO 8601 timestamp.",
+ },
+ },
+ "Refunds": {
+ "description": "Refunds issued against transactions, full or partial.",
+ "docs_url": "https://paystack.com/docs/api/refund/",
+ "columns": {
+ "id": "Unique integer identifier for the refund.",
+ "amount": "Amount refunded, in the smallest currency unit.",
+ "currency": "Currency of the refund.",
+ "status": "Refund status (e.g. pending, processed, failed).",
+ "transaction": "Identifier of the transaction being refunded.",
+ "createdAt": "Time the refund was created, as an ISO 8601 timestamp.",
+ },
+ },
+ "Transfers": {
+ "description": "Money sent from your integration to transfer recipients.",
+ "docs_url": "https://paystack.com/docs/api/transfer/",
+ "columns": {
+ "id": "Unique integer identifier for the transfer.",
+ "transfer_code": "Paystack transfer code (format TRF_xxxxxxxx).",
+ "amount": "Amount transferred, in the smallest currency unit.",
+ "currency": "Currency of the transfer.",
+ "status": "Transfer status (e.g. pending, success, failed).",
+ "reference": "Unique reference for the transfer.",
+ "createdAt": "Time the transfer was created, as an ISO 8601 timestamp.",
+ },
+ },
+ "TransferRecipients": {
+ "description": "Recipients (bank accounts or cards) you can send transfers to.",
+ "docs_url": "https://paystack.com/docs/api/transfer-recipient/",
+ "columns": {
+ "id": "Unique integer identifier for the transfer recipient.",
+ "recipient_code": "Paystack recipient code (format RCP_xxxxxxxx).",
+ "type": "Recipient type (e.g. nuban, mobile_money, basa).",
+ "name": "Name of the recipient.",
+ "currency": "Currency the recipient is settled in.",
+ "createdAt": "Time the recipient was created, as an ISO 8601 timestamp.",
+ },
+ },
+ "Disputes": {
+ "description": "Chargebacks and disputes raised against your transactions.",
+ "docs_url": "https://paystack.com/docs/api/dispute/",
+ "columns": {
+ "id": "Unique integer identifier for the dispute.",
+ "status": "Dispute status (e.g. awaiting-merchant-feedback, resolved).",
+ "currency": "Currency of the disputed transaction.",
+ "transaction": "The transaction being disputed.",
+ "resolution": "Resolution outcome of the dispute, when settled.",
+ "createdAt": "Time the dispute was created, as an ISO 8601 timestamp.",
+ },
+ },
+ "Subaccounts": {
+ "description": "Subaccounts used to split settlement of payments to other bank accounts.",
+ "docs_url": "https://paystack.com/docs/api/subaccount/",
+ "columns": {
+ "id": "Unique integer identifier for the subaccount.",
+ "subaccount_code": "Paystack subaccount code (format ACCT_xxxxxxxx).",
+ "business_name": "Business name registered on the subaccount.",
+ "percentage_charge": "Default percentage of transactions allocated to the subaccount.",
+ "settlement_bank": "Bank the subaccount settles to.",
+ "createdAt": "Time the subaccount was created, as an ISO 8601 timestamp.",
+ },
+ },
+ "PaymentPages": {
+ "description": "Hosted payment pages customers can use to pay you.",
+ "docs_url": "https://paystack.com/docs/api/page/",
+ "columns": {
+ "id": "Unique integer identifier for the payment page.",
+ "slug": "URL slug of the payment page.",
+ "name": "Name of the payment page.",
+ "amount": "Fixed amount for the page, in the smallest currency unit (may be null).",
+ "currency": "Currency of the page.",
+ "active": "Whether the payment page is currently active.",
+ "createdAt": "Time the payment page was created, as an ISO 8601 timestamp.",
+ },
+ },
+}
diff --git a/posthog/temporal/data_imports/sources/paystack/paystack.py b/posthog/temporal/data_imports/sources/paystack/paystack.py
new file mode 100644
index 000000000000..f565c6638f65
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/paystack/paystack.py
@@ -0,0 +1,151 @@
+import dataclasses
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+from requests import Request, Response
+
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.rest_source import RESTAPIConfig, rest_api_resource
+from posthog.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator
+from posthog.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.paystack.settings import PAYSTACK_ENDPOINTS
+
+PAYSTACK_BASE_URL = "https://api.paystack.co"
+# Paystack caps list pages at 100 records (default 50).
+PAGE_SIZE = 100
+
+
+class PaystackResumeConfig:
+ next_page: int
+
+
+class PaystackPaginator(BasePaginator):
+ """Page-number pagination over Paystack list endpoints.
+
+ Paystack wraps list responses as ``{"status", "message", "data": [...], "meta": {...}}`` and
+ paginates with ``page`` / ``perPage``. ``meta.pageCount`` reports the total number of pages, so
+ we walk ``page`` from 1 until it exceeds ``pageCount``. When ``meta`` is missing (or carries no
+ usable ``pageCount``) we fall back to stopping on the first empty page, which is Paystack's own
+ recommended termination signal for offset pagination.
+ """
+
+ def __init__(self, page: int = 1) -> None:
+ super().__init__()
+ self._page = page
+
+ def init_request(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+ request.params["perPage"] = PAGE_SIZE
+ request.params["page"] = self._page
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ meta: dict[str, Any] = {}
+ try:
+ body = response.json()
+ if isinstance(body, dict) and isinstance(body.get("meta"), dict):
+ meta = body["meta"]
+ except Exception:
+ meta = {}
+
+ page_count = meta.get("pageCount")
+ if isinstance(page_count, int):
+ if self._page >= page_count:
+ self._has_next_page = False
+ return
+ elif not data:
+ self._has_next_page = False
+ return
+
+ self._page += 1
+ self._has_next_page = True
+
+ def update_request(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+ request.params["page"] = self._page
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ if self._has_next_page:
+ return {"next_page": self._page}
+ return None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ next_page = state.get("next_page")
+ if next_page is not None:
+ self._page = int(next_page)
+ self._has_next_page = True
+
+
+def get_resource(name: str) -> EndpointResource:
+ config = PAYSTACK_ENDPOINTS[name]
+ return {
+ "name": name,
+ "table_name": name.lower(),
+ # Full refresh: Paystack offers no verified server-side updated-at filter, so we replace
+ # the table each sync rather than risk a corrupt incremental watermark.
+ "write_disposition": "replace",
+ "endpoint": {
+ "data_selector": "data",
+ "path": config.path,
+ },
+ "table_format": "delta",
+ }
+
+
+def paystack_source(
+ secret_api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[PaystackResumeConfig],
+):
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": PAYSTACK_BASE_URL,
+ "auth": {
+ "type": "bearer",
+ "token": secret_api_key,
+ },
+ "paginator": PaystackPaginator(),
+ },
+ "resource_defaults": {
+ "write_disposition": "replace",
+ },
+ "resources": [get_resource(endpoint)],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {"next_page": resume_config.next_page}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Persist only when there's a next page to resume to; the Redis TTL handles cleanup.
+ if state and state.get("next_page"):
+ resumable_source_manager.save_state(PaystackResumeConfig(next_page=int(state["next_page"])))
+
+ return rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ # Full refresh — no incremental cursor.
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+
+def validate_credentials(secret_api_key: str) -> bool:
+ """Cheap authenticated probe. A Paystack secret key is account-wide (no per-resource scopes),
+ so a 200 on a 1-row transaction list confirms the key is genuine."""
+ query = urlencode({"perPage": 1})
+ res = make_tracked_session(redact_values=(secret_api_key,)).get(
+ f"{PAYSTACK_BASE_URL}/transaction?{query}",
+ headers={"Authorization": f"Bearer {secret_api_key}"},
+ timeout=10,
+ )
+ return res.status_code == 200
diff --git a/posthog/temporal/data_imports/sources/paystack/settings.py b/posthog/temporal/data_imports/sources/paystack/settings.py
new file mode 100644
index 000000000000..9722890112ca
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/paystack/settings.py
@@ -0,0 +1,37 @@
+from dataclasses import dataclass
+
+
+@dataclass
+class PaystackEndpointConfig:
+ # API path relative to https://api.paystack.co (e.g. "/transaction").
+ path: str
+ # Paystack list resources expose a globally-unique integer `id`, unique across the account.
+ primary_key: str = "id"
+
+
+# Paystack list endpoints. Each returns a `{"status", "message", "data": [...], "meta": {...}}`
+# envelope and paginates by `page` / `perPage` (default 50, max 100). The schema name (dict key)
+# is what `get_schemas` reports and what the synced warehouse table is named after.
+#
+# All endpoints are full-refresh today. Paystack list endpoints return rows newest-first
+# (descending by creation time) and expose no documented stable ascending sort parameter, and the
+# `from` / `to` creation-time filters could not be verified against the live API (no test
+# credentials). Declaring incremental on unverified ordering risks watermark corruption, so
+# incremental sync is intentionally deferred — see the note in `paystack.py`.
+PAYSTACK_ENDPOINTS: dict[str, PaystackEndpointConfig] = {
+ "Transactions": PaystackEndpointConfig(path="/transaction"),
+ "Customers": PaystackEndpointConfig(path="/customer"),
+ "Subscriptions": PaystackEndpointConfig(path="/subscription"),
+ "Plans": PaystackEndpointConfig(path="/plan"),
+ "Products": PaystackEndpointConfig(path="/product"),
+ "PaymentRequests": PaystackEndpointConfig(path="/paymentrequest"),
+ "Settlements": PaystackEndpointConfig(path="/settlement"),
+ "Refunds": PaystackEndpointConfig(path="/refund"),
+ "Transfers": PaystackEndpointConfig(path="/transfer"),
+ "TransferRecipients": PaystackEndpointConfig(path="/transferrecipient"),
+ "Disputes": PaystackEndpointConfig(path="/dispute"),
+ "Subaccounts": PaystackEndpointConfig(path="/subaccount"),
+ "PaymentPages": PaystackEndpointConfig(path="/page"),
+}
+
+ENDPOINTS = tuple(PAYSTACK_ENDPOINTS.keys())
diff --git a/posthog/temporal/data_imports/sources/paystack/source.py b/posthog/temporal/data_imports/sources/paystack/source.py
index fabcd7e9b929..44272e064cfb 100644
--- a/posthog/temporal/data_imports/sources/paystack/source.py
+++ b/posthog/temporal/data_imports/sources/paystack/source.py
@@ -1,31 +1,127 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-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.common.base import FieldType, ResumableSource
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
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 PaystackSourceConfig
+from posthog.temporal.data_imports.sources.paystack.paystack import (
+ PaystackResumeConfig,
+ paystack_source,
+ validate_credentials as validate_paystack_credentials,
+)
+from posthog.temporal.data_imports.sources.paystack.settings import ENDPOINTS, PAYSTACK_ENDPOINTS
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class PaystackSource(SimpleSource[PaystackSourceConfig]):
+class PaystackSource(ResumableSource[PaystackSourceConfig, PaystackResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.PAYSTACK
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.paystack.co": "Paystack authentication failed. Please check that your secret API key is valid.",
+ "403 Client Error: Forbidden for url: https://api.paystack.co": "Paystack denied access. Please check that your secret API key has the required permissions.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from posthog.temporal.data_imports.sources.paystack.canonical_descriptions import CANONICAL_DESCRIPTIONS
+
+ return CANONICAL_DESCRIPTIONS
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.PAYSTACK,
category=DataWarehouseSourceCategory.PAYMENTS___BILLING,
label="Paystack",
+ caption="""Enter your Paystack secret API key to pull your Paystack data into the PostHog Data warehouse.
+
+You can find your secret key (it starts with `sk_live_` or `sk_test_`) under **Settings → API Keys & Webhooks** in your [Paystack dashboard](https://dashboard.paystack.com/#/settings/developers). The key has read access to your integration's data.""",
iconPath="/static/services/paystack.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/paystack",
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="secret_api_key",
+ label="Secret API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="sk_live_...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: PaystackSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ 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: PaystackSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_paystack_credentials(config.secret_api_key):
+ return True, None
+
+ return False, "Invalid Paystack secret API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PaystackResumeConfig]:
+ return ResumableSourceManager[PaystackResumeConfig](inputs, PaystackResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: PaystackSourceConfig,
+ resumable_source_manager: ResumableSourceManager[PaystackResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ resource = paystack_source(
+ secret_api_key=config.secret_api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ )
+ return SourceResponse(
+ name=resource.name,
+ items=lambda: resource,
+ primary_keys=[PAYSTACK_ENDPOINTS[inputs.schema_name].primary_key],
+ column_hints=resource.column_hints,
)
diff --git a/posthog/temporal/data_imports/sources/paystack/tests/test_paystack.py b/posthog/temporal/data_imports/sources/paystack/tests/test_paystack.py
new file mode 100644
index 000000000000..72280c7e1829
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/paystack/tests/test_paystack.py
@@ -0,0 +1,215 @@
+import json
+from collections.abc import Iterable
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Request, Response
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.paystack.paystack import (
+ PAGE_SIZE,
+ PaystackPaginator,
+ PaystackResumeConfig,
+ get_resource,
+ paystack_source,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.paystack.settings import ENDPOINTS
+
+
+def _meta(page: int, page_count: int) -> dict[str, Any]:
+ return {"total": page_count * PAGE_SIZE, "perPage": PAGE_SIZE, "page": page, "pageCount": page_count}
+
+
+def _response(body: dict[str, Any], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+class TestPaystackPaginator:
+ def test_initial_state(self) -> None:
+ paginator = PaystackPaginator()
+ # BasePaginator starts has_next_page=True so the first request fires; the page begins at 1.
+ assert paginator._page == 1
+ assert paginator.has_next_page is True
+
+ def test_init_request_sets_page_and_per_page(self) -> None:
+ paginator = PaystackPaginator()
+ request = Request(method="GET", url="https://api.paystack.co/transaction")
+ paginator.init_request(request)
+ assert request.params["page"] == 1
+ assert request.params["perPage"] == PAGE_SIZE
+
+ def test_update_state_has_more_pages_via_page_count(self) -> None:
+ paginator = PaystackPaginator()
+ paginator.update_state(_response({"data": [{"id": 1}], "meta": _meta(page=1, page_count=3)}), [{"id": 1}])
+ assert paginator.has_next_page is True
+ assert paginator._page == 2
+
+ def test_update_state_stops_on_last_page_via_page_count(self) -> None:
+ paginator = PaystackPaginator(page=3)
+ paginator.update_state(_response({"data": [{"id": 9}], "meta": _meta(page=3, page_count=3)}), [{"id": 9}])
+ assert paginator.has_next_page is False
+
+ def test_update_state_stops_on_empty_page_without_meta(self) -> None:
+ # No usable meta: fall back to Paystack's documented "stop when a page is empty" signal.
+ paginator = PaystackPaginator()
+ paginator.update_state(_response({"data": []}), [])
+ assert paginator.has_next_page is False
+
+ def test_update_state_advances_without_meta_when_page_full(self) -> None:
+ paginator = PaystackPaginator()
+ paginator.update_state(_response({"data": [{"id": 1}]}), [{"id": 1}])
+ assert paginator.has_next_page is True
+ assert paginator._page == 2
+
+ def test_update_request_targets_current_page(self) -> None:
+ paginator = PaystackPaginator()
+ paginator.update_state(_response({"data": [{"id": 1}], "meta": _meta(page=1, page_count=2)}), [{"id": 1}])
+ request = Request(method="GET", url="https://api.paystack.co/transaction")
+ paginator.update_request(request)
+ assert request.params["page"] == 2
+
+ def test_get_resume_state_returns_next_page_when_more(self) -> None:
+ paginator = PaystackPaginator()
+ paginator.update_state(_response({"data": [{"id": 1}], "meta": _meta(page=1, page_count=2)}), [{"id": 1}])
+ assert paginator.get_resume_state() == {"next_page": 2}
+
+ def test_get_resume_state_returns_none_on_terminal_page(self) -> None:
+ paginator = PaystackPaginator(page=2)
+ paginator.update_state(_response({"data": [{"id": 1}], "meta": _meta(page=2, page_count=2)}), [{"id": 1}])
+ assert paginator.get_resume_state() is None
+
+ def test_set_resume_state_round_trip(self) -> None:
+ paginator = PaystackPaginator()
+ paginator.set_resume_state({"next_page": 7})
+ assert paginator._page == 7
+ assert paginator.has_next_page is True
+ # init_request must target the resumed page.
+ request = Request(method="GET", url="https://api.paystack.co/transaction")
+ paginator.init_request(request)
+ assert request.params["page"] == 7
+
+ def test_set_resume_state_coerces_to_int(self) -> None:
+ paginator = PaystackPaginator()
+ paginator.set_resume_state({"next_page": "4"})
+ assert paginator._page == 4
+
+ def test_set_resume_state_ignores_missing_page(self) -> None:
+ paginator = PaystackPaginator()
+ paginator.set_resume_state({})
+ assert paginator._page == 1
+
+
+class TestPaystackResources:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_get_resource_shape(self, endpoint: str) -> None:
+ resource = get_resource(endpoint)
+ assert resource["name"] == endpoint
+ assert resource["table_name"] == endpoint.lower()
+ # Full refresh — no verified server-side updated-at filter on Paystack.
+ assert resource["write_disposition"] == "replace"
+ assert resource["table_format"] == "delta"
+ endpoint_config = cast(dict[str, Any], resource["endpoint"])
+ assert endpoint_config["data_selector"] == "data"
+ assert endpoint_config["path"].startswith("/")
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ ("status_code", "expected"),
+ [(200, True), (401, False), (403, False), (500, False)],
+ )
+ def test_status_mapping(self, status_code: int, expected: bool) -> None:
+ with patch("posthog.temporal.data_imports.sources.paystack.paystack.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response({"status": True}, status_code=status_code)
+ assert validate_credentials("sk_test_x") is expected
+
+ def test_sends_bearer_header(self) -> None:
+ with patch("posthog.temporal.data_imports.sources.paystack.paystack.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response({"status": True})
+ validate_credentials("sk_test_secret")
+ _, kwargs = mock_session.return_value.get.call_args
+ assert kwargs["headers"]["Authorization"] == "Bearer sk_test_secret"
+
+
+class TestPaystackSourceResumeBehavior:
+ """End-to-end resume behaviour of ``paystack_source`` via ``rest_api_resource``."""
+
+ def _drive(
+ self, endpoint: str, manager: MagicMock, responses: list[Response]
+ ) -> tuple[MagicMock, list[dict[str, Any]]]:
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ return next(response_iter)
+
+ with patch(
+ "posthog.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ resource = paystack_source(
+ secret_api_key="sk_test_x",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ )
+ list(cast(Iterable[Any], resource))
+ return mock_session, sent_params
+
+ def test_fresh_run_saves_next_page_after_each_non_terminal_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _response({"data": [{"id": 1}], "meta": _meta(page=1, page_count=3)}),
+ _response({"data": [{"id": 2}], "meta": _meta(page=2, page_count=3)}),
+ _response({"data": [{"id": 3}], "meta": _meta(page=3, page_count=3)}),
+ ]
+ _, sent_params = self._drive("Transactions", manager, responses)
+
+ assert [p.get("page") for p in sent_params] == [1, 2, 3]
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [PaystackResumeConfig(next_page=2), PaystackResumeConfig(next_page=3)]
+
+ def test_resume_seeds_paginator_with_saved_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = PaystackResumeConfig(next_page=5)
+
+ responses = [_response({"data": [{"id": 50}], "meta": _meta(page=5, page_count=5)})]
+ _, sent_params = self._drive("Customers", manager, responses)
+
+ assert [p.get("page") for p in sent_params] == [5]
+ manager.load_state.assert_called_once()
+
+ def test_terminal_single_page_does_not_save_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_response({"data": [{"id": 1}], "meta": _meta(page=1, page_count=1)})]
+ self._drive("Plans", manager, responses)
+
+ manager.save_state.assert_not_called()
+
+ def test_does_not_load_state_when_cannot_resume(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_response({"data": [{"id": 1}], "meta": _meta(page=1, page_count=1)})]
+ self._drive("Refunds", manager, responses)
+
+ manager.load_state.assert_not_called()
diff --git a/posthog/temporal/data_imports/sources/paystack/tests/test_paystack_source.py b/posthog/temporal/data_imports/sources/paystack/tests/test_paystack_source.py
new file mode 100644
index 000000000000..9866bcebcb3e
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/paystack/tests/test_paystack_source.py
@@ -0,0 +1,135 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import PaystackSourceConfig
+from posthog.temporal.data_imports.sources.paystack.paystack import PaystackResumeConfig
+from posthog.temporal.data_imports.sources.paystack.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.paystack.source import PaystackSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestPaystackSource:
+ def setup_method(self):
+ self.source = PaystackSource()
+ self.team_id = 123
+ self.config = PaystackSourceConfig(secret_api_key="sk_test_x")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.PAYSTACK
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Paystack"
+ assert config.label == "Paystack"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.iconPath == "/static/services/paystack.png"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["secret_api_key"]
+
+ def test_secret_api_key_field_is_secret_password(self):
+ config = self.source.get_source_config
+ key_field = next(
+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "secret_api_key"
+ )
+ assert key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert key_field.secret is True
+ assert key_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.paystack.co/transaction?perPage=1",
+ "403 Client Error: Forbidden for url: https://api.paystack.co/customer",
+ ],
+ )
+ 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_vendor_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.paystack.co/transaction",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_vendor_error for key in non_retryable_errors)
+
+ def test_get_schemas_covers_all_endpoints(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ def test_all_schemas_are_full_refresh(self):
+ # Paystack exposes no verified server-side updated-at filter, so every endpoint is full refresh.
+ for schema in self.source.get_schemas(self.config, self.team_id):
+ assert schema.supports_incremental is False
+ assert schema.supports_append is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Transactions"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "Transactions"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_canonical_descriptions_cover_every_endpoint(self):
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions.keys()) == set(ENDPOINTS)
+ for entry in descriptions.values():
+ assert entry["description"]
+ assert entry["docs_url"].startswith("https://paystack.com/docs/api/")
+ assert "id" in entry["columns"]
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid Paystack secret API key"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.paystack.source.validate_paystack_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(self.config.secret_api_key)
+
+ 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 PaystackResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.paystack.source.paystack_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_paystack_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "Transactions"
+ inputs.team_id = 456
+ inputs.job_id = "job-1"
+ manager = mock.MagicMock()
+
+ response = self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_paystack_source.assert_called_once()
+ kwargs = mock_paystack_source.call_args.kwargs
+ assert kwargs["secret_api_key"] == "sk_test_x"
+ assert kwargs["endpoint"] == "Transactions"
+ assert kwargs["team_id"] == 456
+ assert kwargs["job_id"] == "job-1"
+ assert kwargs["resumable_source_manager"] is manager
+ assert response.primary_keys == ["id"]