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.

61.7 KB
Raw Blame
import hmac
import json
import math
import time
import hashlib
from datetime import UTC, datetime, timedelta
from enum import Enum, StrEnum
from http.cookiejar import DefaultCookiePolicy
from typing import Any, Literal, Optional, cast
from uuid import UUID

from django.conf import settings
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.db.models import F, Q
from django.utils import timezone
from django.utils.dateparse import parse_datetime

import jwt
import requests
import structlog
from requests import JSONDecodeError
from rest_framework.exceptions import NotAuthenticated, NotFound, PermissionDenied, Throttled

from posthog.cloud_utils import get_cached_instance_license
from posthog.dataclasses import frozen
from posthog.event_usage import report_user_action
from posthog.exceptions_capture import capture_exception
from posthog.models import Organization
from posthog.models.oauth import OAuthApplication
from posthog.models.organization import OrganizationMembership, OrganizationUsageInfo
from posthog.models.organization_provisioning import get_billing_lock_partner
from posthog.models.team.event_retention import (
    organization_events_retention_months,
    reconcile_organization_events_retention,
)
from posthog.models.team.logs_retention import reset_revoked_logs_retention
from posthog.models.user import User

from ee.billing.access_token import mint_billing_access_token
from ee.billing.billing_types import BillingProvider, BillingStatus, CustomerInfo
from ee.billing.grants import EffectiveBillingGrants
from ee.billing.quota_limiting import BILLING_STATUS_STAMP_KEYS, set_org_usage_summary, update_org_billing_quotas
from ee.models import License
from ee.settings import BILLING_SERVICE_URL

logger = structlog.get_logger(__name__)

# One pooled session for every call to the billing service. A bare requests.get opens a TCP
# connection and a TLS handshake per call and closes them afterwards; the session keeps connections
# open and reuses them. It rejects cookies because these are server-to-server calls that each carry
# a bearer token for one organization, and a cookie set on one response must not ride along on
# another organization's request.
http_session = requests.Session()
http_session.cookies.set_policy(DefaultCookiePolicy(allowed_domains=[]))

BILLING_PROVIDER_WEBHOOK_SIGNATURE_HEADER = "X-PostHog-Billing-Provider-Signature"
BILLING_PROVIDER_WEBHOOK_TIMESTAMP_HEADER = "X-PostHog-Billing-Provider-Timestamp"
BILLING_PROVIDER_WEBHOOK_SIGNATURE_VERSION = "sha256"
BILLING_TIMESERIES_REQUEST_TIMEOUT = (5, 30)
# An export covers every project rather than the chart's top few, so it reads more and is
# allowed longer. The person is waiting for a file, which tolerates a longer wait than a chart.
BILLING_EXPORT_REQUEST_TIMEOUT = (5, 120)

# Marks tokens minted by the billing alerts evaluation job; billing recognizes this claim
# on its read-only billing status path for tokens without a user role.
BILLING_ALERTS_EVALUATION_SERVICE_ACTION = "billing_alerts_evaluation"


StartupProgramLabel = Literal["Startup", "YC"]


class PrepaidCreditState(StrEnum):
    NONE = "none"
    PENDING = "pending"
    ACTIVE = "active"
    EXHAUSTED = "exhausted"
    EXPIRED = "expired"


class FundingStatusUnavailable(Exception):
    pass


_FUNDING_STATUS_UNAVAILABLE_CACHE_VALUE = "__funding_status_unavailable__"


@frozen
class OrganizationFundingStatus:
    startup_program_label: StartupProgramLabel | None
    prepaid_credit_state: PrepaidCreditState


class BillingAPIErrorCodes(Enum):
    OPEN_INVOICES_ERROR = "open_invoices_error"


class OrganizationHasNoOwnerError(Exception):
    def __init__(self) -> None:
        super().__init__("No owner membership found for organization")


class BillingServiceOpenInvoicesError(Exception):
    def __init__(self, message: str):
        self.message = message
        super().__init__(message)


class BillingManagedByPartnerError(PermissionDenied):
    def __init__(self, partner: OAuthApplication) -> None:
        partner_name = partner.name.strip() or "your partner"
        super().__init__(
            f"Billing for this organization is managed by {partner_name}. "
            f"Contact {partner_name} to change your plan or payment details."
        )


def raise_if_billing_managed_by_partner(organization: Organization) -> None:
    partner = get_billing_lock_partner(organization)
    if partner is not None:
        raise BillingManagedByPartnerError(partner)


def _has_quota_limiting_markers(usage: dict | None) -> bool:
    if not usage:
        return False

    for value in usage.values():
        if isinstance(value, dict) and (
            value.get("quota_limited_until") is not None or value.get("quota_limiting_suspended_until") is not None
        ):
            return True

    return False


def _is_older_than_applied_billing_status(organization: Organization, computed_at: datetime) -> bool:
    applied_at = parse_datetime((organization.usage or {}).get("billing_status_computed_at") or "")
    return applied_at is not None and computed_at < applied_at


def _free_trial_active(customer: CustomerInfo) -> bool:
    free_trial_until = customer.get("free_trial_until")
    if not free_trial_until:
        return False
    expires = parse_datetime(free_trial_until) if isinstance(free_trial_until, str) else free_trial_until
    if expires is None:
        return False
    # An offset-less timestamp parses naive, and comparing naive to aware raises TypeError.
    if timezone.is_naive(expires):
        expires = expires.replace(tzinfo=UTC)
    return expires > timezone.now()


def _is_valid_email(email: str) -> bool:
    try:
        validate_email(email)
    except ValidationError:
        return False
    return True


def get_most_recent_owner(organization: Organization) -> User | None:
    membership = (
        OrganizationMembership.objects.filter(organization=organization, level=OrganizationMembership.Level.OWNER)
        .order_by("-joined_at")
        .first()
    )
    return membership.user if membership else None


def _get_user_organization_role(user: User, organization: Organization) -> Optional[str]:
    """
    Get a user role display string in a given organization, if membership doesn't exist return None.
    """
    try:
        membership = user.organization_memberships.get(organization=organization)
        return membership.get_level_display()
    except OrganizationMembership.DoesNotExist:
        return None


