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.

fix(stripe): scope credit balance transaction sync to a customer (#75723)

Tom Owersf738c7ccb2cb
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py
index 49aefec7dc1b..ca7bb195f03c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe.py
@@ -383,6 +383,20 @@ def _credit_grant_customer_params(credit_grant: dict[str, Any]) -> dict[str, Any
return {"customer": credit_grant.get("customer")}
+def _credit_balance_transaction_lister(client: StripeClient) -> Callable[..., ListObject[Any]]:
+ """`/v1/billing/credit_balance_transactions` requires a `customer` filter — like credit balance
+ summary, it has no unscoped list. Scope it to a single credit grant (also filtering on
+ `credit_grant` so a customer with several grants doesn't return the same transaction once per
+ grant) so each row is a transaction against a grant we already sync."""
+
+ def _list(credit_grant: str, params: dict[str, Any]) -> ListObject[Any]:
+ return client.billing.credit_balance_transactions.list(
+ params=cast(Any, {**params, "credit_grant": credit_grant})
+ )
+
+ return _list
+
+
def _credit_grant_has_customer(credit_grant: dict[str, Any]) -> bool:
"""Credit grants issued to an Account rather than a Customer carry `customer_account` instead of
`customer`. The summary endpoint takes one or the other, and we scope on `customer`, so skip the
@@ -531,8 +545,14 @@ def _build_resources(
EVENT_RESOURCE_NAME: StripeResource(method=client.events.list),
BILLING_METER_RESOURCE_NAME: StripeResource(method=client.billing.meters.list),
BILLING_CREDIT_GRANT_RESOURCE_NAME: StripeResource(method=client.billing.credit_grants.list),
- BILLING_CREDIT_BALANCE_TRANSACTION_RESOURCE_NAME: StripeResource(
- method=client.billing.credit_balance_transactions.list
+ BILLING_CREDIT_BALANCE_TRANSACTION_RESOURCE_NAME: StripeNestedResource(
+ method=_credit_balance_transaction_lister(client),
+ nested_parent_param="credit_grant",
+ parent_id="id",
+ parent=StripeResource(method=client.billing.credit_grants.list),
+ parent_name=BILLING_CREDIT_GRANT_RESOURCE_NAME,
+ parent_has_nested=_credit_grant_has_customer,
+ nested_params_from_parent=_credit_grant_customer_params,
),
ENTITLEMENTS_FEATURE_RESOURCE_NAME: StripeResource(method=client.entitlements.features.list),
INVOICE_PAYMENT_RESOURCE_NAME: StripeResource(method=client.invoice_payments.list),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py
index 5c6f03b8a2a3..6bfc94d526b6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py
@@ -61,6 +61,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.set
)
from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source import StripeSource
from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.stripe import (
+ DEFAULT_LIMIT,
SUBSCRIPTION_PAGE_LIMIT,
StripeAuthenticationError,
StripeNestedResource,
@@ -982,6 +983,67 @@ class TestCreditBalanceSummaryFanout:
assert [row["credit_grant"] for row in rows] == ["credgr_cus"]
+class TestCreditBalanceTransactionFanout:
+ def _run(self, grants: list[dict[str, Any]]) -> tuple[list[dict], list[dict]]:
+ listed: list[dict] = []
+
+ def list_transactions(params):
+ listed.append(params)
+ return _list_object([{"id": f"cbtxn_{params['credit_grant']}", "credit_grant": params["credit_grant"]}])
+
+ client = MagicMock()
+ client.billing.credit_balance_transactions.list.side_effect = list_transactions
+ client.billing.credit_grants.list.return_value = _list_object(grants)
+
+ resource = stripe_module._build_resources(client, logger=None)[BILLING_CREDIT_BALANCE_TRANSACTION_RESOURCE_NAME]
+ resumable_source_manager = MagicMock()
+ resumable_source_manager.can_resume.return_value = False
+
+ with (
+ patch.object(stripe_module, "StripeClient"),
+ patch.object(
+ stripe_module,
+ "_build_resources",
+ return_value={BILLING_CREDIT_BALANCE_TRANSACTION_RESOURCE_NAME: resource},
+ ),
+ ):
+ rows: list[dict] = []
+ for table in get_rows(
+ api_key="sk_test_123",
+ endpoint=BILLING_CREDIT_BALANCE_TRANSACTION_RESOURCE_NAME,
+ account_id=None,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ logger=MagicMock(),
+ resumable_source_manager=resumable_source_manager,
+ api_version=STRIPE_API_VERSION_ACACIA,
+ ):
+ rows.extend(table.to_pylist())
+ return rows, listed
+
+ def test_scopes_each_list_call_to_its_grant_and_customer(self):
+ # Stripe rejects `/v1/billing/credit_balance_transactions` outright without a `customer`
+ # filter ("Must provide customer or customer_account") — calling it as an unscoped list, the
+ # way every other top-level resource is called, 400s on every single sync.
+ rows, listed = self._run([{"id": "credgr_1", "customer": "cus_1"}])
+
+ assert listed == [{"customer": "cus_1", "limit": DEFAULT_LIMIT, "credit_grant": "credgr_1"}]
+ assert [row["credit_grant"] for row in rows] == ["credgr_1"]
+
+ def test_skips_grants_issued_to_an_account(self):
+ # Grants made to an Account carry `customer_account` instead of `customer`; scoping the
+ # request on a missing customer would make Stripe reject it the same way.
+ rows, listed = self._run(
+ [
+ {"id": "credgr_acct", "customer": None, "customer_account": "acct_1"},
+ {"id": "credgr_cus", "customer": "cus_1"},
+ ]
+ )
+
+ assert [params["credit_grant"] for params in listed] == ["credgr_cus"]
+ assert [row["credit_grant"] for row in rows] == ["credgr_cus"]
+
+
class TestSchemaWebhookCapability:
def setup_method(self):
self.source = StripeSource()