tempest_fastapi_sdk.integrations.subscriptions.revenuecat¶
RevenueCat: assinaturas in-app da App Store e do Google Play.
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: |
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 |
RevenueCatCustomerInfo
|
just created — see the module warning) parses the same way. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
HTTPStatusError
|
For any non-2xx answer ( |
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 ( |
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
|
transport
|
AsyncBaseTransport | None
|
Transport override —
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
HTTPClient |
HTTPClient
|
A client with |
HTTPClient
|
accept headers set. |
REVENUECAT_API_BASE_URL
module-attribute
¶
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 |
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 |
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 |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
Ready for |
Raises:
| Type | Description |
|---|---|
ValueError
|
When both |
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 |
required |
signing_secret
|
SecretSource | None
|
The HMAC signing secret, when
signing is enabled on the integration. |
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 |
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 |
body |
bytes
|
The raw body, byte for byte. |
RevenueCatWebhookAck
¶
Bases: BaseModel
What the router answers RevenueCat.
Attributes:
| Name | Type | Description |
|---|---|---|
recorded |
bool
|
|
event_id |
str
|
RevenueCat's event id. |
SecretSource
module-attribute
¶
A secret, or a function reading it per request (rotation, multi-tenant).
verify_authorization
¶
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
|
|
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 |
required |
secret
|
str
|
The integration's signing secret. |
required |
tolerance_seconds
|
int
|
Maximum |
DEFAULT_SIGNATURE_TOLERANCE_SECONDS
|
now
|
float | None
|
Current epoch seconds; injectable for tests. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
window and a |
sign_payload
¶
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 |
parse_signature_header
¶
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, ...]]: |
tuple[str, ...]
|
when absent or not a number) and every |
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
|
REVENUECAT_PROVIDER
module-attribute
¶
provider value the router records events under in the inbox.
REVENUECAT_AUTHORIZATION_HEADER
module-attribute
¶
Header carrying the value configured in the RevenueCat dashboard.
REVENUECAT_SIGNATURE_HEADER
module-attribute
¶
Header carrying t=<timestamp>,v1=<hex> when HMAC signing is on.
DEFAULT_SIGNATURE_TOLERANCE_SECONDS
module-attribute
¶
Accepted distance between t and now: the documentation's 5 minutes.
normalize
¶
normalize(event: RevenueCatEvent) -> SubscriptionSnapshot
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
|
entitlement_ids |
tuple[str, ...]
|
Entitlements of the product. |
period_type |
str | None
|
|
store |
str | None
|
Store of the purchase. |
environment |
str | None
|
|
purchased_at |
datetime | None
|
Start of the period, UTC. |
period_end |
datetime | None
|
End of the period, UTC; |
grace_period_end |
datetime | None
|
End of the grace period, UTC. |
reason |
str | None
|
|
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 untilperiod_end.BILLING_ISSUE— a charge failed; not expired.grace_period_endsays 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 ( |
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 |
type |
str
|
The event type, as delivered. Compare with
:class: |
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
|
product_id |
str | None
|
Product of the subscription. |
new_product_id |
str | None
|
Product switched to, on some
|
entitlement_ids |
list[str]
|
Entitlements of the product. |
period_type |
str | None
|
|
purchased_at_ms |
int | None
|
Purchase time, epoch milliseconds. |
expiration_at_ms |
int | None
|
End of the period; |
grace_period_expiration_at_ms |
int | None
|
Only on
|
auto_resume_at_ms |
int | None
|
Only on |
environment |
str | None
|
|
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 |
expiration_reason |
str | None
|
Only on |
is_trial_conversion |
bool | None
|
Only on |
experiments |
list[RevenueCatExperiment]
|
Experiments the subscriber was enrolled in. |
subscriber_attributes |
dict[str, Any]
|
Customer attributes. Excluded
from |
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; |
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 |
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
|
|
store |
str | None
|
|
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
|
|
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; |
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
¶
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
¶
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.