"""Google Play Billing checks for Android credit packs. The app sends the purchase token it got from Google Play; we ask the Google Play Developer API what that token really is (product, state, buyer account token, test or real) before adding credits, then consume it so the same pack can be bought again. Access uses an OAuth refresh token for a Play Console user with "View financial data" and "Manage orders" permissions (service-account keys are blocked by the organisation policy). Set by scripts/setup_ops_and_play.sh in the NarratifAI folder: GOOGLE_PLAY_CLIENT_ID, GOOGLE_PLAY_CLIENT_SECRET, GOOGLE_PLAY_REFRESH_TOKEN """ import os import time import threading from urllib.parse import quote import requests PACKAGE_NAME = "com.consulaw.narratifai" _API = f"https://androidpublisher.googleapis.com/androidpublisher/v3/applications/{PACKAGE_NAME}" _token = {"value": "", "expires": 0.0} _lock = threading.Lock() class GooglePlayError(Exception): """The purchase could not be checked (bad token, not ours, or Google unreachable).""" def __init__(self, message: str, retryable: bool = False): super().__init__(message) self.retryable = retryable def configured() -> bool: return all(os.getenv(k) for k in ("GOOGLE_PLAY_CLIENT_ID", "GOOGLE_PLAY_CLIENT_SECRET", "GOOGLE_PLAY_REFRESH_TOKEN")) def _access_token() -> str: with _lock: if _token["value"] and time.time() < _token["expires"] - 60: return _token["value"] if not configured(): raise GooglePlayError("Google Play access is not configured", retryable=True) try: r = requests.post("https://oauth2.googleapis.com/token", data={ "client_id": os.environ["GOOGLE_PLAY_CLIENT_ID"], "client_secret": os.environ["GOOGLE_PLAY_CLIENT_SECRET"], "refresh_token": os.environ["GOOGLE_PLAY_REFRESH_TOKEN"], "grant_type": "refresh_token", }, timeout=20) data = r.json() except Exception: raise GooglePlayError("Google sign-in unreachable", retryable=True) if r.status_code != 200 or not data.get("access_token"): raise GooglePlayError(f"Google sign-in refused ({r.status_code})", retryable=True) _token.update(value=data["access_token"], expires=time.time() + int(data.get("expires_in", 3600))) return _token["value"] def _call(method: str, path: str, **kw) -> requests.Response: try: return requests.request(method, _API + path, headers={"Authorization": f"Bearer {_access_token()}"}, timeout=20, **kw) except GooglePlayError: raise except Exception: raise GooglePlayError("Google Play unreachable", retryable=True) def get_purchase(product_id: str, purchase_token: str) -> dict: """purchases.products.get: the purchase as Google recorded it.""" r = _call("GET", f"/purchases/products/{quote(product_id, safe='')}/tokens/{quote(purchase_token, safe='')}") if r.status_code in (400, 404, 410): raise GooglePlayError("Google Play does not recognise this purchase") if r.status_code != 200: raise GooglePlayError(f"Google Play answered {r.status_code}", retryable=True) return r.json() def consume(product_id: str, purchase_token: str) -> bool: """Mark a delivered pack as used so it can be bought again. Consuming also acknowledges it, so Google won't auto-refund it after 3 days.""" try: r = _call("POST", f"/purchases/products/{quote(product_id, safe='')}/tokens/{quote(purchase_token, safe='')}:consume") return r.status_code in (200, 204) except GooglePlayError: return False def voided_purchases(since_ms: int) -> list: """One-time purchases refunded, charged back or revoked since `since_ms`.""" out, page = [], None while True: params = {"startTime": str(since_ms), "type": "0", "maxResults": "1000"} if page: params["token"] = page r = _call("GET", "/purchases/voidedpurchases", params=params) if r.status_code != 200: raise GooglePlayError(f"Google Play answered {r.status_code}", retryable=True) data = r.json() out += data.get("voidedPurchases", []) page = (data.get("tokenPagination") or {}).get("nextPageToken") if not page: return out