def build_billing_token(
    license: Optional[License],
    organization: Optional[Organization],
    user: Optional[User] = None,
    authorizer_actor: Optional[User] = None,
    billing_provider: BillingProvider | None = None,
    service_action: str | None = None,
) -> str:
    """
    Build the JWT token to authenticate with the Billing system.

    Allows doing privilege escalation with the `authorizer_actor` parameter, in that case the distinct_id
    will be that of the user, but the role will be that of the authorizer_actor.

    `service_action` marks a token minted by a backend job for one specific service-to-service
    endpoint (e.g. "signals_pr_dispute"); billing rejects calls to such endpoints from tokens
    without the matching claim, so tokens minted for user-initiated calls can't reach them.

    Raises NotAuthenticated if the authorizer_actor (or user in case there's no authorizer_actor) are not
    part of the organization.
    """
    if not organization or not license:
        raise NotAuthenticated()

    license_id = license.key.split("::")[0]
    license_secret = license.key.split("::")[1]

    payload = {
        "exp": datetime.now(tz=UTC) + timedelta(minutes=15),
        "id": license_id,
        "organization_id": str(organization.id),
        "organization_name": organization.name,
        "aud": "posthog:license-key",
    }

    if user:
        authorizer_actor = authorizer_actor or user

        payload["distinct_id"] = str(user.distinct_id)
        # Billing's startup program checks read an email domain as evidence of who an applicant
        # works for, and this is the only address it gets from us.
        payload["email"] = user.email
        authorizer_role = _get_user_organization_role(authorizer_actor, organization)

        if authorizer_role:
            payload["organization_role"] = authorizer_role
        else:
            raise NotAuthenticated(f"Authorizer is not part of organization")

        if authorizer_actor != user:
            # We've done a privilege escalation
            report_user_action(
                authorizer_actor,
                "$billing_privilege_escalation",
                properties={
                    "target_user_id": user.id,
                    "target_distinct_id": str(user.distinct_id),
                    "target_email": user.email,
                    "action": "update_billing",
                },
            )
            payload["original_role"] = _get_user_organization_role(user, organization)

    if billing_provider:
        payload["billing_provider"] = billing_provider.value

    if service_action:
        payload["service_action"] = service_action

    paying_partner = get_billing_lock_partner(organization)
    if paying_partner:
        payload["payer_partner_id"] = str(paying_partner.id)

    encoded_jwt = jwt.encode(
        payload,
        license_secret,
        algorithm="HS256",
    )

    return encoded_jwt


DEACTIVATED_ORGANIZATIONS_SERVICE_ACTION = "deactivated_organizations"


def build_billing_system_token(license: License, service_action: str) -> str:
    """JWT for billing's /api/internal/* endpoints: license-signed, org-less, action-scoped.

    Billing's internal endpoints reject tokens that carry an organization_id claim, so unlike
    build_billing_token this deliberately omits the organization.
    """
    license_id = license.key.split("::")[0]
    license_secret = license.key.split("::")[1]

    payload = {
        "exp": datetime.now(tz=UTC) + timedelta(minutes=15),
        "id": license_id,
        "aud": "posthog:license-key",
        "service_action": service_action,
    }

    return jwt.encode(payload, license_secret, algorithm="HS256")


def _compute_webhook_signature(secret: str, timestamp: int, body: bytes) -> str:
    """HMAC-SHA256 over "<timestamp>.<body>", hex-encoded."""
    mac = hmac.new(secret.encode(), digestmod=hashlib.sha256)
    mac.update(f"{timestamp}.".encode())
    mac.update(body)
    return mac.digest().hex()


def build_billing_provider_webhook_signature_headers(body: bytes) -> dict[str, str]:
    secret = getattr(settings, "BILLING_PROVIDER_WEBHOOK_SECRET", "")
    if not secret:
        raise ValueError("BILLING_PROVIDER_WEBHOOK_SECRET is not configured")

    timestamp = int(time.time())
    digest = _compute_webhook_signature(secret, timestamp, body)
    return {
        BILLING_PROVIDER_WEBHOOK_SIGNATURE_HEADER: f"{BILLING_PROVIDER_WEBHOOK_SIGNATURE_VERSION}={digest}",
        BILLING_PROVIDER_WEBHOOK_TIMESTAMP_HEADER: str(timestamp),
    }


BILLING_ORGANIZATION_ACCESS_DENIED = "You do not have access to Billing for this organization."


def _raise_for_organization_error(res: requests.Response, *, map_not_found: bool = True) -> None:
    """Turn billing's refusals on the organization routes into this API's own errors.

    Only the machine-readable `code` crosses over, and it chooses one of the errors defined here.
    Billing's body never reaches the caller: it is written for a different API, it renders through
    the same error envelope this one uses, so re-raising it names billing's `type` field as the
    offending parameter, and an upstream body can carry detail a caller should not see.

    The body is read defensively for the same reason. A non-JSON error, from billing or from a
    proxy in front of it, must not turn a mapped refusal into a 500.
    """
    from ee.api.billing import (  # noqa: PLC0415 - circular import
        BILLING_GUIDANCE_ERRORS,
        BillingQueryRejected,
        BillingServiceError,
    )

    if res.status_code >= 500:
        # A billing failure, including a response billing could not build. It is not the caller's
        # to fix, so it never maps to a refusal that tells them to change the request.
        logger.warning("billing_organization_error", upstream_status=res.status_code)
        raise BillingServiceError()
    if res.status_code not in (400, 403, 404):
        return
    try:
        parsed = res.json()
    except JSONDecodeError:
        parsed = None
    code = parsed.get("code") if isinstance(parsed, dict) else None
    if res.status_code != 404 or map_not_found:
        logger.warning("billing_organization_error", upstream_status=res.status_code, code=code)
    if res.status_code == 403:
        raise PermissionDenied(BILLING_ORGANIZATION_ACCESS_DENIED)
    if res.status_code == 404:
        if not map_not_found:
            return
        raise NotFound("Not found.")
    if code in BILLING_GUIDANCE_ERRORS:
        raise BILLING_GUIDANCE_ERRORS[code]()
    raise BillingQueryRejected()


class BillingServiceResponseError(Exception):
    """Billing answered with a status code the caller does not accept, other than 429,
    which raises BillingServiceRateLimited."""

    def __init__(self, status_code: int, body: Any) -> None:
        # The message and the body keep the positions callers already read: see
        # `_raise_billing_error` in ee/api/billing.py, which parses the status out of the message.
        super().__init__(f"Billing service returned bad status code: {status_code}", "body:", body)
        self.status_code = status_code
        self.body = body


class BillingServiceRateLimited(Throttled):
    # DRF sets this in Throttled.__init__ and its handler turns it into Retry-After; the stubs omit it.
    wait: Optional[float]

    default_code = "billing_rate_limited"
    default_detail = "Billing is receiving too many requests for this organization. Try again shortly."


def _retry_after_seconds(res: requests.Response) -> Optional[float]:
    try:
        seconds = float(res.headers.get("Retry-After", ""))
    except ValueError:
        return None
    # DRF rounds the wait up with math.ceil, which raises on nan and infinity.
    return seconds if math.isfinite(seconds) and seconds >= 0 else None


