github-actions[bot]
Automated Deploy: 0d5b759d8eca219a25b3ab717925e73a66bbf4a4
2756f0f
Raw History Blame Contribute Delete
5.31 kB
"""Google Play: subscription lookups (Play Developer API, purchases.subscriptionsv2) and Pub/Sub push auth.
The Play API is called with a service-account access token (scope androidpublisher). Real-time developer
notifications arrive as Pub/Sub pushes whose Authorization header carries a Google-signed OIDC token.
"""
import asyncio
from dataclasses import dataclass
from datetime import datetime
from functools import lru_cache
from typing import Any
from urllib.parse import quote
import httpx
from google.auth.exceptions import GoogleAuthError
from google.auth.transport.requests import Request as GoogleRequest
from google.oauth2 import id_token, service_account
from app.core.config import get_settings
API = "https://androidpublisher.googleapis.com/androidpublisher/v3/applications"
SCOPE = "https://www.googleapis.com/auth/androidpublisher"
class InvalidPurchase(Exception):
"""Google does not know this purchase token for our package."""
class InvalidPushToken(Exception):
"""The Pub/Sub push was not signed by Google for our audience."""
@dataclass(frozen=True)
class PlayLineItem:
product_id: str
expires_at: datetime | None
@dataclass(frozen=True)
class PlaySubscription:
state: str # SUBSCRIPTION_STATE_* without the prefix, e.g. ACTIVE, IN_GRACE_PERIOD, CANCELED
line_items: tuple[PlayLineItem, ...]
latest_order_id: str | None
linked_purchase_token: str | None
acknowledged: bool
def _time(value: Any) -> datetime | None:
if not value:
return None
try:
return datetime.fromisoformat(str(value).replace("Z", "+00:00"))
except ValueError:
return None
def parse_subscription(data: dict[str, Any]) -> PlaySubscription:
items = tuple(PlayLineItem(product_id=str(li.get("productId", "")), expires_at=_time(li.get("expiryTime")))
for li in data.get("lineItems") or [])
order_id = data.get("latestOrderId") or next(
(li.get("latestSuccessfulOrderId") for li in data.get("lineItems") or [] if li.get("latestSuccessfulOrderId")),
None)
return PlaySubscription(
state=str(data.get("subscriptionState", "")).removeprefix("SUBSCRIPTION_STATE_"),
line_items=items,
latest_order_id=order_id,
linked_purchase_token=data.get("linkedPurchaseToken"),
acknowledged=data.get("acknowledgementState") == "ACKNOWLEDGEMENT_STATE_ACKNOWLEDGED",
)
class PlayStoreClient:
def __init__(self, *, package_name: str, service_account_file: str):
self.package_name = package_name
self.service_account_file = service_account_file
self._credentials: service_account.Credentials | None = None
async def _access_token(self) -> str:
if self._credentials is None:
self._credentials = service_account.Credentials.from_service_account_file(
self.service_account_file, scopes=[SCOPE])
if not self._credentials.valid:
await asyncio.to_thread(self._credentials.refresh, GoogleRequest())
return self._credentials.token
async def _request(self, method: str, url: str) -> httpx.Response:
headers = {"Authorization": f"Bearer {await self._access_token()}"}
async with httpx.AsyncClient(timeout=15) as client:
return await client.request(method, url, headers=headers)
async def get_subscription(self, purchase_token: str) -> PlaySubscription:
if not self.package_name:
raise InvalidPurchase("no package configured")
url = (f"{API}/{quote(self.package_name, safe='')}/purchases/subscriptionsv2"
f"/tokens/{quote(purchase_token, safe='')}")
response = await self._request("GET", url)
if response.status_code in (400, 404, 410):
raise InvalidPurchase(f"play api {response.status_code}")
response.raise_for_status()
return parse_subscription(response.json())
async def acknowledge(self, product_id: str, purchase_token: str) -> None:
"""Unacknowledged purchases are refunded by Google after three days."""
url = (f"{API}/{quote(self.package_name, safe='')}/purchases/subscriptions/{quote(product_id, safe='')}"
f"/tokens/{quote(purchase_token, safe='')}:acknowledge")
response = await self._request("POST", url)
response.raise_for_status()
class PubSubVerifier:
def __init__(self, *, audience: str):
self.audience = audience
async def verify(self, token: str) -> None:
if not self.audience or not token:
raise InvalidPushToken("not configured")
try:
claims = await asyncio.to_thread(id_token.verify_oauth2_token, token, GoogleRequest(), self.audience)
except (ValueError, GoogleAuthError) as exc:
raise InvalidPushToken(str(exc)) from exc
if not claims.get("email_verified", False):
raise InvalidPushToken("unverified email")
@lru_cache
def get_play_store() -> PlayStoreClient:
settings = get_settings()
return PlayStoreClient(package_name=settings.google_package_name,
service_account_file=settings.google_service_account_file)
@lru_cache
def get_pubsub_verifier() -> PubSubVerifier:
return PubSubVerifier(audience=get_settings().google_pubsub_audience)