Ir para o conteúdo

tempest_fastapi_sdk.integrations.subscriptions.revenuecat

RevenueCat: assinaturas in-app da App Store e do Google Play.

« Integrações e pagamentos


RevenueCatClient

RevenueCatClient(http: HTTPClient)

The RevenueCat calls a subscription backend needs from the server.

Example

client = RevenueCatClient(revenuecat_http_client("sk_...")) info = await client.get_subscriber("user-1456") info.subscriber.entitlements.keys()

Wrap an HTTP client already pointed at the API.

Parameters:

Name Type Description Default
http HTTPClient

From :func:revenuecat_http_client, or HTTPClient(**settings.revenuecat_kwargs()).

required

get_subscriber async

get_subscriber(app_user_id: str) -> RevenueCatCustomerInfo

Read a customer's current info (GET /subscribers/{app_user_id}).

Does not send X-Platform: the reference says not to set it "if you are calling the getter for informational purposes or using a secret API key", because it updates the customer's last_seen.

Parameters:

Name Type Description Default
app_user_id str

The App User ID (any of the subscriber's aliases works).

required

Returns:

Name Type Description
RevenueCatCustomerInfo RevenueCatCustomerInfo

The customer info. A 201 (customer

RevenueCatCustomerInfo

just created — see the module warning) parses the same way.

Raises:

Type Description
ValueError

If app_user_id is empty, . or .. — the path would collapse to /subscribers/, or the HTTP client would resolve the dot segment and send the request to another endpoint with the secret key.

HTTPStatusError

For any non-2xx answer (401 for a bad key, 400 for a malformed id).

revenuecat_http_client

revenuecat_http_client(
    api_key: str,
    *,
    base_url: str = REVENUECAT_API_BASE_URL,
    timeout: float = 10.0,
    retry_policy: RetryPolicy | None = None,
    transport: AsyncBaseTransport | None = None,
) -> HTTPClient

Build the :class:~tempest_fastapi_sdk.utils.HTTPClient RevenueCat expects.

Parameters:

Name Type Description Default
api_key str

A secret API key (sk_...) from the dashboard.

required
base_url str

API host; override only for a proxy or a recorded fixture server.

REVENUECAT_API_BASE_URL
timeout float

Per-request timeout, seconds.

10.0
retry_policy RetryPolicy | None

Retry behaviour; None keeps the SDK default. The only call is a read, so retrying is safe.

None
transport AsyncBaseTransport | None

Transport override — httpx.MockTransport in tests.

None

Returns:

Name Type Description
HTTPClient HTTPClient

A client with Authorization: Bearer <key> and JSON

HTTPClient

accept headers set.

REVENUECAT_API_BASE_URL module-attribute

REVENUECAT_API_BASE_URL: str = 'https://api.revenuecat.com/v1'

Base URL of the REST API v1, from https://www.revenuecat.com/docs/api-v1.

make_revenuecat_webhook_router

make_revenuecat_webhook_router(
    *,
    inbox: WebhookInbox[Any],
    secret: SecretSource | None,
    signing_secret: SecretSource | None = None,
    on_recorded: Callable[[UUID], Awaitable[object]] | None = None,
    path: str = "/webhooks/revenuecat",
    tags: list[str] | None = None,
    include_in_schema: bool = True,
    tolerance_seconds: int = DEFAULT_SIGNATURE_TOLERANCE_SECONDS,
    docs_locale: str | None = None,
) -> APIRouter

Mount the whole RevenueCat webhook: authenticate, record, answer 200.

The route does no business logic. It records the event in inbox under (provider="revenuecat", external_id=event.id) with the body's model_dump — which leaves subscriber_attributes out — and answers 200. A repeated event.id records nothing and still answers 200. Processing happens later, through :meth:~tempest_fastapi_sdk.db.WebhookInbox.process or the scheduled :meth:~tempest_fastapi_sdk.db.WebhookInbox.drain_once.

Parameters:

Name Type Description Default
inbox WebhookInbox[Any]

Where events are recorded.

required
secret SecretSource | None

The Authorization value; see :func:make_revenuecat_webhook_dependency.

required
signing_secret SecretSource | None

The HMAC signing secret.

None
on_recorded Callable[[UUID], Awaitable[object]] | None

Awaited with the inbox id of a newly recorded event — enqueue the processing task here. Not called for a repeat. If it raises, the event is already recorded and the sweep picks it up, so the route still answers 200.

None
path str

Route path.

'/webhooks/revenuecat'
tags list[str] | None

OpenAPI tags.

None
include_in_schema bool

Whether the route appears in OpenAPI.

True
tolerance_seconds int

Signature timestamp window.

DEFAULT_SIGNATURE_TOLERANCE_SECONDS
docs_locale str | None

Language of the OpenAPI summary and description text — "en-US" or "pt-BR". None (default) reads API_DOCS_LOCALE through :class:~tempest_fastapi_sdk.settings.ServerSettings, whose default is "en-US".

None

Returns:

Name Type Description
APIRouter APIRouter

Ready for app.include_router.

Raises:

Type Description
ValueError

When both secret and signing_secret are None.

make_revenuecat_webhook_dependency

make_revenuecat_webhook_dependency(
    secret: SecretSource | None,
    *,
    signing_secret: SecretSource | None = None,
    tolerance_seconds: int = DEFAULT_SIGNATURE_TOLERANCE_SECONDS,
    error_message: str = "Invalid RevenueCat webhook credentials",
) -> Callable[..., Coroutine[Any, Any, RevenueCatWebhookDelivery]]

Build a FastAPI dependency that authenticates and parses a delivery.

Each secret is resolved per request, and every one that resolves to a value must pass. So secret="" with a filled signing_secret is HMAC only, and the reverse is Authorization only — the reading :class:~tempest_fastapi_sdk.settings.RevenueCatSettings applies at boot. When neither resolves to a value the request is refused: emptiness fails closed, it never opens the endpoint.

Parameters:

Name Type Description Default
secret SecretSource | None

The Authorization value configured in the dashboard, or a function returning it per request. None or a value that resolves to empty skips this check.

required
signing_secret SecretSource | None

The HMAC signing secret, when signing is enabled on the integration. None or a value that resolves to empty skips this check.

None
tolerance_seconds int

Signature timestamp window, in seconds.

DEFAULT_SIGNATURE_TOLERANCE_SECONDS
error_message str

Message of the 401.

'Invalid RevenueCat webhook credentials'

Returns:

Type Description
Callable[..., Coroutine[Any, Any, RevenueCatWebhookDelivery]]

Callable[..., Coroutine[Any, Any, RevenueCatWebhookDelivery]]: The

Callable[..., Coroutine[Any, Any, RevenueCatWebhookDelivery]]

async dependency.

Raises:

Type Description
ValueError

When both secret and signing_secret are None — that endpoint would accept anyone.

UnauthorizedException

(401, from the dependency) When a configured check fails (header missing or wrong), or when neither secret resolves to a value for this request.

ValidationException

(422, from the dependency) When an authenticated body is not a valid event.

RevenueCatWebhookDelivery dataclass

RevenueCatWebhookDelivery(
    webhook: RevenueCatWebhook, event_type: RevenueCatEventTypeEnum | None, body: bytes
)

An authenticated, parsed RevenueCat delivery.

Attributes:

Name Type Description
webhook RevenueCatWebhook

The parsed body.

event_type RevenueCatEventTypeEnum | None

The type as an enum member, or None for a type this release does not know.

body bytes

The raw body, byte for byte.

RevenueCatWebhookAck

Bases: BaseModel

What the router answers RevenueCat.

Attributes:

Name Type Description
recorded bool

True for the first delivery of this event, False for a repeat (still a 200: RevenueCat only needs to stop retrying).

event_id str

RevenueCat's event id.

SecretSource module-attribute

SecretSource = str | Callable[[Request], str]

A secret, or a function reading it per request (rotation, multi-tenant).

verify_authorization

verify_authorization(header: str, secret: str) -> bool

Check the Authorization header against the configured value.

Accepts the value with or without a Bearer prefix, on either side: the dashboard field is free text, and services store both spellings.

Parameters:

Name Type Description Default
header str

The received header value.

required
secret str

The value configured in the dashboard.

required

Returns:

Name Type Description
bool bool

True only when secret is non-empty and the header

bool

matches it, compared in constant time.

verify_signature

verify_signature(
    body: bytes,
    header: str,
    secret: str,
    *,
    tolerance_seconds: int = DEFAULT_SIGNATURE_TOLERANCE_SECONDS,
    now: float | None = None,
) -> bool

Check an HMAC-signed RevenueCat delivery.

Parameters:

Name Type Description Default
body bytes

The raw body, exactly as received. Re-serialized JSON changes the bytes and fails, as the documentation warns.

required
header str

The X-RevenueCat-Webhook-Signature value.

required
secret str

The integration's signing secret.

required
tolerance_seconds int

Maximum abs(now - t). 0 disables the window, and with it the replay protection.

DEFAULT_SIGNATURE_TOLERANCE_SECONDS
now float | None

Current epoch seconds; injectable for tests.

None

Returns:

Name Type Description
bool bool

True when secret is non-empty, t is inside the

bool

window and a v1 matches in constant time.

sign_payload

sign_payload(body: bytes, secret: str, *, timestamp: int) -> str

Build the signature header RevenueCat would send for body.

For tests: a suite that signs by hand re-derives the "<timestamp>.<body>" detail, and a test that signs the wrong thing passes against a verifier that checks the wrong thing.

Parameters:

Name Type Description Default
body bytes

The raw body.

required
secret str

The integration's signing secret.

required
timestamp int

Epoch seconds.

required

Returns:

Name Type Description
str str

A t=...,v1=... header value.

parse_signature_header

parse_signature_header(header: str) -> tuple[int | None, tuple[str, ...]]

Split X-RevenueCat-Webhook-Signature into timestamp and signatures.

Parameters:

Name Type Description Default
header str

The raw header value.

required

Returns:

Type Description
int | None

tuple[int | None, tuple[str, ...]]: t as an integer (None

tuple[str, ...]

when absent or not a number) and every v1 value.

parse_webhook

parse_webhook(body: bytes) -> RevenueCatWebhook

Decode an authenticated body into :class:RevenueCatWebhook.

Parameters:

Name Type Description Default
body bytes

The raw body.

required

Returns:

Name Type Description
RevenueCatWebhook RevenueCatWebhook

The parsed body.

Raises:

Type Description
ValidationException

(422) When the body is not JSON or has no event.id / event.type — without an id there is nothing to deduplicate on, and RevenueCat will retry the delivery.

REVENUECAT_PROVIDER module-attribute

REVENUECAT_PROVIDER: str = 'revenuecat'

provider value the router records events under in the inbox.

REVENUECAT_AUTHORIZATION_HEADER module-attribute

REVENUECAT_AUTHORIZATION_HEADER: str = 'Authorization'

Header carrying the value configured in the RevenueCat dashboard.

REVENUECAT_SIGNATURE_HEADER module-attribute

REVENUECAT_SIGNATURE_HEADER: str = 'X-RevenueCat-Webhook-Signature'

Header carrying t=<timestamp>,v1=<hex> when HMAC signing is on.

DEFAULT_SIGNATURE_TOLERANCE_SECONDS module-attribute

DEFAULT_SIGNATURE_TOLERANCE_SECONDS: int = 300

Accepted distance between t and now: the documentation's 5 minutes.

normalize

Reduce one RevenueCat event to a :class:SubscriptionSnapshot.

Never raises on an event type: an unknown one gives :attr:SubscriptionStatusEnum.UNKNOWN with the identity fields filled, so the service can log it and move on.

Parameters:

Name Type Description Default
event RevenueCatEvent

The parsed event.

required

Returns:

Name Type Description
SubscriptionSnapshot SubscriptionSnapshot

The state and the fields that go with it.

SubscriptionSnapshot dataclass

SubscriptionSnapshot(
    status: SubscriptionStatusEnum,
    event_id: str,
    event_type: str,
    app_user_id: str | None = None,
    original_app_user_id: str | None = None,
    aliases: tuple[str, ...] = tuple(),
    product_id: str | None = None,
    new_product_id: str | None = None,
    entitlement_ids: tuple[str, ...] = tuple(),
    period_type: str | None = None,
    store: str | None = None,
    environment: str | None = None,
    purchased_at: datetime | None = None,
    period_end: datetime | None = None,
    grace_period_end: datetime | None = None,
    reason: str | None = None,
    event_at: datetime | None = None,
)

The subscription state one event leaves behind.

A dataclass rather than a schema: it is a value the service reads and branches on, and keeping :attr:status an enum member (not a bare string) keeps snapshot.status is SubscriptionStatusEnum.EXPIRED true.

Attributes:

Name Type Description
status SubscriptionStatusEnum

The normalized state.

event_id str

The event it came from.

event_type str

The event type, as delivered.

app_user_id str | None

Last seen App User ID.

original_app_user_id str | None

First App User ID.

aliases tuple[str, ...]

Every App User ID of the subscriber.

product_id str | None

Product of the subscription.

new_product_id str | None

Product switched to, on a PRODUCT_CHANGE.

entitlement_ids tuple[str, ...]

Entitlements of the product.

period_type str | None

TRIAL, INTRO, NORMAL, ...

store str | None

Store of the purchase.

environment str | None

SANDBOX or PRODUCTION.

purchased_at datetime | None

Start of the period, UTC.

period_end datetime | None

End of the period, UTC; None for a lifetime or one-off purchase.

grace_period_end datetime | None

End of the grace period, UTC.

reason str | None

cancel_reason or expiration_reason.

event_at datetime | None

When RevenueCat generated the event, UTC. Order by this to discard a late delivery of an older event.

SubscriptionStatusEnum

Bases: BaseStrEnum

Normalized state of a subscription after one event.

  • TRIAL — active, in a free trial period.
  • ACTIVE — active and paid (or a one-off purchase).
  • CANCELLED — renewal turned off; access normally lasts until period_end.
  • BILLING_ISSUE — a charge failed; not expired. grace_period_end says how long the store keeps trying, when it has a grace period.
  • PAUSE_SCHEDULED — a Google Play pause starts at the end of the period; access continues until then.
  • PAUSED — the pause started; access is gone until it resumes.
  • EXPIRED — access should be removed.
  • REFUNDED — the latest period was refunded.
  • TEMPORARY_GRANT — RevenueCat granted access for at most 24 hours while it could not validate the purchase.
  • NO_CHANGE — a documented event that does not move the state.
  • UNKNOWN — an event type this release does not know.

RevenueCatWebhook

Bases: BaseModel

The whole body RevenueCat POSTs: api_version plus event.

Attributes:

Name Type Description
api_version str

Version of the webhook format ("1.0").

event RevenueCatEvent

The event.

RevenueCatEvent

Bases: BaseModel

The event object of a RevenueCat webhook (format 1.0).

Field names and meanings come from the documentation's field tables. Only the fields that drive a decision are named; the rest (price, tax_percentage, adjustments, transferred_from, ...) stay readable through model_extra.

Attributes:

Name Type Description
id str

Unique id of the event. "Retries reuse the same id" — this is the inbox's idempotency key.

type str

The event type, as delivered. Compare with :class:~tempest_fastapi_sdk.integrations.subscriptions.revenuecat.RevenueCatEventTypeEnum.

event_timestamp_ms int | None

When the event was generated.

app_id str | None

Dashboard app the event belongs to.

app_user_id str | None

Last seen App User ID.

original_app_user_id str | None

First App User ID used.

aliases list[str]

Every App User ID the subscriber used. The documentation says to search both this and original_app_user_id when looking a user up.

product_id str | None

Product of the subscription.

new_product_id str | None

Product switched to, on some PRODUCT_CHANGE events.

entitlement_ids list[str]

Entitlements of the product. null in the payload becomes [].

period_type str | None

TRIAL, INTRO, NORMAL, ...

purchased_at_ms int | None

Purchase time, epoch milliseconds.

expiration_at_ms int | None

End of the period; None for lifetime and non-subscription purchases.

grace_period_expiration_at_ms int | None

Only on BILLING_ISSUE.

auto_resume_at_ms int | None

Only on SUBSCRIPTION_PAUSED.

environment str | None

SANDBOX or PRODUCTION.

store str | None

Store of the purchase.

transaction_id str | None

Store transaction id.

original_transaction_id str | None

First transaction of the subscription.

cancel_reason str | None

Only on CANCELLATION.

expiration_reason str | None

Only on EXPIRATION.

is_trial_conversion bool | None

Only on RENEWAL.

experiments list[RevenueCatExperiment]

Experiments the subscriber was enrolled in.

subscriber_attributes dict[str, Any]

Customer attributes. Excluded from model_dump(); see the module docstring.

RevenueCatExperiment

Bases: BaseModel

One entry of an event's experiments array.

Attributes:

Name Type Description
experiment_id str | None

ID of the experiment.

experiment_variant str | None

Variant the subscriber was in.

enrolled_at_ms int | None

Enrollment time, epoch milliseconds.

RevenueCatCustomerInfo

Bases: BaseModel

Body of GET /v1/subscribers/{app_user_id}.

Attributes:

Name Type Description
request_date datetime | None

When RevenueCat answered.

request_date_ms int | None

The same, epoch milliseconds.

subscriber RevenueCatSubscriber

The customer.

RevenueCatSubscriber

Bases: BaseModel

subscriber of the v1 customer info.

Attributes:

Name Type Description
original_app_user_id str | None

App User ID the customer was first known by.

first_seen datetime | None

When RevenueCat first saw the customer.

last_seen datetime | None

When RevenueCat last saw the customer.

management_url str | None

Where the customer manages the active subscription; None when there is none.

entitlements dict[str, RevenueCatEntitlement]

Every entitlement, expired ones included.

subscriptions dict[str, RevenueCatSubscription]

Subscriptions by product id.

non_subscriptions dict[str, list[dict[str, Any]]]

One-off purchases by product id.

subscriber_attributes dict[str, Any]

Only sent to a secret key. Excluded from model_dump().

RevenueCatSubscription

Bases: BaseModel

One entry of subscriber.subscriptions (keyed by product id).

store_transaction_id is typed str | int because the documentation's own sample carries both shapes (a GPA.… string and 1000000652379790 as a number).

Attributes:

Name Type Description
expires_date datetime | None

End of the current period.

purchase_date datetime | None

Start of the current period.

original_purchase_date datetime | None

First purchase.

period_type str | None

normal, trial, intro (lowercase in this API, unlike the webhook).

store str | None

app_store, play_store, ... (lowercase).

is_sandbox bool | None

Whether the purchase is a sandbox one.

unsubscribe_detected_at datetime | None

When auto-renew was turned off.

billing_issues_detected_at datetime | None

When a charge failed.

grace_period_expires_date datetime | None

End of the grace period.

refunded_at datetime | None

When it was refunded.

auto_resume_date datetime | None

When a paused subscription resumes.

ownership_type str | None

PURCHASED or FAMILY_SHARED.

store_transaction_id str | int | None

The store's transaction id.

RevenueCatEntitlement

Bases: BaseModel

One entry of subscriber.entitlements (keyed by entitlement id).

Attributes:

Name Type Description
expires_date datetime | None

When access ends; None for lifetime.

grace_period_expires_date datetime | None

End of the grace period.

product_identifier str | None

Product granting the entitlement.

purchase_date datetime | None

Latest purchase date.

RevenueCatEventTypeEnum

Bases: BaseStrEnum

Every event.type the RevenueCat documentation lists.

Grouped as the documentation groups them. SUBSCRIBER_ALIAS is marked deprecated there ("New projects don't receive this webhook") and stays here because older projects still do.

RevenueCatPeriodTypeEnum

Bases: BaseStrEnum

period_type of a subscription lifecycle event.

RevenueCatEnvironmentEnum

Bases: BaseStrEnum

environment — decided by the store transaction, not by RevenueCat.

The webhooks page says RevenueCat "itself does not have sandbox and production environments", so the same customer can carry both.

RevenueCatStoreEnum

Bases: BaseStrEnum

store the purchase belongs to.

RevenueCatReasonEnum

Bases: BaseStrEnum

Reason of a CANCELLATION or of an EXPIRATION.

One vocabulary for both fields, as the documentation's "Cancellation and Expiration Reasons" table has it. SUBSCRIPTION_PAUSED appears only on EXPIRATION.