def handle_billing_service_error(res: requests.Response, valid_codes=(200, 201, 404, 401)) -> None:
    if res.status_code not in valid_codes:
        if res.status_code == 429:
            wait = _retry_after_seconds(res)
            # A streamed response (see _get_csv) keeps its pooled connection until it is closed.
            res.close()
            # Keyword arguments only, so args stays empty: the legacy handlers in ee/api/billing.py turn an
            # exception with more than two args into a 400.
            raise BillingServiceRateLimited(wait=wait)
        logger.error(f"Billing service returned bad status code: {res.status_code}, body: {res.text}")
        try:
            body: Any = res.json()
        except JSONDecodeError:
            # A body that is not JSON, such as the empty body of a proxy timeout, is still the
            # answer the caller has to report. Read it as text, so the decode failure does not
            # become the reported cause of the error.
            body = res.text

        raise BillingServiceResponseError(res.status_code, body)


def _parse_funding_status(data: object) -> OrganizationFundingStatus:
    if not isinstance(data, dict):
        raise FundingStatusUnavailable("Billing returned an invalid funding status response")

    if "startup_program_label" not in data:
        raise FundingStatusUnavailable("Billing returned an invalid startup program label")
    raw_startup_program_label = data.get("startup_program_label")
    if raw_startup_program_label not in (None, "Startup", "YC"):
        raise FundingStatusUnavailable("Billing returned an invalid startup program label")
    startup_program_label = cast(StartupProgramLabel | None, raw_startup_program_label)

    raw_prepaid_credit_state = data.get("prepaid_credit_state")
    if not isinstance(raw_prepaid_credit_state, str):
        raise FundingStatusUnavailable("Billing returned an invalid prepaid credit state")
    try:
        prepaid_credit_state = PrepaidCreditState(raw_prepaid_credit_state)
    except ValueError as error:
        raise FundingStatusUnavailable("Billing returned an invalid prepaid credit state") from error

    return OrganizationFundingStatus(
        startup_program_label=startup_program_label,
        prepaid_credit_state=prepaid_credit_state,
    )


