: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 razorpay import source (#72647)
Tom Owers344ffb0ac1ca
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex f5bc2a4c1be7..a1935938edec 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -436,6 +436,7 @@ the row lists both.| ramp | HTTP | requests | ✅ || rapid7_insightvm | HTTP | requests | ✅ || raygun | HTTP | requests | ✅ |+| razorpay | HTTP | requests + `rest_source.RESTClient` | ✅ || recharge | HTTP | requests | ✅ || recruitee | HTTP | requests | ✅ || reddit_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -875,7 +876,6 @@ doesn't conflict with concurrent PRs.- railz- rapid7_insightvm- raygun-- razorpay- rb2b- rd_station_marketing- recreationdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/razorpay.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/razorpay.pyindex e76b50afac84..952e046fbef2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/razorpay.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/razorpay.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass RazorpaySourceConfig(config.Config):- pass+ key_id: str+ key_secret: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/razorpay/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/razorpay/canonical_descriptions.pynew file mode 100644index 000000000000..0a5720ab9434--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/razorpay/canonical_descriptions.py@@ -0,0 +1,191 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Customers": {+ "description": "A customer of your business, identified by name, email, and contact number, that payments and orders can be associated with.",+ "docs_url": "https://razorpay.com/docs/api/customers/",+ "columns": {+ "id": "Unique identifier of the customer.",+ "name": "Name of the customer.",+ "email": "Email address of the customer.",+ "contact": "Contact number of the customer.",+ "gstin": "GST identification number of the customer.",+ "notes": "Key-value pairs of additional information about the customer.",+ "created_at": "UNIX timestamp (seconds) when the customer was created.",+ },+ },+ "Disputes": {+ "description": "A chargeback or dispute raised against a payment, including its phase, status, and the evidence submitted.",+ "docs_url": "https://razorpay.com/docs/api/disputes/",+ "columns": {+ "id": "Unique identifier of the dispute.",+ "payment_id": "Identifier of the payment against which the dispute was created.",+ "amount": "Disputed amount, in the smallest currency sub-unit (e.g. paise).",+ "currency": "ISO currency code of the disputed amount.",+ "amount_deducted": "Amount deducted from your account balance for the dispute.",+ "reason_code": "Network reason code for the dispute.",+ "respond_by": "UNIX timestamp by which a response must be submitted.",+ "status": "Status of the dispute, such as open, under_review, won, lost, or closed.",+ "phase": "Phase of the dispute, such as fraud, retrieval, chargeback, pre_arbitration, or arbitration.",+ "created_at": "UNIX timestamp (seconds) when the dispute was created.",+ },+ },+ "Invoices": {+ "description": "An invoice issued to a customer, carrying line items, amounts, payment status, and the linked order and payment.",+ "docs_url": "https://razorpay.com/docs/api/payments/invoices/",+ "columns": {+ "id": "Unique identifier of the invoice.",+ "entity": "Entity name, here invoice.",+ "type": "Type of entity, here invoice.",+ "customer_id": "Identifier of the customer the invoice was issued to.",+ "order_id": "Identifier of the order associated with the invoice.",+ "payment_id": "Identifier of the payment made against the invoice.",+ "status": "Status of the invoice, such as draft, issued, partially_paid, paid, cancelled, expired, or deleted.",+ "amount": "Total amount of the invoice, in the smallest currency sub-unit.",+ "amount_paid": "Amount paid against the invoice so far.",+ "amount_due": "Amount remaining to be paid.",+ "currency": "ISO currency code of the invoice amount.",+ "issued_at": "UNIX timestamp when the invoice was issued.",+ "paid_at": "UNIX timestamp when the invoice was paid.",+ "created_at": "UNIX timestamp (seconds) when the invoice was created.",+ },+ },+ "Items": {+ "description": "A reusable item (product or service) with a name, price, and currency that can be added to invoices and subscriptions.",+ "docs_url": "https://razorpay.com/docs/api/payments/items/",+ "columns": {+ "id": "Unique identifier of the item.",+ "name": "Name of the item.",+ "description": "Description of the item.",+ "amount": "Price of the item, in the smallest currency sub-unit.",+ "currency": "ISO currency code the item is billed in.",+ "active": "Whether the item is active or inactive.",+ "created_at": "UNIX timestamp (seconds) when the item was created.",+ },+ },+ "Orders": {+ "description": "An order created to bind payments to a purchase intent; a payment is only considered complete against its order.",+ "docs_url": "https://razorpay.com/docs/api/orders/",+ "columns": {+ "id": "Unique identifier of the order.",+ "amount": "Order amount, in the smallest currency sub-unit (e.g. paise).",+ "amount_paid": "Amount paid against the order so far.",+ "amount_due": "Amount remaining to be paid against the order.",+ "currency": "ISO currency code of the order amount.",+ "receipt": "Your internal receipt number for the order.",+ "status": "Status of the order: created, attempted, or paid.",+ "attempts": "Number of payment attempts made against the order.",+ "offer_id": "Identifier of the offer applied to the order.",+ "notes": "Key-value pairs of additional information about the order.",+ "created_at": "UNIX timestamp (seconds) when the order was created.",+ },+ },+ "Payments": {+ "description": "A payment made by a customer, covering every payment method (card, UPI, netbanking, wallet) and its full lifecycle status.",+ "docs_url": "https://razorpay.com/docs/api/payments/",+ "columns": {+ "id": "Unique identifier of the payment.",+ "amount": "Payment amount, in the smallest currency sub-unit (e.g. paise).",+ "currency": "ISO currency code of the payment amount.",+ "status": "Status of the payment: created, authorized, captured, refunded, or failed.",+ "order_id": "Identifier of the order the payment was made against.",+ "invoice_id": "Identifier of the invoice the payment was made against, if any.",+ "method": "Payment method used, such as card, netbanking, wallet, emi, or upi.",+ "amount_refunded": "Amount refunded from the payment, in the smallest currency sub-unit.",+ "refund_status": "Refund status of the payment: null, partial, or full.",+ "captured": "Whether the payment has been captured.",+ "email": "Email address of the customer who made the payment.",+ "contact": "Contact number of the customer who made the payment.",+ "customer_id": "Identifier of the customer who made the payment.",+ "fee": "Fee charged by Razorpay for the payment, including tax.",+ "tax": "Tax charged on the fee.",+ "error_code": "Error code for a failed payment.",+ "error_description": "Description of the error for a failed payment.",+ "notes": "Key-value pairs of additional information about the payment.",+ "created_at": "UNIX timestamp (seconds) when the payment was created.",+ },+ },+ "Plans": {+ "description": "A billing plan defining the amount and billing cycle used to create subscriptions.",+ "docs_url": "https://razorpay.com/docs/api/payments/plans/",+ "columns": {+ "id": "Unique identifier of the plan.",+ "period": "Billing period unit: daily, weekly, monthly, or yearly.",+ "interval": "Number of billing periods between charges.",+ "item": "The item (name, amount, currency) billed by the plan.",+ "notes": "Key-value pairs of additional information about the plan.",+ "created_at": "UNIX timestamp (seconds) when the plan was created.",+ },+ },+ "Refunds": {+ "description": "A full or partial refund issued against a payment, with its processing status and speed.",+ "docs_url": "https://razorpay.com/docs/api/refunds/",+ "columns": {+ "id": "Unique identifier of the refund.",+ "payment_id": "Identifier of the payment that was refunded.",+ "amount": "Refund amount, in the smallest currency sub-unit.",+ "currency": "ISO currency code of the refund amount.",+ "status": "Status of the refund: pending, processed, or failed.",+ "speed_requested": "Refund speed requested: normal or optimum.",+ "speed_processed": "Refund speed at which the refund was actually processed.",+ "batch_id": "Identifier of the batch the refund was created in, if any.",+ "receipt": "Your internal receipt number for the refund.",+ "notes": "Key-value pairs of additional information about the refund.",+ "created_at": "UNIX timestamp (seconds) when the refund was created.",+ },+ },+ "Settlements": {+ "description": "A settlement of captured payments transferred to your bank account, with fees, tax, and the bank UTR reference.",+ "docs_url": "https://razorpay.com/docs/api/settlements/",+ "columns": {+ "id": "Unique identifier of the settlement.",+ "amount": "Settlement amount transferred to your bank account, in the smallest currency sub-unit.",+ "status": "Status of the settlement: created, processed, or failed.",+ "fees": "Fees deducted for the settlement.",+ "tax": "Tax deducted for the settlement.",+ "utr": "Unique transaction reference number from the bank for the settlement.",+ "created_at": "UNIX timestamp (seconds) when the settlement was created.",+ },+ },+ "Subscriptions": {+ "description": "A recurring billing relationship between a customer and a plan, with its cycle counts and lifecycle status.",+ "docs_url": "https://razorpay.com/docs/api/payments/subscriptions/",+ "columns": {+ "id": "Unique identifier of the subscription.",+ "plan_id": "Identifier of the plan the subscription is based on.",+ "customer_id": "Identifier of the customer who owns the subscription.",+ "status": "Status of the subscription, such as created, authenticated, active, paused, halted, cancelled, completed, or expired.",+ "quantity": "Number of units of the plan billed per cycle.",+ "total_count": "Total number of billing cycles for the subscription.",+ "paid_count": "Number of billing cycles already paid.",+ "remaining_count": "Number of billing cycles remaining.",+ "current_start": "UNIX timestamp when the current billing cycle started.",+ "current_end": "UNIX timestamp when the current billing cycle ends.",+ "charge_at": "UNIX timestamp of the next charge.",+ "start_at": "UNIX timestamp when the subscription starts.",+ "end_at": "UNIX timestamp when the subscription ends.",+ "notes": "Key-value pairs of additional information about the subscription.",+ "created_at": "UNIX timestamp (seconds) when the subscription was created.",+ },+ },+ "VirtualAccounts": {+ "description": "A Smart Collect virtual account (bank account number, VPA, or QR code) created to receive payments from a customer.",+ "docs_url": "https://razorpay.com/docs/api/payments/smart-collect/",+ "columns": {+ "id": "Unique identifier of the virtual account.",+ "name": "Name of the virtual account.",+ "status": "Status of the virtual account: active or closed.",+ "description": "Description of the virtual account.",+ "amount_expected": "Amount expected to be paid into the virtual account.",+ "amount_paid": "Amount paid into the virtual account so far.",+ "customer_id": "Identifier of the customer the virtual account belongs to.",+ "receivers": "Bank account, VPA, or QR code receivers configured on the virtual account.",+ "close_by": "UNIX timestamp when the virtual account is scheduled to close.",+ "closed_at": "UNIX timestamp when the virtual account was closed.",+ "notes": "Key-value pairs of additional information about the virtual account.",+ "created_at": "UNIX timestamp (seconds) when the virtual account was created.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/razorpay/razorpay.py b/products/warehouse_sources/backend/temporal/data_imports/sources/razorpay/razorpay.pynew file mode 100644index 000000000000..9530897ffaf6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/razorpay/razorpay.py@@ -0,0 +1,159 @@+import dataclasses+from typing import Any, Optional++from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ OffsetPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.razorpay.settings import (+ API_BASE_URL,+ ENDPOINT_CONFIGS,+ PAGE_SIZE,+)++# Razorpay has no updated-at filter, so incremental syncs window on created_at only. Re-read a+# trailing overlap each run to catch status transitions on recently created records (e.g.+# authorized -> captured payments, settlement state changes); the merge on `id` dedupes the+# overlap. Older mutations still need an occasional full refresh.+INCREMENTAL_LOOKBACK_SECONDS = 3 * 24 * 60 * 60++# The API rejects `from` values before 2000-01-01 with a 400.+MIN_FROM_TIMESTAMP = 946_684_800+++class RazorpayResumeConfig:+ skip: int+++def build_from_param(db_incremental_field_last_value: Optional[Any]) -> Optional[int]:+ """UNIX-seconds `from` bound for an incremental sync, or None for a full walk."""+ if db_incremental_field_last_value is None:+ return None++ try:+ watermark = int(db_incremental_field_last_value)+ except (TypeError, ValueError):+ return None++ return max(watermark - INCREMENTAL_LOOKBACK_SECONDS, MIN_FROM_TIMESTAMP)+++def _build_paginator() -> OffsetPaginator:+ # Collection responses carry `count` as the page's item count (not a grand total), so+ # termination is a short or empty page; `total_path=None` keeps the paginator from+ # misreading any body field as a total.+ return OffsetPaginator(+ limit=PAGE_SIZE,+ offset_param="skip",+ limit_param="count",+ total_path=None,+ )+++def get_resource(+ name: str,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+) -> EndpointResource:+ config = ENDPOINT_CONFIGS[name]++ params: dict[str, Any] = {}+ if config.supports_created_filter and should_use_incremental_field:+ # None values are dropped before the request, so the first incremental sync (no+ # watermark yet) walks the full history without a `from` bound.+ params["from"] = build_from_param(db_incremental_field_last_value)++ return {+ "name": config.name,+ "table_name": config.name.lower(),+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ }+ if should_use_incremental_field+ else "replace",+ "endpoint": {+ "data_selector": "items",+ "path": config.path,+ "params": params,+ "paginator": _build_paginator(),+ },+ "table_format": "delta",+ }+++def razorpay_source(+ key_id: str,+ key_secret: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[RazorpayResumeConfig],+ db_incremental_field_last_value: Optional[Any],+ should_use_incremental_field: bool = False,+) -> Resource:+ config: RESTAPIConfig = {+ "client": {+ "base_url": API_BASE_URL,+ "auth": {+ "type": "http_basic",+ "username": key_id,+ "password": key_secret,+ },+ },+ "resource_defaults": {+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ }+ if should_use_incremental_field+ else "replace",+ },+ "resources": [+ get_resource(+ endpoint,+ should_use_incremental_field,+ db_incremental_field_last_value if should_use_incremental_field else None,+ )+ ],+ }++ 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 = {"offset": resume_config.skip}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's a next page to resume to; the Redis TTL handles+ # cleanup on completion.+ if state and state.get("offset") is not None:+ resumable_source_manager.save_state(RazorpayResumeConfig(skip=int(state["offset"])))++ return rest_api_resource(+ config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+++def validate_credentials(key_id: str, key_secret: str) -> bool:+ session = make_tracked_session(redact_values=(key_secret,))+ res = session.get(+ f"{API_BASE_URL}/v1/payments",+ params={"count": 1},+ auth=(key_id, key_secret),+ timeout=30,+ )+ return res.status_code == 200diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/razorpay/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/razorpay/settings.pynew file mode 100644index 000000000000..ebcaa58d107c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/razorpay/settings.py@@ -0,0 +1,100 @@+from dataclasses import dataclass++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++API_BASE_URL = "https://api.razorpay.com"++# `count` is capped at 100 by the API (default 10).+PAGE_SIZE = 100+++@dataclass(frozen=True)+class RazorpayEndpointConfig:+ name: str+ path: str+ # Whether the endpoint documents the standard `from`/`to` created_at window filters.+ # Endpoints without them sync as full refresh only.+ supports_created_filter: bool+ primary_key: str = "id"+ partition_key: str = "created_at"+++ENDPOINT_CONFIGS: dict[str, RazorpayEndpointConfig] = {+ "Customers": RazorpayEndpointConfig(+ name="Customers",+ path="/v1/customers",+ supports_created_filter=True,+ ),+ # The disputes docs don't list `from`/`to` filters, so full refresh only. Disputes are+ # heavily mutable (status/phase transitions), so full refresh is also the safer sync mode.+ "Disputes": RazorpayEndpointConfig(+ name="Disputes",+ path="/v1/disputes",+ supports_created_filter=False,+ ),+ # The invoices docs list only type/payment_id/receipt/customer_id filters — no documented+ # `from`/`to` — so full refresh only.+ "Invoices": RazorpayEndpointConfig(+ name="Invoices",+ path="/v1/invoices",+ supports_created_filter=False,+ ),+ "Items": RazorpayEndpointConfig(+ name="Items",+ path="/v1/items",+ supports_created_filter=True,+ ),+ "Orders": RazorpayEndpointConfig(+ name="Orders",+ path="/v1/orders",+ supports_created_filter=True,+ ),+ "Payments": RazorpayEndpointConfig(+ name="Payments",+ path="/v1/payments",+ supports_created_filter=True,+ ),+ "Plans": RazorpayEndpointConfig(+ name="Plans",+ path="/v1/plans",+ supports_created_filter=True,+ ),+ "Refunds": RazorpayEndpointConfig(+ name="Refunds",+ path="/v1/refunds",+ supports_created_filter=True,+ ),+ "Settlements": RazorpayEndpointConfig(+ name="Settlements",+ path="/v1/settlements",+ supports_created_filter=True,+ ),+ "Subscriptions": RazorpayEndpointConfig(+ name="Subscriptions",+ path="/v1/subscriptions",+ supports_created_filter=True,+ ),+ # Smart Collect docs confirm count/skip pagination but not `from`/`to`, so full refresh only.+ "VirtualAccounts": RazorpayEndpointConfig(+ name="VirtualAccounts",+ path="/v1/virtual_accounts",+ supports_created_filter=False,+ ),+}++ENDPOINTS = tuple(ENDPOINT_CONFIGS.keys())++# Razorpay only filters on created_at (there is no updated-at filter), advertised as a DateTime+# cursor stored as a UNIX-seconds integer.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: [+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.Integer,+ }+ ]+ for name, config in ENDPOINT_CONFIGS.items()+ if config.supports_created_filter+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/razorpay/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/razorpay/source.pyindex a5d2f8b4994b..5022dcfba905 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/razorpay/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/razorpay/source.py@@ -1,32 +1,152 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+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.generated_configs.razorpay import (RazorpaySourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.razorpay.razorpay import (+ RazorpayResumeConfig,+ razorpay_source,+ validate_credentials as validate_razorpay_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.razorpay.settings import (+ ENDPOINT_CONFIGS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class RazorpaySource(SimpleSource[RazorpaySourceConfig]):+class RazorpaySource(ResumableSource[RazorpaySourceConfig, RazorpayResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ api_docs_url = "https://razorpay.com/docs/api/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.RAZORPAY+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.razorpay.com": "Razorpay authentication failed. Please check your key ID and key secret.",+ "400 Client Error: Bad Request for url: https://api.razorpay.com": None,+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.razorpay.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: RazorpaySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self, config: RazorpaySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_razorpay_credentials(config.key_id, config.key_secret):+ return True, None++ return (+ False,+ "Razorpay rejected the credentials. Check that the key ID and key secret are correct and the key is active.",+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RazorpayResumeConfig]:+ return ResumableSourceManager[RazorpayResumeConfig](inputs, RazorpayResumeConfig)++ def source_for_pipeline(+ self,+ config: RazorpaySourceConfig,+ resumable_source_manager: ResumableSourceManager[RazorpayResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ endpoint_config = ENDPOINT_CONFIGS[inputs.schema_name]+ resource = razorpay_source(+ key_id=config.key_id,+ key_secret=config.key_secret,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ 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,+ )+ return SourceResponse(+ name=resource.name,+ items=lambda: resource,+ primary_keys=[endpoint_config.primary_key],+ column_hints=resource.column_hints,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="week",+ partition_keys=[endpoint_config.partition_key],+ # List endpoints return newest-first and expose no sort param.+ sort_mode="desc",+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.RAZORPAY,category=DataWarehouseSourceCategory.PAYMENTS___BILLING,label="Razorpay",+ caption="Enter your Razorpay API key pair to pull payments, orders, refunds, settlements, and subscription data into the PostHog Data warehouse. Generate a key ID and key secret in the Razorpay Dashboard under Account & Settings → API keys. Use a `rzp_live_` key for live-mode data or a `rzp_test_` key for test-mode data.",+ docsUrl="https://posthog.com/docs/cdp/sources/razorpay",iconPath="/static/services/razorpay.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="key_id",+ label="Key ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="rzp_live_...",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="key_secret",+ label="Key secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/razorpay/tests/test_razorpay.py b/products/warehouse_sources/backend/temporal/data_imports/sources/razorpay/tests/test_razorpay.pynew file mode 100644index 000000000000..4dfb3365e321--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/razorpay/tests/test_razorpay.py@@ -0,0 +1,224 @@+import json+from collections.abc import Iterable+from typing import Any, Optional, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.razorpay.razorpay import (+ INCREMENTAL_LOOKBACK_SECONDS,+ MIN_FROM_TIMESTAMP,+ RazorpayResumeConfig,+ build_from_param,+ get_resource,+ razorpay_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.razorpay.settings import (+ ENDPOINT_CONFIGS,+ PAGE_SIZE,+)+++def _collection_response(items: list[dict[str, Any]], status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps({"entity": "collection", "count": len(items), "items": items}).encode()+ resp.headers["Content-Type"] = "application/json"+ return resp+++def _items(count: int, start: int = 0) -> list[dict[str, Any]]:+ return [{"id": f"pay_{start + i}", "created_at": 1_750_000_000 + start + i} for i in range(count)]+++def _drive(+ manager: MagicMock,+ responses: list[Response],+ endpoint: str = "Payments",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:+ """Run ``razorpay_source`` against a mocked HTTP session.++ Returns ``(rows, sent_params)`` where ``sent_params`` are shallow copies of+ ``request.params`` captured at send-time (the Request object is mutated+ in-place by the paginator between pages).+ """+ 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(+ "products.warehouse_sources.backend.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 = razorpay_source(+ key_id="rzp_test_key",+ key_secret="secret",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ db_incremental_field_last_value=db_incremental_field_last_value,+ should_use_incremental_field=should_use_incremental_field,+ )+ rows = [row for page in cast(Iterable[Any], resource) for row in (page if isinstance(page, list) else [page])]+ return rows, sent_params+++class TestRazorpayPagination:+ def test_full_walk_uses_skip_count_and_saves_resume_state_after_each_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _collection_response(_items(PAGE_SIZE)),+ _collection_response(_items(PAGE_SIZE, start=PAGE_SIZE)),+ _collection_response(_items(3, start=2 * PAGE_SIZE)),+ ]+ rows, sent_params = _drive(manager, responses)++ assert len(rows) == 2 * PAGE_SIZE + 3+ assert [(p.get("skip"), p.get("count")) for p in sent_params] == [+ (0, PAGE_SIZE),+ (PAGE_SIZE, PAGE_SIZE),+ (2 * PAGE_SIZE, PAGE_SIZE),+ ]++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [+ RazorpayResumeConfig(skip=PAGE_SIZE),+ RazorpayResumeConfig(skip=2 * PAGE_SIZE),+ ]++ def test_short_first_page_terminates_without_saving_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ rows, sent_params = _drive(manager, [_collection_response(_items(5))])++ assert len(rows) == 5+ assert len(sent_params) == 1+ manager.save_state.assert_not_called()++ def test_resume_seeds_skip_from_saved_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = RazorpayResumeConfig(skip=200)++ _, sent_params = _drive(manager, [_collection_response(_items(1))])++ assert [p.get("skip") for p in sent_params] == [200]+ manager.load_state.assert_called_once()++ def test_does_not_load_state_when_cannot_resume(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ _drive(manager, [_collection_response(_items(1))])++ manager.load_state.assert_not_called()+++class TestRazorpayIncremental:+ def test_incremental_sync_sends_lookback_adjusted_from_on_every_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ watermark = 1_750_000_000++ responses = [+ _collection_response(_items(PAGE_SIZE)),+ _collection_response(_items(2, start=PAGE_SIZE)),+ ]+ _, sent_params = _drive(+ manager,+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )++ expected_from = watermark - INCREMENTAL_LOOKBACK_SECONDS+ assert [p.get("from") for p in sent_params] == [expected_from, expected_from]++ def test_first_incremental_sync_omits_from(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ _, sent_params = _drive(+ manager,+ [_collection_response(_items(1))],+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ )++ assert "from" not in sent_params[0]++ def test_full_refresh_endpoint_never_sends_from(self) -> None:+ # Disputes doesn't document `from`/`to`; sending unknown params risks a 400 from+ # Razorpay's strict param validation.+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ _, sent_params = _drive(+ manager,+ [_collection_response(_items(1))],+ endpoint="Disputes",+ should_use_incremental_field=True,+ db_incremental_field_last_value=1_750_000_000,+ )++ assert "from" not in sent_params[0]++ @pytest.mark.parametrize(+ ("last_value", "expected"),+ [+ (None, None),+ (1_750_000_000, 1_750_000_000 - INCREMENTAL_LOOKBACK_SECONDS),+ ("1750000000", 1_750_000_000 - INCREMENTAL_LOOKBACK_SECONDS),+ (MIN_FROM_TIMESTAMP + 10, MIN_FROM_TIMESTAMP),+ ("not-a-timestamp", None),+ ],+ )+ def test_build_from_param(self, last_value: Any, expected: Optional[int]) -> None:+ assert build_from_param(last_value) == expected+++class TestRazorpayResources:+ @pytest.mark.parametrize("endpoint", list(ENDPOINT_CONFIGS.keys()))+ def test_resource_shape_for_each_endpoint(self, endpoint: str) -> None:+ resource = get_resource(endpoint, should_use_incremental_field=False, db_incremental_field_last_value=None)++ endpoint_config = cast(dict[str, Any], resource["endpoint"])+ assert resource["name"] == endpoint+ assert endpoint_config["data_selector"] == "items"+ assert endpoint_config["path"] == ENDPOINT_CONFIGS[endpoint].path+ assert resource["write_disposition"] == "replace"++ def test_incremental_resource_uses_merge_disposition(self) -> None:+ resource = get_resource("Payments", should_use_incremental_field=True, db_incremental_field_last_value=None)++ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}+++class TestRazorpayValidateCredentials:+ @pytest.mark.parametrize(("status_code", "expected"), [(200, True), (401, False), (500, False)])+ def test_status_code_mapping(self, status_code: int, expected: bool) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.razorpay.razorpay.make_tracked_session"+ ) as MockSession:+ response = Response()+ response.status_code = status_code+ MockSession.return_value.get.return_value = response++ assert validate_credentials("rzp_test_key", "secret") is expecteddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/razorpay/tests/test_razorpay_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/razorpay/tests/test_razorpay_source.pynew file mode 100644index 000000000000..f1142e0a5670--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/razorpay/tests/test_razorpay_source.py@@ -0,0 +1,170 @@+from typing import Any, Optional++import pytest+from unittest.mock import MagicMock, patch++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.razorpay import (+ RazorpaySourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.razorpay.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.razorpay.razorpay import RazorpayResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.razorpay.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.razorpay.source import RazorpaySource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _source_inputs(+ schema_name: str = "Payments",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema_id",+ source_id="source_id",+ team_id=1,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ db_incremental_field_earliest_value=None,+ incremental_field="created_at" if should_use_incremental_field else None,+ incremental_field_type=None,+ job_id="job_id",+ logger=MagicMock(),+ reset_pipeline=False,+ )+++class TestRazorpaySource:+ def setup_method(self) -> None:+ self.source = RazorpaySource()+ self.config = RazorpaySourceConfig(key_id="rzp_test_key", key_secret="secret")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.RAZORPAY++ def test_source_is_released_as_alpha(self) -> None:+ config = self.source.get_source_config++ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA++ def test_source_config_fields(self) -> None:+ fields = {+ field.name: field+ for field in self.source.get_source_config.fields+ if isinstance(field, SourceFieldInputConfig)+ }++ assert set(fields.keys()) == {"key_id", "key_secret"}+ assert fields["key_secret"].secret is True+ assert fields["key_secret"].type == SourceFieldInputConfigType.PASSWORD+ assert fields["key_id"].required is True+ assert fields["key_secret"].required is True++ @pytest.mark.parametrize(+ ("endpoint", "supports_incremental"),+ [+ ("Customers", True),+ ("Disputes", False),+ ("Invoices", False),+ ("Items", True),+ ("Orders", True),+ ("Payments", True),+ ("Plans", True),+ ("Refunds", True),+ ("Settlements", True),+ ("Subscriptions", True),+ ("VirtualAccounts", False),+ ],+ )+ def test_get_schemas_incremental_support(self, endpoint: str, supports_incremental: bool) -> None:+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, team_id=1)}++ assert endpoint in schemas+ schema = schemas[endpoint]+ assert schema.supports_incremental is supports_incremental+ if supports_incremental:+ assert [field["field"] for field in schema.incremental_fields] == ["created_at"]+ else:+ assert schema.incremental_fields == []++ def test_get_schemas_covers_all_endpoints_and_filters_by_name(self) -> None:+ all_schemas = self.source.get_schemas(self.config, team_id=1)+ assert [schema.name for schema in all_schemas] == list(ENDPOINTS)++ filtered = self.source.get_schemas(self.config, team_id=1, names=["Payments", "Refunds"])+ assert [schema.name for schema in filtered] == ["Payments", "Refunds"]++ @pytest.mark.parametrize(+ ("is_valid", "expected_ok"),+ [(True, True), (False, False)],+ )+ def test_validate_credentials(self, is_valid: bool, expected_ok: bool) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.razorpay.source.validate_razorpay_credentials",+ return_value=is_valid,+ ) as mock_validate:+ ok, message = self.source.validate_credentials(self.config, team_id=1)++ mock_validate.assert_called_once_with("rzp_test_key", "secret")+ assert ok is expected_ok+ assert (message is None) is expected_ok++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_source_inputs())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is RazorpayResumeConfig++ @pytest.mark.parametrize(+ ("should_use_incremental_field", "last_value", "expected_last_value"),+ [+ (True, 1_750_000_000, 1_750_000_000),+ (False, 1_750_000_000, None),+ ],+ )+ def test_source_for_pipeline_plumbing(+ self,+ should_use_incremental_field: bool,+ last_value: Optional[int],+ expected_last_value: Optional[int],+ ) -> None:+ inputs = _source_inputs(+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=last_value,+ )+ manager = MagicMock(spec=ResumableSourceManager)+ mock_resource = MagicMock()+ mock_resource.name = "Payments"+ mock_resource.column_hints = None++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.razorpay.source.razorpay_source",+ return_value=mock_resource,+ ) as mock_source:+ response = self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once_with(+ key_id="rzp_test_key",+ key_secret="secret",+ endpoint="Payments",+ team_id=1,+ job_id="job_id",+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=expected_last_value,+ )+ assert response.name == "Payments"+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "desc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]++ def test_canonical_descriptions_cover_only_known_endpoints(self) -> None:+ assert set(CANONICAL_DESCRIPTIONS.keys()) == set(ENDPOINTS)