:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement the paymongo import source (#108652)
Tom Owers854ff2b60dc3
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 779d5d109e79..c55325232162 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -554,6 +554,7 @@ the row lists both.| partnerize | HTTP | requests | ✅ || partnerstack | HTTP | requests | ✅ || payfit | HTTP | requests | ✅ |+| paymongo | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || paystack | HTTP | requests + `rest_source.RESTClient` | ✅ || pendo | HTTP | requests | ✅ || perigon | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -1279,7 +1280,6 @@ doesn't conflict with concurrent PRs.- paychex- paylocity- paymob-- paymongo- paypal- peec_ai- pendodiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/webhook_s3.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/webhook_s3.pyindex 42fab212dabe..41e54b66a516 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/webhook_s3.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/webhook_s3.py@@ -1,5 +1,6 @@from __future__ import annotations+import asynciofrom collections.abc import AsyncGenerator, Callablefrom typing import Optional@@ -155,7 +156,7 @@ class WebhookSourceManager:table = self._transform_webhook_table(table)if batch.add(table, path):- merged = finalize_batch(batch.tables)+ merged = await asyncio.to_thread(finalize_batch, batch.tables)await self._logger.adebug("webhook_batch_yield",file_count=len(batch.items),@@ -171,7 +172,7 @@ class WebhookSourceManager:# Yield any remaining rowsif batch:- merged = finalize_batch(batch.tables)+ merged = await asyncio.to_thread(finalize_batch, batch.tables)await self._logger.adebug("webhook_batch_yield",file_count=len(batch.items),diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/paymongo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/paymongo.pyindex f6045b55d372..ea05c7f87a7c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/paymongo.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/paymongo.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass PaymongoSourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paymongo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paymongo/canonical_descriptions.pynew file mode 100644index 000000000000..41914a348063--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paymongo/canonical_descriptions.py@@ -0,0 +1,56 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "payments": {+ "description": "Payment transactions processed through PayMongo.",+ "docs_url": "https://docs.paymongo.com/reference/list-all-payments",+ "columns": {+ "id": "PayMongo payment identifier.",+ "amount": "Payment amount in the currency's smallest unit.",+ "currency": "Payment currency code.",+ "status": "Payment status.",+ "created_at": "Time the payment was created, in UTC.",+ },+ },+ "refunds": {+ "description": "Refunds associated with payments, including partial refunds.",+ "docs_url": "https://docs.paymongo.com/reference/list-all-refunds",+ "columns": {+ "id": "PayMongo refund identifier.",+ "payment_id": "Identifier of the refunded payment.",+ "amount": "Refund amount in the currency's smallest unit.",+ },+ },+ "links": {+ "description": "Shareable checkout links from the Payment Links API.",+ "docs_url": "https://docs.paymongo.com/reference/get_v1-payment-links",+ "columns": {+ "id": "Payment link identifier.",+ "reference_number": "Reference associated with the payment link.",+ "url": "Checkout URL for the payment link.",+ "status": "Whether the link is active or archived.",+ },+ },+ "payouts": {+ "description": "Payouts with amounts, deductions, destination accounts, and transfer status.",+ "docs_url": "https://docs.paymongo.com/reference/getpayoutlist",+ "columns": {+ "id": "PayMongo payout identifier.",+ "net_amount": "Payout amount after deductions.",+ "status": "Current payout status.",+ "created_at": "Time the payout was created, in UTC.",+ },+ },+ "webhooks": {+ "description": "Registered webhook endpoints and their subscribed events, excluding signing secrets.",+ "docs_url": "https://docs.paymongo.com/reference/list-all-webhooks",+ "columns": {+ "id": "Webhook endpoint identifier.",+ "events": "Event types delivered to this endpoint.",+ "url": "Destination URL for webhook deliveries.",+ "status": "Whether the webhook is enabled or disabled.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paymongo/paymongo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paymongo/paymongo.pynew file mode 100644index 000000000000..5c15ed42a631--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paymongo/paymongo.py@@ -0,0 +1,381 @@+import json+from collections.abc import AsyncIterator, Generator, Iterator+from datetime import UTC, datetime+from typing import TYPE_CHECKING, Any+from urllib.parse import quote++from requests import Response+from requests.exceptions import HTTPError++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ ExternalWebhookInfo,+ WebhookCreationResult,+ WebhookDeletionResult,+)+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,+ rest_api_resources,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import HttpBasicAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponseCursorPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ Endpoint,+ EndpointResource,+)+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 schema_for_resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.paymongo.settings import (+ BASE_URL,+ ENDPOINTS,+ PAGE_SIZE,+ WEBHOOK_EVENTS,+)++if TYPE_CHECKING:+ import pyarrow as pa++ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC+++@frozen+class PaymongoResumeConfig:+ paginator_state: dict[str, Any] | None = None+ finished: bool = False+++class PaymongoAuth(HttpBasicAuth):+ def secret_values(self) -> tuple[str, ...]:+ # PayMongo puts the secret in the username; the shared Basic auth redacts the password.+ return (self.username,) if self.username else ()+++class PaymongoCursorPaginator(JSONResponseCursorPaginator):+ def __init__(self, cursor_param: str = "after") -> None:+ super().__init__(cursor_path="data[-1].id", cursor_param=cursor_param)++ def update_state(self, response: Response, data: list[Any] | None = None) -> None:+ previous = self._cursor_value+ super().update_state(response, data)+ if response.json().get("has_more") is False:+ self._has_next_page = False+ elif self.has_next_page and self._cursor_value == previous:+ raise ValueError("PayMongo repeated a pagination cursor. The sync cannot continue safely.")+++def normalize_row(item: dict[str, Any]) -> dict[str, Any]:+ row = {**item.get("attributes", {}), **{key: value for key, value in item.items() if key != "attributes"}}+ row.pop("secret_key", None)+ for field in ("created_at", "updated_at"):+ if isinstance(row.get(field), int | float):+ row[field] = datetime.fromtimestamp(row[field], tz=UTC)+ return row+++def get_resource(name: str) -> EndpointResource:+ settings = schema_for_resource(ENDPOINTS, name)+ endpoint: Endpoint = {"path": settings.path, "data_selector": "data", "data_selector_required": True}+ if settings.pagination == "single":+ # Payment Links documents no cursor; fail instead of silently importing a partial collection.+ endpoint["paginator"] = "single_page"+ endpoint["response_actions"] = [+ {+ "status_code": 200,+ "json_field": "has_more",+ "json_values": [True],+ "action": "raise",+ "message": "PayMongo returned more payment links than its documented list API can retrieve.",+ }+ ]+ elif settings.pagination == "payout":+ endpoint["params"] = {"limit": PAGE_SIZE}+ endpoint["paginator"] = {+ "type": "cursor",+ "cursor_path": "pagination.next_cursor",+ "cursor_param": "after",+ }+ else:+ endpoint["params"] = {"limit": PAGE_SIZE}+ endpoint["paginator"] = PaymongoCursorPaginator()+ if name == "refunds":+ endpoint["params"] = {+ "payment_id": {"type": "resolve", "resource": "payments", "field": "id"},+ "data.attributes.limit": PAGE_SIZE,+ }+ endpoint["paginator"] = PaymongoCursorPaginator(cursor_param="data.attributes.after")+ return {"name": name, "endpoint": endpoint, "data_map": normalize_row, "primary_key": list(settings.primary_keys)}+++def pull_rows(+ api_key: str, inputs: SourceInputs, manager: ResumableSourceManager[PaymongoResumeConfig]+) -> Generator[list[dict[str, Any]]]:+ state = manager.load_state() if manager.can_resume() else None+ if state and state.finished:+ return++ def save_state(paginator_state: dict[str, Any] | None) -> None:+ manager.save_state(PaymongoResumeConfig(paginator_state=paginator_state, finished=paginator_state is None))++ auth = PaymongoAuth(username=api_key, password="")+ with make_tracked_session(redact_values=auth.secret_values(), capture=inputs.schema_name != "webhooks") as session:+ config: RESTAPIConfig = {+ "client": {"base_url": BASE_URL, "auth": auth, "session": session, "request_timeout": 30},+ "resources": [get_resource(inputs.schema_name)],+ }+ initial_state = state.paginator_state if state else None+ if inputs.schema_name == "refunds":+ config["resources"].insert(0, get_resource("payments"))+ resources = rest_api_resources(+ config,+ inputs.team_id,+ inputs.job_id,+ None,+ resume_hook=save_state,+ initial_paginator_state=initial_state,+ )+ resource = next(resource for resource in resources if resource.name == "refunds")+ else:+ resource = rest_api_resource(+ config,+ inputs.team_id,+ inputs.job_id,+ None,+ resume_hook=save_state,+ initial_paginator_state=initial_state,+ )+ yield from resource+ manager.save_state(PaymongoResumeConfig(finished=True))+++def webhook_table(table: "pa.Table", client: "PaymongoClient") -> "pa.Table":+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import ( # noqa: PLC0415 - keeps Arrow off the source registration path+ table_from_py_list,+ )++ latest: dict[str, dict[str, Any]] = {}+ refunded: set[str] = set()+ for event in table.to_pylist():+ if isinstance(event["data"], str):+ event["data"] = json.loads(event["data"])+ attributes = event["data"]["attributes"]+ item = attributes["data"]+ is_refund = item["type"] == "refund"+ if is_refund:+ refund_attributes = item.get("attributes")+ payment_id = refund_attributes.get("payment_id") if isinstance(refund_attributes, dict) else None+ else:+ payment_id = item.get("id")+ created_at = attributes.get("created_at")+ if not payment_id or created_at is None:+ continue+ if is_refund:+ refunded.add(payment_id)+ previous = latest.get(payment_id)+ if previous is None or created_at >= previous["data"]["attributes"]["created_at"]:+ latest[payment_id] = event+ rows = []+ for payment_id, event in latest.items():+ # Refund events can contain only the refund, so retrieve the payment's current snapshot.+ item = (+ client.request("GET", f"payments/{quote(payment_id, safe='')}").json()["data"]+ if payment_id in refunded+ else event["data"]["attributes"]["data"]+ )+ rows.append(normalize_row(item))+ return table_from_py_list(rows)+++def paymongo_source(+ api_key: str,+ inputs: SourceInputs,+ manager: ResumableSourceManager[PaymongoResumeConfig],+ webhook_manager: WebhookSourceManager,+) -> SourceResponse:+ settings = schema_for_resource(ENDPOINTS, inputs.schema_name)++ async def items() -> AsyncIterator[Any]:+ if inputs.schema_name == "payments" and await webhook_manager.webhook_enabled():+ async for table in webhook_manager.get_items(+ table_transformer=lambda table: webhook_table(table, PaymongoClient(api_key))+ ):+ yield table+ else:+ for page in pull_rows(api_key, inputs, manager):+ yield page++ return SourceResponse(+ name=inputs.schema_name,+ items=items,+ primary_keys=list(settings.primary_keys),+ partition_keys=[settings.partition_key],+ partition_mode="datetime",+ partition_format="month",+ sort_mode=None,+ supports_resume=settings.pagination != "single",+ )+++class PaymongoClient:+ def __init__(self, api_key: str) -> None:+ self.auth = PaymongoAuth(username=api_key, password="")++ def request(self, method: str, path: str, **kwargs: Any) -> Response:+ with make_tracked_session(redact_values=self.auth.secret_values(), capture=False) as session:+ response = session.request(method, BASE_URL + path, auth=self.auth, timeout=30, **kwargs)+ response.raise_for_status()+ return response++ def validate_credentials(self, schema_name: str | None) -> tuple[bool, str | None]:+ name = schema_name or "payments"+ endpoint = schema_for_resource(ENDPOINTS, name)+ path = "payments" if name == "refunds" else endpoint.path+ try:+ response = self.request("GET", path, params={} if endpoint.pagination == "single" else {"limit": 1})+ if name == "refunds" and response.json()["data"]:+ self.request(+ "GET",+ "refunds",+ params={"data.attributes.payment_id": response.json()["data"][0]["id"], "data.attributes.limit": 1},+ )+ except HTTPError as error:+ status = error.response.status_code if error.response is not None else None+ if status == 401:+ return (+ False,+ "PayMongo rejected your secret API key. Check the key in your PayMongo dashboard and reconnect.",+ )+ if status == 403:+ if schema_name is None:+ return True, None+ return False, "Your PayMongo API key cannot access this table. Check your account permissions."+ raise+ return True, None++ def webhooks(self) -> Iterator[dict[str, Any]]:+ client = RESTClient(base_url=BASE_URL, auth=self.auth, capture=False, request_timeout=30)+ try:+ for page in client.paginate(+ "webhooks",+ params={"limit": PAGE_SIZE},+ paginator=PaymongoCursorPaginator(),+ data_selector="data",+ data_selector_required=True,+ ):+ yield from page+ finally:+ client.session.close()++ def create_webhook(self, webhook_url: str) -> WebhookCreationResult:+ existing = next((item for item in self.webhooks() if item["attributes"]["url"] == webhook_url), None)+ if existing:+ identifier = quote(existing["id"], safe="")+ self.request(+ "PUT", f"webhooks/{identifier}", json={"data": {"attributes": {"events": list(WEBHOOK_EVENTS)}}}+ )+ response = self.request("POST", f"webhooks/{identifier}/enable")+ else:+ response = self.request(+ "POST", "webhooks", json={"data": {"attributes": {"url": webhook_url, "events": list(WEBHOOK_EVENTS)}}}+ )+ secret = response.json()["data"]["attributes"].get("secret_key")+ return WebhookCreationResult(+ success=True,+ extra_inputs={"signing_secret": secret} if secret else {},+ pending_inputs=[] if secret else ["signing_secret"],+ )++ def delete_webhook(self, webhook_url: str) -> WebhookDeletionResult:+ for item in self.webhooks():+ if item["attributes"]["url"] == webhook_url:+ self.request("POST", f"webhooks/{quote(item['id'], safe='')}/disable")+ return WebhookDeletionResult(success=True)++ def get_external_webhook_info(self, webhook_url: str) -> ExternalWebhookInfo:+ for item in self.webhooks():+ attributes = item["attributes"]+ if attributes["url"] == webhook_url:+ return ExternalWebhookInfo(+ exists=True, url=webhook_url, enabled_events=attributes["events"], status=attributes["status"]+ )+ return ExternalWebhookInfo(exists=False)+++def webhook_template() -> "HogFunctionTemplateDC":+ from posthog.cdp.templates.hog_function_template import ( # noqa: PLC0415 - keeps the template dependencies off the source registration path+ HogFunctionTemplateDC,+ )++ return HogFunctionTemplateDC(+ status="alpha",+ free=False,+ type="warehouse_source_webhook",+ id="template-warehouse-source-paymongo",+ name="PayMongo warehouse source webhook",+ description="Receive PayMongo payment updates for the data warehouse",+ icon_url="/static/services/paymongo.png",+ category=["Data warehouse"],+ code_language="hog",+ code="""+if (request.method != 'POST') {+ return {'httpResponse': {'status': 405, 'body': 'Method not allowed'}}+}+if (empty(inputs.signing_secret)) {+ return {'httpResponse': {'status': 200, 'body': 'Signing secret not configured, delivery dropped'}, 'appMetric': 'missing_credential'}+}+let header := request.headers['paymongo-signature']+if (empty(header)) {+ return {'httpResponse': {'status': 401, 'body': 'Missing signature'}}+}+let parts := {}+for (let part in splitByString(',', header)) {+ let pair := splitByString('=', trim(part))+ if (length(pair) == 2) { parts[pair[1]] := pair[2] }+}+let signature := request.body.data.attributes.livemode ? parts.li : parts.te+if (empty(parts.t) or empty(signature)) {+ return {'httpResponse': {'status': 401, 'body': 'Missing signature'}}+}+let expected := sha256HmacChain([inputs.signing_secret, concat(parts.t, '.', request.stringBody)], 'hex')+if (expected != signature) {+ return {'httpResponse': {'status': 401, 'body': 'Bad signature'}}+}+let age := toInt(toUnixTimestamp(now())) - toInt(parts.t)+if (age > 300 or age < -300) {+ return {'httpResponse': {'status': 401, 'body': 'Timestamp outside tolerance'}}+}+let attributes := request.body.data.attributes+if (not (attributes.data.type in ['payment', 'refund']) or not (attributes.type in ['payment.paid', 'payment.failed', 'payment.refunded', 'payment.refund.updated'])) {+ return {'httpResponse': {'status': 200, 'body': 'Event skipped'}}+}+let schemaId := inputs.schema_mapping?.['payment']+if (empty(schemaId)) { return {'httpResponse': {'status': 200, 'body': 'Table not selected'}} }+produceToWarehouseWebhooks(request.body, schemaId)+""",+ inputs_schema=[+ {"type": "string", "key": "signing_secret", "label": "Signing secret", "required": True, "secret": True},+ {+ "type": "json",+ "key": "schema_mapping",+ "label": "Schema mapping",+ "required": True,+ "hidden": True,+ "secret": False,+ },+ {+ "type": "string",+ "key": "source_id",+ "label": "Source ID",+ "required": True,+ "hidden": True,+ "secret": False,+ },+ ],+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paymongo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paymongo/settings.pynew file mode 100644index 000000000000..bebc6bded30a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paymongo/settings.py@@ -0,0 +1,29 @@+from typing import Literal++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.types import IncrementalField++BASE_URL = "https://api.paymongo.com/v1/"+PAGE_SIZE = 10+WEBHOOK_EVENTS = ("payment.paid", "payment.failed", "payment.refunded", "payment.refund.updated")+++@frozen+class PaymongoEndpoint:+ path: str+ pagination: Literal["after", "payout", "single"] = "after"+ primary_keys: tuple[str, ...] = ("id",)+ partition_key: str = "created_at"+++ENDPOINTS = {+ "payments": PaymongoEndpoint(path="payments"),+ "refunds": PaymongoEndpoint(path="refunds?data.attributes.payment_id={payment_id}"),+ "links": PaymongoEndpoint(path="payment_links", pagination="single"),+ "payouts": PaymongoEndpoint(path="payouts", pagination="payout"),+ "webhooks": PaymongoEndpoint(path="webhooks"),+}++# Creation-time filters cannot capture later refunds or status changes, and remain unverified.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paymongo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paymongo/source.pyindex 9b37c6568717..3d2bcb191c5e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/paymongo/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paymongo/source.py@@ -1,16 +1,67 @@-from typing import cast+from typing import TYPE_CHECKING, cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from requests.exceptions import HTTPError++from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ ExternalWebhookInfo,+ FieldType,+ ResumableSource,+ WebhookCreationResult,+ WebhookDeletionResult,+ WebhookSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.paymongo import (PaymongoSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.paymongo.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.paymongo.paymongo import (+ PaymongoClient,+ PaymongoResumeConfig,+ paymongo_source,+ webhook_template,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.paymongo.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+if TYPE_CHECKING:+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC+++def webhook_error(error: HTTPError) -> str:+ status = error.response.status_code if error.response is not None else "unknown"+ return (+ f"PayMongo could not update the webhook (HTTP {status}). Check your API key and webhook settings, then retry."+ )+@SourceRegistry.register-class PaymongoSource(SimpleSource[PaymongoSourceConfig]):+class PaymongoSource(ResumableSource[PaymongoSourceConfig, PaymongoResumeConfig], WebhookSource[PaymongoSourceConfig]):+ lists_tables_without_credentials = True+ api_docs_url = "https://docs.paymongo.com/reference/list-all-payments"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PAYMONGO@@ -22,6 +73,105 @@ class PaymongoSource(SimpleSource[PaymongoSourceConfig]):category=DataWarehouseSourceCategory.PAYMENTS___BILLING,label="PayMongo",iconPath="/static/services/paymongo.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/paymongo",+ caption="Import payments, refunds, payment links, payouts, and webhook settings from PayMongo.",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="Secret API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ secret=True,+ placeholder="",+ caption="Copy your secret API key from your [PayMongo dashboard](https://dashboard.paymongo.com). Test keys import test data; live keys import live data.",+ )+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,+ webhookSetupCaption="PostHog registers payment webhooks automatically. For manual setup, add the URL below in PayMongo, select payment.paid, payment.failed, payment.refunded, and payment.refund.updated, then copy the signing secret below. Disconnecting disables the webhook in PayMongo.",+ webhookFields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="signing_secret",+ label="Signing secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ secret=True,+ placeholder="",+ )+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized": "PayMongo rejected your API key. Replace the invalid or expired key and reconnect.",+ "403 Client Error: Forbidden": "Your PayMongo API key cannot access this table. Check your account permissions.",+ }++ def get_schemas(+ self,+ config: PaymongoSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, supports_webhooks=("payments",))++ def validate_credentials(+ self, config: PaymongoSourceConfig, team_id: int, schema_name: str | None = None, api_version: str | None = None+ ) -> tuple[bool, str | None]:+ return PaymongoClient(config.api_key).validate_credentials(schema_name)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PaymongoResumeConfig]:+ return ResumableSourceManager(inputs, PaymongoResumeConfig)++ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:+ return WebhookSourceManager(inputs, inputs.logger)++ @property+ def webhook_template(self) -> "HogFunctionTemplateDC":+ return webhook_template()++ @property+ def webhook_resource_map(self) -> dict[str, str]:+ return {"payments": "payment"}++ def create_webhook(+ self, config: PaymongoSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> WebhookCreationResult:+ try:+ return PaymongoClient(config.api_key).create_webhook(webhook_url)+ except HTTPError as error:+ return WebhookCreationResult(success=False, error=webhook_error(error))++ def delete_webhook(+ self, config: PaymongoSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> WebhookDeletionResult:+ try:+ return PaymongoClient(config.api_key).delete_webhook(webhook_url)+ except HTTPError as error:+ return WebhookDeletionResult(success=False, error=webhook_error(error))++ def get_external_webhook_info(+ self, config: PaymongoSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> ExternalWebhookInfo:+ return PaymongoClient(config.api_key).get_external_webhook_info(webhook_url)++ def source_for_pipeline(+ self,+ config: PaymongoSourceConfig,+ resumable_source_manager: ResumableSourceManager[PaymongoResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return paymongo_source(+ config.api_key, inputs, resumable_source_manager, self.get_webhook_source_manager(inputs))diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paymongo/tests/test_paymongo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paymongo/tests/test_paymongo.pynew file mode 100644index 000000000000..73a38ee804d3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paymongo/tests/test_paymongo.py@@ -0,0 +1,372 @@+import json+import asyncio+from collections.abc import AsyncIterable, Iterator+from datetime import UTC, datetime+from http import HTTPStatus+from typing import Any, cast+from urllib.parse import parse_qs, urlsplit++import pytest+from unittest.mock import AsyncMock, MagicMock, patch++import pyarrow as pa+from requests import PreparedRequest, Response+from requests.exceptions import HTTPError++from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_list+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.paymongo.paymongo import (+ PaymongoClient,+ PaymongoResumeConfig,+ paymongo_source,+ pull_rows,+ webhook_table,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.paymongo.source import PaymongoSource+++def source_inputs(name: str = "payments") -> SourceInputs:+ return SourceInputs(+ schema_name=name,+ schema_id="schema",+ source_id="source",+ team_id=1,+ should_use_incremental_field=False,+ db_incremental_field_last_value=1900000000,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id="job",+ logger=MagicMock(),+ reset_pipeline=False,+ )+++def row(identifier: str, **attributes: Any) -> dict[str, Any]:+ return {"id": identifier, "type": "payment", "attributes": {"created_at": 1700000000, **attributes}}+++def manager() -> MagicMock:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ return manager+++def http() -> Iterator[MagicMock]:+ with patch("requests.sessions.Session.send") as send:+ yield send+++def respond(http: MagicMock, bodies: list[dict[str, Any]], statuses: list[int] | None = None) -> list[PreparedRequest]:+ sent: list[PreparedRequest] = []+ responses = iter(zip(statuses or [200] * len(bodies), bodies))++ def send(request: PreparedRequest, **kwargs: Any) -> Response:+ status, body = next(responses)+ sent.append(request)+ response = Response()+ response.status_code = status+ response.reason = HTTPStatus(status).phrase+ response.url = request.url or ""+ response.request = request+ response.headers["Content-Type"] = "application/json"+ response.headers["Retry-After"] = "0"+ response._content = json.dumps(body).encode()+ return response++ http.side_effect = send+ return sent+++ "name,metadata",+ [+ ("payments", {"has_more": True}),+ ("webhooks", {"has_more": True}),+ ("payouts", {"pagination": {"next_cursor": "pay_1"}}),+ ],+)+def test_pagination_auth_normalization_and_checkpoint(+ http: MagicMock, manager: MagicMock, name: str, metadata: dict[str, Any]+) -> None:+ sent = respond(+ http,+ [+ {"data": [row("pay_1", secret_key="fake-signing-secret")], **metadata},+ {"data": [row("pay_2")], "has_more": False},+ ],+ )+ pages = pull_rows("sk_test_fake", source_inputs(name), manager)+ first = next(pages)+ assert first == [{"id": "pay_1", "type": "payment", "created_at": datetime.fromtimestamp(1700000000, UTC)}]+ manager.save_state.assert_not_called()+ assert next(pages)[0]["id"] == "pay_2"+ assert manager.save_state.call_args.args[0].paginator_state == {"cursor": "pay_1"}+ assert list(pages) == []+ assert manager.save_state.call_args.args[0].finished+ assert sent[0].headers["Authorization"] == "Basic c2tfdGVzdF9mYWtlOg=="+ assert parse_qs(urlsplit(sent[0].url or "").query) == {"limit": ["10"]}+ assert parse_qs(urlsplit(sent[1].url or "").query) == {"limit": ["10"], "after": ["pay_1"]}++[email protected]("finished", [False, True])+def test_resume_skips_completed_pages(http: MagicMock, manager: MagicMock, finished: bool) -> None:+ manager.can_resume.return_value = True+ manager.load_state.return_value = PaymongoResumeConfig(paginator_state={"cursor": "pay_saved"}, finished=finished)+ sent = respond(http, [{"data": [], "has_more": False}])+ assert list(pull_rows("fake", source_inputs(), manager)) == []+ if finished:+ assert sent == []+ else:+ assert parse_qs(urlsplit(sent[0].url or "").query)["after"] == ["pay_saved"]+++def test_refund_fanout_keeps_payment_and_child_cursors(http: MagicMock, manager: MagicMock) -> None:+ sent = respond(+ http,+ [+ {"data": [row("pay_one"), row("pay_two")], "has_more": False},+ {"data": [row("ref_one", payment_id="pay_one")], "has_more": True},+ {"data": [row("ref_two", payment_id="pay_one")], "has_more": False},+ {"data": [row("ref_three", payment_id="pay_two")], "has_more": False},+ ],+ )+ rows = [item for page in pull_rows("fake", source_inputs("refunds"), manager) for item in page]+ assert [item["id"] for item in rows] == ["ref_one", "ref_two", "ref_three"]+ queries = [parse_qs(urlsplit(request.url or "").query) for request in sent[1:]]+ assert queries == [+ {"data.attributes.payment_id": ["pay_one"], "data.attributes.limit": ["10"]},+ {+ "data.attributes.payment_id": ["pay_one"],+ "data.attributes.limit": ["10"],+ "data.attributes.after": ["ref_one"],+ },+ {"data.attributes.payment_id": ["pay_two"], "data.attributes.limit": ["10"]},+ ]+++ "body,message", [({"data": [row("pay_same")], "has_more": True}, "repeated"), ({"unexpected": []}, "data")]+)+def test_broken_pagination_fails_instead_of_looping_or_truncating(+ http: MagicMock, manager: MagicMock, body: dict[str, Any], message: str+) -> None:+ respond(http, [body, body])+ with pytest.raises(ValueError, match=message):+ list(pull_rows("fake", source_inputs(), manager))++[email protected]("has_more", [False, True])+def test_links_use_new_api_and_reject_truncation(http: MagicMock, manager: MagicMock, has_more: bool) -> None:+ sent = respond(http, [{"data": [{"id": "link_one", "created_at": "2026-01-01T00:00:00Z"}], "has_more": has_more}])+ if has_more:+ with pytest.raises(ValueError, match="more payment links"):+ list(pull_rows("fake", source_inputs("links"), manager))+ else:+ assert next(pull_rows("fake", source_inputs("links"), manager))[0]["id"] == "link_one"+ assert sent[0].url == "https://api.paymongo.com/v1/payment_links"+++ "status,schema,valid,message",+ [+ (200, None, True, None),+ (401, None, False, "rejected"),+ (403, None, True, None),+ (403, "payouts", False, "permissions"),+ ],+)+def test_credential_probe_status_mapping(+ http: MagicMock, status: int, schema: str | None, valid: bool, message: str | None+) -> None:+ sent = respond(http, [{"data": []}], [status])+ result, error = PaymongoClient("fake").validate_credentials(schema)+ assert result is valid+ if message:+ assert error is not None and message in error+ else:+ assert error is None+ assert parse_qs(urlsplit(sent[0].url or "").query) == {"limit": ["1"]}++[email protected]("status", [401, 403, 429, 500])+def test_pull_retries_only_transient_statuses(http: MagicMock, manager: MagicMock, status: int) -> None:+ respond(http, [{}, {"data": [], "has_more": False}], [status, 200])+ if status in (401, 403):+ with pytest.raises(HTTPError) as error:+ list(pull_rows("fake", source_inputs(), manager))+ assert any(pattern in str(error.value) for pattern in PaymongoSource().get_non_retryable_errors())+ assert http.call_count == 1+ else:+ assert list(pull_rows("fake", source_inputs(), manager)) == []+ assert http.call_count == 2+++def test_webhook_management_reuses_matching_url_and_disables_only_owned_endpoint(http: MagicMock) -> None:+ url = "https://example.com/hook"+ hook = {+ "id": "hook_one",+ "attributes": {"url": url, "status": "disabled", "events": [], "secret_key": "fake-secret"},+ }+ unrelated = {"id": "hook_other", "attributes": {"url": "https://example.com/other"}}+ sent = respond(+ http,+ [+ {"data": [unrelated, hook], "has_more": False},+ {},+ {"data": hook},+ {"data": [unrelated, hook], "has_more": False},+ {},+ ],+ )+ client = PaymongoClient("fake")+ result = client.create_webhook(url)+ assert result.success and result.extra_inputs == {"signing_secret": "fake-secret"}+ assert client.delete_webhook(url).success+ assert [(r.method, urlsplit(r.url or "").path) for r in sent] == [+ ("GET", "/v1/webhooks"),+ ("PUT", "/v1/webhooks/hook_one"),+ ("POST", "/v1/webhooks/hook_one/enable"),+ ("GET", "/v1/webhooks"),+ ("POST", "/v1/webhooks/hook_one/disable"),+ ]++[email protected]("secret", ["fake-signing-secret", None])+def test_webhook_creation_saves_or_requests_signing_secret(http: MagicMock, secret: str | None) -> None:+ sent = respond(http, [{"data": [], "has_more": False}, {"data": {"attributes": {"secret_key": secret}}}])+ result = PaymongoClient("fake").create_webhook("https://example.com/hook")+ assert result.success+ assert result.pending_inputs == ([] if secret else ["signing_secret"])+ assert result.extra_inputs == ({"signing_secret": secret} if secret else {})+ assert json.loads(sent[1].body or b"")["data"]["attributes"]["url"] == "https://example.com/hook"+++def test_webhook_batch_deduplicates_and_matches_poll_shape() -> None:+ def event(timestamp: int, status: str) -> dict[str, Any]:+ return {"data": {"attributes": {"created_at": timestamp, "data": row("pay_one", status=status)}}}++ result = webhook_table(+ table_from_py_list([event(30, "refunded"), event(10, "paid"), event(30, "refunded")]), PaymongoClient("fake")+ )+ assert result.to_pylist() == [+ {+ "created_at": datetime.fromtimestamp(1700000000, UTC),+ "status": "refunded",+ "id": "pay_one",+ "type": "payment",+ }+ ]+++def test_webhook_batch_skips_events_without_required_identifiers_or_timestamp() -> None:+ def event(item: dict[str, Any], created_at: int | None = 1700000100) -> dict[str, Any]:+ attributes: dict[str, Any] = {"data": item}+ if created_at is not None:+ attributes["created_at"] = created_at+ return {"data": {"attributes": attributes}}++ malformed = [+ event({"type": "payment"}),+ event({"id": "pay_one", "type": "payment"}, created_at=None),+ event({"id": "ref_one", "type": "refund", "attributes": {}}),+ ]++ assert webhook_table(table_from_py_list(malformed), PaymongoClient("fake")).num_rows == 0+++def test_webhook_sync_does_not_poll(http: MagicMock, manager: MagicMock) -> None:+ webhook_manager = MagicMock()+ webhook_manager.webhook_enabled = AsyncMock(return_value=True)++ async def batches(**kwargs: Any) -> Any:+ yield pa.Table.from_pylist([{"id": "pay_one"}])++ webhook_manager.get_items = batches+ response = paymongo_source("fake", source_inputs(), manager, webhook_manager)++ async def collect() -> list[Any]:+ items = cast(AsyncIterable[Any], response.items())+ return [table async for table in items]++ assert asyncio.run(collect())[0].to_pylist() == [{"id": "pay_one"}]+ http.assert_not_called()+++def test_refund_resume_continues_child_cursor(http: MagicMock, manager: MagicMock) -> None:+ parents = {"data": [row("pay_one"), row("pay_two")], "has_more": False}+ respond(+ http, [parents, {"data": [row("ref_one")], "has_more": True}, {"data": [row("ref_two")], "has_more": False}]+ )+ pages = pull_rows("fake", source_inputs("refunds"), manager)+ assert next(pages)[0]["id"] == "ref_one"+ assert next(pages)[0]["id"] == "ref_two"+ saved = manager.save_state.call_args.args[0]+ pages.close()+ manager.can_resume.return_value = True+ manager.load_state.return_value = saved+ sent = respond(+ http, [parents, {"data": [row("ref_two")], "has_more": False}, {"data": [row("ref_three")], "has_more": False}]+ )+ assert [item["id"] for page in pull_rows("fake", source_inputs("refunds"), manager) for item in page] == [+ "ref_two",+ "ref_three",+ ]+ assert parse_qs(urlsplit(sent[1].url or "").query)["data.attributes.after"] == ["ref_one"]+++def test_refund_webhooks_refresh_payment_once(http: MagicMock) -> None:+ event = {+ "data": {+ "attributes": {+ "created_at": 1700000100,+ "data": {"id": "ref_one", "type": "refund", "attributes": {"payment_id": "pay_one"}},+ }+ }+ }+ sent = respond(http, [{"data": row("pay_one", status="refunded", refunds=[{"id": "ref_one"}])}])+ table = webhook_table(table_from_py_list([event, event]), PaymongoClient("fake"))+ assert table.to_pylist()[0]["status"] == "refunded"+ assert json.loads(table.to_pylist()[0]["refunds"]) == [{"id": "ref_one"}]+ assert [request.url for request in sent] == ["https://api.paymongo.com/v1/payments/pay_one"]++[email protected]("exists", [True, False])+def test_webhook_info_finds_matching_url_on_later_page(http: MagicMock, exists: bool) -> None:+ url = "https://example.com/hook"+ hook = {+ "id": "hook_one",+ "attributes": {"url": url, "events": ["payment.paid"], "status": "enabled", "secret_key": "fake-secret"},+ }+ respond(+ http,+ [+ {"data": [{"id": "hook_other", "attributes": {"url": "https://example.com/other"}}], "has_more": True},+ {"data": [hook] if exists else [], "has_more": False},+ ],+ )+ info = PaymongoClient("fake").get_external_webhook_info(url)+ assert info.exists is exists+ if exists:+ assert info.status == "enabled"+ assert info.enabled_events == ["payment.paid"]+ assert "fake-secret" not in repr(info)++[email protected]("status", [200, 403])+def test_refund_permissions_probe_child_endpoint(http: MagicMock, status: int) -> None:+ sent = respond(http, [{"data": [row("pay_one")]}, {"data": []}], [200, status])+ valid, message = PaymongoClient("fake").validate_credentials("refunds")+ assert valid is (status == 200)+ if status == 200:+ assert message is None+ else:+ assert message is not None and "permissions" in message+ assert urlsplit(sent[1].url or "").path == "/v1/refunds"+ assert parse_qs(urlsplit(sent[1].url or "").query) == {+ "data.attributes.payment_id": ["pay_one"],+ "data.attributes.limit": ["1"],+ }diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paymongo/tests/test_paymongo_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paymongo/tests/test_paymongo_source.pynew file mode 100644index 000000000000..59cc544842da--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paymongo/tests/test_paymongo_source.py@@ -0,0 +1,119 @@+import hmac+import json+import time+import hashlib+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++from requests import Response++from posthog.cdp.validation import compile_hog++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import UnknownResourceError+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.paymongo import (+ PaymongoSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.paymongo.source import PaymongoSource++from common.hogvm.python.execute import execute_bytecode++[email protected]("operation", ["create_webhook", "delete_webhook"])+def test_webhook_failures_do_not_expose_vendor_body(operation: str) -> None:+ response = Response()+ response.status_code = 403+ response.reason = "Forbidden"+ response.url = "https://api.paymongo.com/v1/webhooks"+ response._content = b'{"errors": [{"detail": "fake-sensitive-response"}]}'+ with patch("requests.sessions.Session.send", return_value=response):+ result = getattr(PaymongoSource(), operation)(+ PaymongoSourceConfig(api_key="fake"), "https://example.com/hook", 1+ )+ assert not result.success+ assert "HTTP 403" in result.error+ assert "fake-sensitive-response" not in result.error+++def test_unknown_schema_fails_before_network() -> None:+ with patch("requests.sessions.Session.send") as send:+ with pytest.raises(UnknownResourceError, match="missing_table"):+ PaymongoSource().validate_credentials(PaymongoSourceConfig(api_key="fake"), 1, schema_name="missing_table")+ send.assert_not_called()++[email protected](scope="module")+def webhook_bytecode() -> list[Any]:+ return compile_hog(PaymongoSource().webhook_template.code, "warehouse_source_webhook")++[email protected]("livemode", [True, False])+ "case,expected_status",+ [+ ("valid", None),+ ("refund", None),+ ("bad_signature", 401),+ ("expired", 401),+ ("wrong_mode", 401),+ ("missing_secret", 200),+ ("unselected", 200),+ ("unrelated", 200),+ ("get", 405),+ ],+)+def test_webhook_verifies_signature_and_routes_payment(+ webhook_bytecode: list[Any], livemode: bool, case: str, expected_status: int | None+) -> None:+ source = PaymongoSource()+ timestamp = str(int(time.time()) - (600 if case == "expired" else 0))+ payload: dict[str, Any] = {+ "data": {+ "id": "evt_fake",+ "attributes": {+ "type": "payment.paid" if case != "unrelated" else "unrelated.created",+ "livemode": livemode,+ "created_at": int(timestamp),+ "data": {"id": "pay_fake", "type": "payment", "attributes": {"status": "paid"}},+ },+ }+ }+ if case == "refund":+ payload["data"]["attributes"]["type"] = "payment.refund.updated"+ payload["data"]["attributes"]["data"] = {+ "id": "ref_fake",+ "type": "refund",+ "attributes": {"payment_id": "pay_fake"},+ }+ raw = json.dumps(payload)+ signature = hmac.new(b"fake-secret", f"{timestamp}.{raw}".encode(), hashlib.sha256).hexdigest()+ if case == "bad_signature":+ signature = "bad"+ mode = "li" if livemode else "te"+ if case == "wrong_mode":+ mode = "te" if livemode else "li"+ producer = MagicMock()+ result = execute_bytecode(+ webhook_bytecode,+ globals={+ "request": {+ "method": "GET" if case == "get" else "POST",+ "body": payload,+ "stringBody": raw,+ "headers": {"paymongo-signature": f"t={timestamp},{mode}={signature}"},+ },+ "inputs": {+ "signing_secret": "" if case == "missing_secret" else "fake-secret",+ "schema_mapping": {}+ if case == "unselected"+ else {source.webhook_mapping_key("payments"): "schema_fake"},+ },+ },+ functions={"produceToWarehouseWebhooks": producer},+ ).result+ if expected_status is None:+ producer.assert_called_once_with(payload, "schema_fake")+ else:+ producer.assert_not_called()+ assert result["httpResponse"]["status"] == expected_status