class BillingManager:
    license: License | None
    user: User | None
    ip_address: str | None

    def __init__(self, license, user: User | None = None, ip_address: str | None = None):
        self.license = license or get_cached_instance_license()
        self.user = user
        self.ip_address = ip_address

    def get_billing(
        self,
        organization: Organization | None,
        query_params: dict[str, Any] | None = None,
    ) -> dict[str, Any]:
        if not organization or not self.license or not self.license.is_v2_license:
            return self._get_default_billing_response(organization)

        # Get billing info from billing service
        billing_service_response = self._get_billing(organization, query_params)

        customer = cast(dict[str, Any], billing_service_response).get("customer")
        if not customer:
            return self._get_default_billing_response(organization)

        # Ensure the license and org are updated with the latest info
        if billing_service_response.get("license"):
            self.update_license_details(billing_service_response)

        if organization and billing_service_response:
            self.update_org_details(organization, billing_service_response)

        response: dict[str, Any] = {"available_product_features": []}

        response["license"] = {"plan": self.license.plan}

        response.update(billing_service_response["customer"])

        if not billing_service_response["customer"].get("products"):
            products = self.get_default_products(organization)
            response["products"] = products["products"]

        response["stripe_portal_url"] = f"{settings.SITE_URL}/api/billing/portal"

        usage_summary = response.get("usage_summary") or {}
        if organization.usage:
            for usage_key, usage in usage_summary.items():
                # both dicts carry non-usage entries, e.g. "period" is a list
                org_usage = organization.usage.get(usage_key)
                if not isinstance(org_usage, dict) or not isinstance(usage, dict):
                    continue
                todays_usage = org_usage.get("todays_usage")
                if todays_usage is not None:
                    usage["todays_usage"] = todays_usage

        # Extend the products with accurate usage_limit info
        for product in response["products"]:
            usage_key = product.get("usage_key")
            if not usage_key:
                continue
            usage = response.get("usage_summary", {}).get(usage_key, {})
            usage_limit = usage.get("limit")
            billing_reported_usage = usage.get("usage") or 0
            current_usage = billing_reported_usage

            if usage.get("todays_usage"):
                todays_usage = usage["todays_usage"]
                current_usage = billing_reported_usage + todays_usage

            product["current_usage"] = current_usage
            product["percentage_usage"] = current_usage / usage_limit if usage_limit else 0

        return response

    def update_billing(
        self, organization: Organization, data: dict[str, Any], authorizer_actor: Optional[User] = None
    ) -> requests.Response:
        res = http_session.patch(
            f"{BILLING_SERVICE_URL}/api/billing/",
            headers=self.get_auth_headers(organization, authorizer_actor=authorizer_actor),
            json=data,
        )

        handle_billing_service_error(res)
        return res

    def update_available_product_features(self, organization: Organization) -> list[dict[str, Any]]:
        res = http_session.get(
            f"{BILLING_SERVICE_URL}/api/billing/available_product_features",
            headers=self.get_auth_headers(organization),
        )

        handle_billing_service_error(res)

        available_product_features_json = res.json()
        available_product_features = available_product_features_json.get("available_product_features", [])
        previous_feature_keys = {
            feature.get("key") for feature in (organization.available_product_features or []) if feature
        }
        previous_retention_months = organization_events_retention_months(organization)
        organization.available_product_features = available_product_features
        organization.save()

        if (
            available_product_features
            and organization_events_retention_months(organization) != previous_retention_months
        ):
            reconcile_organization_events_retention(organization)

        # Only reset on a non-empty list: the retention reset is not self-healing, so an
        # empty error-path response must not permanently downgrade team settings.
        if available_product_features:
            revoked_feature_keys = previous_feature_keys - {
                feature.get("key") for feature in available_product_features if feature
            }
            if revoked_feature_keys:
                reset_revoked_logs_retention(organization, revoked_feature_keys)

        return available_product_features

    def update_billing_organization_users(self, organization: Organization) -> None:
        """
        Updates the register of users in the Billing service, reporting any failure to error
        tracking instead of raising.
        """
        try:
            self.sync_organization_users(organization)
        except Exception as e:
            capture_exception(e, {"organization_id": organization.id})

    def sync_organization_users(self, organization: Organization) -> requests.Response:
        """
        Sends the organization's members to the Billing service and returns its response.
        A 401 or 404 from billing is returned rather than raised, so a caller that needs to know
        whether the sync landed checks the status code.
        Since this can be called with users that are not ADMINs and update_billing requires
        an ADMIN role, we do a privilege escalation using the owner.
        """
        first_owner = get_most_recent_owner(organization)
        if not first_owner:
            raise OrganizationHasNoOwnerError()

        # Billing rejects the whole update when one value fails its validation, so values it would
        # reject are left out: a NULL or empty distinct_id, and an admin email that is not valid.
        members_with_distinct_id = organization.members.exclude(Q(distinct_id__isnull=True) | Q(distinct_id=""))

        distinct_ids = list(members_with_distinct_id.values_list("distinct_id", flat=True))

        admin_emails = [
            email
            for email in organization.members.filter(
                organization_membership__level__gte=OrganizationMembership.Level.ADMIN
            ).values_list("email", flat=True)
            if _is_valid_email(email)
        ]

        org_users = list(
            members_with_distinct_id.values("email", "distinct_id", "organization_membership__level")
            .order_by("email")  # Deterministic order for tests
            .annotate(role=F("organization_membership__level"))
            .filter(role__gte=OrganizationMembership.Level.ADMIN)
            .values(
                "email",
                "distinct_id",
                "role",
            )
        )

        return self.update_billing(
            organization,
            {
                "distinct_ids": distinct_ids,
                "org_customer_email": first_owner.email,
                "org_admin_emails": admin_emails,
                "org_users": org_users,
            },
            authorizer_actor=first_owner,
        )

    def activate_subscription(self, organization: Organization, data: dict[str, Any]) -> dict[str, Any]:
        res = http_session.post(
            f"{BILLING_SERVICE_URL}/api/activate",
            headers=self.get_auth_headers(organization),
            json=data,
        )

        handle_billing_service_error(res)

        return res.json()

    def deactivate_products(self, organization: Organization, products: str) -> None:
        res = http_session.post(
            f"{BILLING_SERVICE_URL}/api/billing/deactivate",
            headers=self.get_auth_headers(organization),
            json={"products": products},
        )

        handle_billing_service_error(res)

    def get_funding_status(self, organization: Organization) -> OrganizationFundingStatus:
        cache_key = f"organization_funding_status:{organization.id}"
        try:
            cached_status = cache.get(cache_key)
        except Exception:
            logger.warning("funding_status_cache_read_failed", exc_info=True)
            cached_status = None

        if cached_status == _FUNDING_STATUS_UNAVAILABLE_CACHE_VALUE:
            raise FundingStatusUnavailable("Could not resolve organization funding status")
        if cached_status is not None:
            return _parse_funding_status(cached_status)

        try:
            response = http_session.get(
                f"{BILLING_SERVICE_URL}/api/billing/funding-status/",
                headers=self.get_auth_headers(organization),
                timeout=5,
            )
            handle_billing_service_error(response, valid_codes=(200,))
            raw_status = response.json()
            funding_status = _parse_funding_status(raw_status)
        except Exception as error:
            try:
                cache.set(cache_key, _FUNDING_STATUS_UNAVAILABLE_CACHE_VALUE, timeout=5)
            except Exception:
                logger.warning("funding_status_failure_cache_write_failed", exc_info=True)
            if isinstance(error, FundingStatusUnavailable):
                raise
            raise FundingStatusUnavailable("Could not resolve organization funding status") from error

        try:
            cache.set(cache_key, raw_status, timeout=30)
        except Exception:
            logger.warning("funding_status_cache_write_failed", exc_info=True)

        return funding_status

    def _get_default_billing_response(self, organization: Organization | None) -> dict[str, Any]:
        products = self.get_default_products(organization)
        response = {
            "available_product_features": [],
            "products": products["products"],
        }

        return response

    def get_default_products(self, organization: Organization | None) -> dict:
        response = {}
        # If we don't have products from the billing service then get the default ones with our local usage calculation
        products = self._get_products(organization)
        response["products"] = products

        return response

    def update_license_details(self, billing_status: BillingStatus) -> License:
        """
        Ensure the license details are up-to-date locally
        """
        if not self.license:  # mypy
            raise Exception("No license found")

        license_modified = False

        data = billing_status["license"]

        if not self.license.valid_until or self.license.valid_until < datetime.now(UTC) + timedelta(days=29):
            # NOTE: License validity is a legacy concept. For now we always extend the license validity by 30 days.
            self.license.valid_until = datetime.now(UTC) + timedelta(days=30)
            license_modified = True

        if self.license.plan != data["type"]:
            self.license.plan = data["type"]
            license_modified = True

        if license_modified:
            self.license.save()

        return self.license

    def _get_billing(self, organization: Organization, query_params: dict[str, Any] | None = None) -> BillingStatus:
        """
        Retrieves billing info and updates local models if necessary
        """
        if not self.license:  # mypy
            raise Exception("No license found")

        res = http_session.get(
            f"{BILLING_SERVICE_URL}/api/billing",
            headers=self.get_auth_headers(organization),
            params=query_params,
        )
        handle_billing_service_error(res)

        data = res.json()

        return data

    def _get_stripe_portal_url(self, organization: Organization) -> str:
        """
        Retrieves stripe protal url
        """
        if not self.license:  # mypy
            raise Exception("No license found")

        res = http_session.get(
            f"{BILLING_SERVICE_URL}/api/billing/portal",
            headers=self.get_auth_headers(organization),
        )

        handle_billing_service_error(res)

        data = res.json()

        return data["url"]

    def _get_products(self, organization: Organization | None):
        headers = {}
        params = {"plan": "standard"}

        if self.license and organization:
            headers = self.get_auth_headers(organization)

        res = http_session.get(
            f"{BILLING_SERVICE_URL}/api/products-v2",
            params=params,
            headers=headers,
        )

        handle_billing_service_error(res)

        return res.json().get("products", [])

    def update_org_details(self, organization: Organization, billing_status: BillingStatus) -> Organization:
        """
        Ensure the relevant organization details are up-to-date locally
        """
        computed_at = parse_datetime(billing_status.get("computed_at") or "")
        if computed_at is not None and _is_older_than_applied_billing_status(organization, computed_at):
            logger.info(
                "billing_status_out_of_order_skipped",
                organization_id=str(organization.id),
                computed_at=computed_at.isoformat(),
            )
            return organization

        org_modified = False

        data = billing_status["customer"]

        if data.get("customer_id") and organization.customer_id != data["customer_id"]:
            organization.customer_id = data["customer_id"]
            org_modified = True

        should_update_org_billing_quotas = False

        usage_summary = cast(dict, data.get("usage_summary"))
        if usage_summary:
            usage_info = OrganizationUsageInfo(
                events=usage_summary["events"],
                exceptions=usage_summary.get("exceptions", {}),
                recordings=usage_summary["recordings"],
                survey_responses=usage_summary.get("survey_responses", {}),
                rows_synced=usage_summary.get("rows_synced", {}),
                cdp_trigger_events=usage_summary.get("cdp_trigger_events", {}),
                rows_exported=usage_summary.get("rows_exported", {}),
                feature_flag_requests=usage_summary.get("feature_flag_requests", {}),
                api_queries_read_bytes=usage_summary.get("api_queries_read_bytes", {}),
                llm_events=usage_summary.get("llm_events", {}),
                mcp_events=usage_summary.get("mcp_events", {}),
                ai_credits=usage_summary.get("ai_credits", {}),
                signals_credits=usage_summary.get("signals_credits", {}),
                signals_spend_credits=usage_summary.get("signals_spend_credits", {}),
                posthog_code_credits=usage_summary.get("posthog_code_credits", {}),
                posthog_code_token_credits=usage_summary.get("posthog_code_token_credits", {}),
                sandbox_compute_credits=usage_summary.get("sandbox_compute_credits", {}),
                sandbox_compute_cpu_millicore_seconds=usage_summary.get("sandbox_compute_cpu_millicore_seconds", {}),
                sandbox_compute_memory_mib_seconds=usage_summary.get("sandbox_compute_memory_mib_seconds", {}),
                workflow_emails=usage_summary.get("workflow_emails", {}),
                workflow_push=usage_summary.get("workflow_push", {}),
                workflow_destinations_dispatched=usage_summary.get("workflow_destinations_dispatched", {}),
                logs_mb_ingested=usage_summary.get("logs_mb_ingested", {}),
                replay_vision_credits=usage_summary.get("replay_vision_credits", {}),
                period=[
                    data["billing_period"]["current_period_start"],
                    data["billing_period"]["current_period_end"],
                ],
            )

            had_quota_limiting_markers = _has_quota_limiting_markers(organization.usage)
            usage_changed = set_org_usage_summary(organization, new_usage=usage_info)
            if usage_changed and computed_at is None and organization.usage is not None:
                # The stored stamps describe an older total, so the quota check must not pair them with this one.
                for key in BILLING_STATUS_STAMP_KEYS:
                    cast(dict, organization.usage).pop(key, None)

            if usage_changed:
                org_modified = True

            should_update_org_billing_quotas = usage_changed or had_quota_limiting_markers

        available_product_features = data.get("available_product_features", None)
        revoked_feature_keys: set[str] = set()
        events_retention_changed = False
        # An empty list is deliberately ignored: this runs on hot paths (get_billing, usage
        # reports) and a partial or error-path billing response must not downgrade the org.
        # Genuine cancellations still send the (non-empty) free-tier feature list.
        if available_product_features and available_product_features != organization.available_product_features:
            previous_feature_keys = {
                feature.get("key") for feature in (organization.available_product_features or []) if feature
            }
            new_feature_keys = {feature.get("key") for feature in available_product_features if feature}
            revoked_feature_keys = previous_feature_keys - new_feature_keys
            previous_retention_months = organization_events_retention_months(organization)
            organization.available_product_features = data["available_product_features"]
            events_retention_changed = organization_events_retention_months(organization) != previous_retention_months
            org_modified = True

        never_drop_data = cast(bool | None, data.get("never_drop_data"))
        if never_drop_data != organization.never_drop_data:
            organization.never_drop_data = never_drop_data
            org_modified = True

        # A missing key (partial or error-path response) must not reset a known value to unknown.
        if "has_active_subscription" in data:
            has_active_subscription = data.get("has_active_subscription")
            # Trials run without a Stripe subscription, so a trialing org would otherwise read
            # as free tier and get metered; count an active trial as paid until it expires.
            if has_active_subscription is False and _free_trial_active(data):
                has_active_subscription = True
            if has_active_subscription != organization.has_active_subscription:
                organization.has_active_subscription = has_active_subscription
                org_modified = True

        customer_trust_scores = data.get("customer_trust_scores", {})

        if customer_trust_scores:
            product_key_to_usage_key = {
                product["type"]: product["usage_key"]
                for product in (
                    billing_status["customer"].get("products") or self.get_default_products(organization)["products"]
                )
            }
            org_customer_trust_scores = {}
            for product_key in customer_trust_scores:
                if product_key in product_key_to_usage_key:
                    org_customer_trust_scores[product_key_to_usage_key[product_key]] = customer_trust_scores[
                        product_key
                    ]

            current_customer_trust_scores = organization.customer_trust_scores or {}
            updated_customer_trust_scores = {
                **current_customer_trust_scores,
                **org_customer_trust_scores,
            }
            if updated_customer_trust_scores != current_customer_trust_scores:
                organization.customer_trust_scores = updated_customer_trust_scores
                org_modified = True

        # The stamp goes out only with a save that a change already needs. A save for the stamp
        # alone writes this in-memory copy back over counters and quota markers that the quota
        # run wrote in the meantime.
        if org_modified and computed_at is not None and organization.usage is not None:
            organization.usage["billing_status_computed_at"] = computed_at.isoformat()
            organization.usage["billing_latest_usage_report_date"] = billing_status.get("latest_usage_report_date")

        if org_modified:
            organization.save()

        if events_retention_changed:
            reconcile_organization_events_retention(organization)

        if revoked_feature_keys:
            reset_revoked_logs_retention(organization, revoked_feature_keys)

        if should_update_org_billing_quotas:
            update_org_billing_quotas(organization)

        return organization

    def get_auth_headers(
        self,
        organization: Organization,
        billing_provider: BillingProvider | None = None,
        authorizer_actor: User | None = None,
        service_action: str | None = None,
    ):
        if not self.license:  # mypy
            raise Exception("No license found")
        billing_service_token = build_billing_token(
            self.license,
            organization,
            self.user,
            authorizer_actor=authorizer_actor,
            billing_provider=billing_provider,
            service_action=service_action,
        )
        headers = {"Authorization": f"Bearer {billing_service_token}"}
        if self.ip_address:
            # Billing is called server-to-server, so it only ever sees PostHog's egress IP.
            # Forward the end-user's IP so billing can attach it to activity-log records.
            headers["X-PostHog-Actor-IP"] = self.ip_address
        return headers

    def organization_api_headers(self, organization: Organization, grants: EffectiveBillingGrants) -> dict[str, str]:
        """Headers for billing's /api/v2/billing/ routes: the PostHog-minted access token carrying the
        caller's grants, plus the end-user IP as on every other call."""
        headers = {"Authorization": f"Bearer {mint_billing_access_token(organization, grants, self.license)}"}
        if self.ip_address:
            headers["X-PostHog-Actor-IP"] = self.ip_address
        return headers

    def _organization_get(
        self,
        organization: Organization,
        grants: EffectiveBillingGrants,
        path: str,
        params: dict[str, Any] | None = None,
    ) -> dict[str, Any]:
        """One read of billing's organization API routes, with the envelope removed. Billing's own refusals
        come back as the matching DRF errors, so the caller sees why."""
        res = http_session.get(
            f"{BILLING_SERVICE_URL}/api/v2/billing/{path}",
            headers=self.organization_api_headers(organization, grants),
            params=params or None,
            timeout=BILLING_TIMESERIES_REQUEST_TIMEOUT,
        )
        _raise_for_organization_error(res)
        handle_billing_service_error(res, valid_codes=(200,))
        data = res.json()
        data.pop("status", None)
        data.pop("customer_id", None)
        return data

    def get_organization_subscription(
        self, organization: Organization, grants: EffectiveBillingGrants
    ) -> dict[str, Any]:
        return self._organization_get(organization, grants, "subscription/")

    def get_organization_features(self, organization: Organization, grants: EffectiveBillingGrants) -> dict[str, Any]:
        return self._organization_get(organization, grants, "features/")

    def get_organization_products(
        self,
        organization: Organization,
        grants: EffectiveBillingGrants,
        *,
        include_plans: bool = False,
        product_key: str | None = None,
    ) -> dict[str, Any]:
        path = f"products/{product_key}/" if product_key else "products/"
        return self._organization_get(organization, grants, path, {"include_plans": "true"} if include_plans else None)

    def get_organization_products_summary(
        self, organization: Organization, grants: EffectiveBillingGrants
    ) -> dict[str, Any]:
        # Billing serves this as products/catalog/, the name it shipped with.
        return self._organization_get(organization, grants, "products/catalog/")

    def get_organization_usage(self, organization: Organization, grants: EffectiveBillingGrants) -> dict[str, Any]:
        return self._organization_get(organization, grants, "usage/")

    def get_organization_usage_status(
        self, organization: Organization, grants: EffectiveBillingGrants
    ) -> dict[str, Any]:
        return self._organization_get(organization, grants, "usage/status/")

    def get_organization_spend(self, organization: Organization, grants: EffectiveBillingGrants) -> dict[str, Any]:
        return self._organization_get(organization, grants, "spend/")

    def get_organization_forecast(self, organization: Organization, grants: EffectiveBillingGrants) -> dict[str, Any]:
        return self._organization_get(organization, grants, "forecast/")

    def get_organization_export(
        self, organization: Organization, grants: EffectiveBillingGrants, kind: str, params: dict[str, Any]
    ) -> requests.Response:
        """Stream a usage or spend CSV from billing's organization export route, with the export
        timeout. Returns the response rather than parsed data, so the file streams through."""
        res = http_session.get(
            f"{BILLING_SERVICE_URL}/api/v2/billing/{kind}/export/",
            headers=self.organization_api_headers(organization, grants),
            params=self._to_query_params(params),
            timeout=BILLING_EXPORT_REQUEST_TIMEOUT,
            stream=True,
        )
        # A 404 here means billing lacks the route, so it stays a server error rather than "not found".
        _raise_for_organization_error(res, map_not_found=False)
        handle_billing_service_error(res, valid_codes=(200,))
        return res

    def get_organization_invoices(
        self,
        organization: Organization,
        grants: EffectiveBillingGrants,
        *,
        cursor: str | None = None,
        limit: int | None = None,
        status: str | None = None,
    ) -> dict[str, Any]:
        params = {key: value for key, value in (("cursor", cursor), ("limit", limit), ("status", status)) if value}
        return self._organization_get(organization, grants, "invoices/", params)

    def get_organization_invoice_pdf_url(
        self, organization: Organization, grants: EffectiveBillingGrants, invoice_id: str
    ) -> str:
        url = self._organization_get(organization, grants, f"invoices/{invoice_id}/pdf-url/").get("url")
        if not url:
            raise NotFound(f"No document for invoice {invoice_id}.")
        return url

    def get_organization_limits(self, organization: Organization, grants: EffectiveBillingGrants) -> dict[str, Any]:
        return self._organization_get(organization, grants, "limits/")

    def get_organization_projects(self, organization: Organization, grants: EffectiveBillingGrants) -> dict[str, Any]:
        return self._organization_get(organization, grants, "projects/")

    def get_organization_timeseries(
        self, organization: Organization, grants: EffectiveBillingGrants, kind: str, params: dict[str, Any]
    ) -> dict[str, Any]:
        """The usage or spend timeseries copy. GET first, then POST when the query string is too long
        for the organization's teams map, as the root usage and spend reads do."""
        url = f"{BILLING_SERVICE_URL}/api/v2/billing/{kind}/timeseries/"
        headers = self.organization_api_headers(organization, grants)
        res = http_session.get(
            url, headers=headers, params=self._to_query_params(params), timeout=BILLING_TIMESERIES_REQUEST_TIMEOUT
        )
        if res.status_code in (414, 431):
            res = http_session.post(
                url, headers=headers, json=self._to_post_body(params), timeout=BILLING_TIMESERIES_REQUEST_TIMEOUT
            )
        # A 404 here means the route is missing rather than the resource, so it stays a server error.
        _raise_for_organization_error(res, map_not_found=False)
        handle_billing_service_error(res, valid_codes=(200,))
        data = res.json()
        data.pop("status", None)
        data.pop("customer_id", None)
        return data

    def get_invoices(self, organization: Organization, status: str | None):
        res = http_session.get(
            # TODO(@zach): update this to /api/invoices
            f"{BILLING_SERVICE_URL}/api/billing/get_invoices",
            params={"status": status},
            headers=self.get_auth_headers(organization),
        )

        handle_billing_service_error(res)

        data = res.json()

        return data

    def credits_overview(self, organization: Organization):
        res = http_session.get(
            f"{BILLING_SERVICE_URL}/api/credits/overview",
            headers=self.get_auth_headers(organization),
        )

        handle_billing_service_error(res)

        return res.json()

    def purchase_credits(self, organization: Organization, data: dict[str, Any]):
        res = http_session.post(
            f"{BILLING_SERVICE_URL}/api/credits/purchase",
            headers=self.get_auth_headers(organization),
            json=data,
        )

        handle_billing_service_error(res)

        return res.json()

    def dispute_signals_pr(self, organization: Organization, data: dict[str, Any]) -> dict[str, Any]:
        """Ask billing to credit back a refunded Signals PR (idempotent on data['refund_id']).

        Billing returns 200 for every handled business outcome, including $0 credits; any other
        status means "not handled" and must raise so the caller retries. The default valid_codes
        would swallow 404 (endpoint not deployed) and 401 (auth failure) as success and record an
        error body as a synced credit, hence the explicit (200,).
        """
        res = http_session.post(
            f"{BILLING_SERVICE_URL}/api/signals/dispute-pr",
            # The service_action claim is required by billing: it distinguishes this
            # backend-minted token from ones minted for user-initiated billing calls,
            # which cannot reach the dispute endpoint.
            headers=self.get_auth_headers(organization, service_action="signals_pr_dispute"),
            json=data,
            timeout=30,
        )

        handle_billing_service_error(res, valid_codes=(200,))

        return res.json()

    def record_rated_usage(self, organization: Organization, items: list[dict[str, str | int]]) -> None:
        res = http_session.post(
            f"{BILLING_SERVICE_URL}/api/rated-usage",
            headers=self.get_auth_headers(organization, service_action="rated_usage"),
            json={"items": items},
            timeout=30,
        )
        handle_billing_service_error(res, valid_codes=(200,))
        body = res.json()
        results = body.get("results") if isinstance(body, dict) else None
        if (
            not isinstance(results, list)
            or len(results) != len(items)
            or any(result not in ("created", "replayed") for result in results)
        ):
            raise ValueError("Billing did not accept every rated usage item")

    def _system_auth_headers(self, service_action: str) -> dict[str, str]:
        if not self.license:  # mypy
            raise Exception("No license found")
        return {"Authorization": f"Bearer {build_billing_system_token(self.license, service_action)}"}

    def set_organizations_deactivated(self, organization_ids: list[str], deactivated: bool) -> dict[str, Any]:
        """Set or remove billing's forecast-exclusion flag for these organizations.

        Billing returns 200 for every handled outcome. The default valid_codes would swallow
        404 (endpoint not deployed) and 401 (auth failure) as success, so the caller would
        record a sync that never happened, hence the explicit (200,).
        """
        res = http_session.post(
            f"{BILLING_SERVICE_URL}/api/internal/deactivated-organizations",
            headers=self._system_auth_headers(DEACTIVATED_ORGANIZATIONS_SERVICE_ACTION),
            json={"organization_ids": organization_ids, "deactivated": deactivated},
            timeout=30,
        )

        handle_billing_service_error(res, valid_codes=(200,))

        return res.json()

    def get_deactivated_organizations(self) -> list[str]:
        """Organization ids billing currently excludes from the revenue forecast."""
        res = http_session.get(
            f"{BILLING_SERVICE_URL}/api/internal/deactivated-organizations",
            headers=self._system_auth_headers(DEACTIVATED_ORGANIZATIONS_SERVICE_ACTION),
            timeout=30,
        )

        handle_billing_service_error(res, valid_codes=(200,))

        return res.json()["deactivated_organization_ids"]

    def activate_trial(self, organization: Organization, data: dict[str, Any]):
        res = http_session.post(
            f"{BILLING_SERVICE_URL}/api/trials/activate",
            headers=self.get_auth_headers(organization),
            json=data,
        )

        handle_billing_service_error(res)

        # A full status carries `computed_at`, so a status queued before the trial change can't roll it back.
        self.get_billing(organization)

        return res.json()

    def cancel_trial(self, organization: Organization, data: dict[str, Any]):
        res = http_session.post(
            f"{BILLING_SERVICE_URL}/api/trials/cancel",
            headers=self.get_auth_headers(organization),
            json=data,
        )

        handle_billing_service_error(res)

        # A full status carries `computed_at`, so a status queued before the trial change can't roll it back.
        self.get_billing(organization)

    def authorize(self, organization: Organization, billing_provider: BillingProvider | None = None):
        """
        Authorize billing for an organization, optionally through a marketplace provider.

        Args:
            organization: The organization to authorize billing for
            billing_provider: Optional marketplace provider (e.g., "vercel"). If provided, the organization
                            must have a corresponding integration configured.

        Raises:
            ValueError: If billing_provider is specified but the organization doesn't have the integration
            BillingManagedByPartnerError: If a partner pays for the organization and it has no Stripe customer
        """
        raise_if_billing_managed_by_partner(organization)

        # Validate that organization has the integration if billing_provider is specified
        if billing_provider:
            from posthog.models import OrganizationIntegration

            has_integration = OrganizationIntegration.objects.filter(
                organization=organization,
                kind=billing_provider,  # kind matches billing_provider value
            ).exists()

            if not has_integration:
                raise ValueError(f"Organization does not have a {billing_provider} integration configured")

        data = {"billing_provider": billing_provider}

        res = http_session.post(
            f"{BILLING_SERVICE_URL}/api/activate/authorize",
            headers=self.get_auth_headers(organization, billing_provider),
            json=data,
        )

        handle_billing_service_error(res, valid_codes=(200, 201))

        return res.json()

    def authorize_with_shared_payment_token(self, organization: Organization, shared_payment_token: str) -> None:
        raise_if_billing_managed_by_partner(organization)

        res = http_session.post(
            f"{BILLING_SERVICE_URL}/api/activate/authorize",
            headers=self.get_auth_headers(organization),
            json={"shared_payment_token": shared_payment_token},
            timeout=30,
        )

        handle_billing_service_error(res, valid_codes=(200, 201))

    def authorize_status(self, organization: Organization, data: dict[str, Any]):
        res = http_session.post(
            f"{BILLING_SERVICE_URL}/api/activate/authorize/status",
            headers=self.get_auth_headers(organization),
            json=data,
        )

        handle_billing_service_error(res)

        return res.json()

    def deauthorize(self, organization: Organization, billing_provider: BillingProvider) -> dict[str, Any]:
        """
        Deauthorize billing for an organization when a marketplace provider uninstalls.

        This cancels the Stripe subscription and resets the billing provider to default,
        effectively ending the customer's paid access through the marketplace.

        Args:
            organization: The organization to deauthorize billing for
            billing_provider: The marketplace provider being uninstalled (e.g., "vercel")

        Returns:
            Response from billing service with success status
        """
        res = http_session.post(
            f"{BILLING_SERVICE_URL}/api/activate/authorize/uninstall",
            headers=self.get_auth_headers(organization),
            json={"billing_provider": billing_provider.value},
            timeout=30,
        )

        if res.status_code == 409:
            try:
                data = res.json()
            except JSONDecodeError:
                data = {}
            if data.get("code") == BillingAPIErrorCodes.OPEN_INVOICES_ERROR.value:
                raise BillingServiceOpenInvoicesError(data.get("error_message", "Open invoices must be resolved first"))

        handle_billing_service_error(res, valid_codes=(200,))

        return res.json()

    def switch_plan(self, organization: Organization, data: dict[str, Any]) -> dict[str, Any]:
        res = http_session.post(
            f"{BILLING_SERVICE_URL}/api/subscription/switch-plan/",
            headers=self.get_auth_headers(organization),
            json=data,
        )

        handle_billing_service_error(res)
        # A full status carries `computed_at`, so a status queued before the plan switch can't roll it back.
        self.get_billing(organization)

        return res.json()

    def apply_startup_program(self, organization: Organization, data: dict[str, Any]) -> dict[str, Any]:
        res = http_session.post(
            f"{BILLING_SERVICE_URL}/api/startups/apply",
            json=data,
            headers=self.get_auth_headers(organization),
        )

        handle_billing_service_error(res)
        return res.json()

    def claim_coupon(self, organization: Organization, data: dict[str, Any]) -> dict[str, Any]:
        res = http_session.post(
            f"{BILLING_SERVICE_URL}/api/coupons/claim",
            json=data,
            headers=self.get_auth_headers(organization),
        )

        handle_billing_service_error(res)
        return res.json()

    def coupons_overview(self, organization: Organization) -> dict[str, Any]:
        res = http_session.get(
            f"{BILLING_SERVICE_URL}/api/coupons/overview",
            headers=self.get_auth_headers(organization),
        )

        handle_billing_service_error(res)
        return res.json()

    def get_billing_status_for_alerts(self, organization: Organization) -> dict[str, Any]:
        """Read billing status for billing alert evaluation.

        Evaluation runs as a backend job without an acting user, so the token carries the
        billing alerts service_action claim instead of a user role claim.
        """
        res = http_session.get(
            f"{BILLING_SERVICE_URL}/api/billing",
            headers=self.get_auth_headers(organization, service_action=BILLING_ALERTS_EVALUATION_SERVICE_ACTION),
            timeout=BILLING_TIMESERIES_REQUEST_TIMEOUT,
        )
        handle_billing_service_error(res)
        return res.json()

    def get_usage_data(self, organization: Organization, params: dict[str, Any]) -> dict[str, Any]:
        return self._request_with_post_fallback(organization, "/api/v2/usage/", params)

    def get_spend_csv(self, organization: Organization, params: dict[str, Any]) -> requests.Response:
        """Stream the spend breakdown as CSV. See get_usage_csv."""
        return self._get_csv(organization, "/api/v2/spend/export/", params)

    def get_usage_csv(self, organization: Organization, params: dict[str, Any]) -> requests.Response:
        """Stream the usage breakdown as CSV.

        Returns the response rather than parsed data: the body is a file passed through to the
        browser, and buffering it here would stop it streaming.
        """
        return self._get_csv(organization, "/api/v2/usage/export/", params)

    def _get_csv(self, organization: Organization, path: str, params: dict[str, Any]) -> requests.Response:
        """GET a streamed CSV from billing with the export timeout, BILLING_EXPORT_REQUEST_TIMEOUT."""
        res = http_session.get(
            f"{BILLING_SERVICE_URL}{path}",
            headers=self.get_auth_headers(organization),
            params=self._to_query_params(params),
            timeout=BILLING_EXPORT_REQUEST_TIMEOUT,
            stream=True,
        )
        handle_billing_service_error(res)
        return res

    def get_spend_data(self, organization: Organization, params: dict[str, Any]) -> dict[str, Any]:
        return self._request_with_post_fallback(organization, "/api/v2/spend/", params)

    def get_usage_team_options(self, organization: Organization) -> dict[str, Any]:
        """The project ids that have appeared in the organization's usage reports, for the project filter."""
        return self._request_with_post_fallback(organization, "/api/v2/usage/team_options/", {})

    def _request_with_post_fallback(
        self, organization: Organization, path: str, params: dict[str, Any]
    ) -> dict[str, Any]:
        """
        GET with automatic POST fallback for large payloads.

        Tries GET first with query params. If the server responds with 414
        (URI Too Long) or 431 (Request Header Fields Too Large), retries as
        POST with a JSON body. This handles orgs with many teams whose
        teams_map serialization exceeds URL/header limits.
        """
        url = f"{BILLING_SERVICE_URL}{path}"
        headers = self.get_auth_headers(organization)

        res = http_session.get(
            url,
            headers=headers,
            params=self._to_query_params(params),
            timeout=BILLING_TIMESERIES_REQUEST_TIMEOUT,
        )

        if res.status_code in (414, 431):
            logger.info(
                "billing_get_to_post_fallback",
                path=path,
                status_code=res.status_code,
                organization_id=str(organization.id),
            )
            res = http_session.post(
                url,
                headers=headers,
                json=self._to_post_body(params),
                timeout=BILLING_TIMESERIES_REQUEST_TIMEOUT,
            )

        handle_billing_service_error(res)
        return res.json()

    @staticmethod
    def _to_query_params(params: dict[str, Any]) -> dict[str, Any]:
        """Serialize complex types to JSON strings for GET query params."""
        result = {}
        for k, v in params.items():
            if isinstance(v, (dict, list)):
                result[k] = json.dumps(v)
            elif isinstance(v, UUID):
                result[k] = str(v)
            else:
                result[k] = v
        return result

    @staticmethod
    def _to_post_body(params: dict[str, Any]) -> dict[str, Any]:
        """Convert params to a JSON-safe POST body.

        Handles two conversions: UUIDs are stringified, and string values
        that contain JSON arrays or objects (from frontend query-param
        encoding) are parsed back into native types so the billing service
        receives structured data rather than escaped strings.
        """
        result: dict[str, Any] = {}
        for k, v in params.items():
            if isinstance(v, UUID):
                result[k] = str(v)
            elif isinstance(v, str):
                try:
                    parsed = json.loads(v)
                    if isinstance(parsed, (list, dict)):
                        result[k] = parsed
                    else:
                        result[k] = v
                except (json.JSONDecodeError, ValueError):
                    result[k] = v
            else:
                result[k] = v
        return result

    def handle_billing_provider_webhook(
        self,
        event_type: str,
        event_data: dict[str, Any],
        organization: Organization,
        billing_provider: str,
    ) -> None:
        """
        Forward billing provider webhook to billing service for processing.

        Pure passthrough - no transformation of event data.
        Raises exception on failure (causes webhook endpoint to return 500, triggering provider retry).
        """
        body = json.dumps(
            {
                "event_type": event_type,
                "event_data": event_data,
                "billing_provider": billing_provider,
            },
            allow_nan=False,
            separators=(",", ":"),
        ).encode("utf-8")
        headers = {
            **self.get_auth_headers(organization),
            **build_billing_provider_webhook_signature_headers(body),
            "Content-Type": "application/json",
        }

        res = http_session.post(
            f"{BILLING_SERVICE_URL}/api/webhooks/billing-provider",
            headers=headers,
            data=body,
            timeout=30,
        )

        if not res.ok:
            logger.error(
                "billing_provider_webhook_error",
                event_type=event_type,
                billing_provider=billing_provider,
                status_code=res.status_code,
                response_text=res.text[:500] if res.text else "",
            )
            raise Exception(f"Billing service returned {res.status_code}: {res.text}")