Spaces:
Running on T4
Running on T4
File size: 5,314 Bytes
2756f0f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | """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)
|