"""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 The UK app (com.consulawtechnologies.narratifai) lives in Consulaw Technologies Ltd's own Play developer account, so it needs a sign-in by a user of THAT account: GOOGLE_PLAY_UK_REFRESH_TOKEN, with GOOGLE_PLAY_UK_CLIENT_ID / GOOGLE_PLAY_UK_CLIENT_SECRET (falling back to the Nigerian OAuth client). """ import os import time import threading from urllib.parse import quote import requests PACKAGE_NAME = "com.consulaw.narratifai" UK_PACKAGE_NAME = "com.consulawtechnologies.narratifai" _ENV_PREFIX = {PACKAGE_NAME: "GOOGLE_PLAY_", UK_PACKAGE_NAME: "GOOGLE_PLAY_UK_"} _tokens: dict = {} _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 _creds(package: str) -> tuple: prefix = _ENV_PREFIX.get(package) if not prefix: return ("", "", "") get = lambda k: os.getenv(prefix + k) or (os.getenv("GOOGLE_PLAY_" + k) if k != "REFRESH_TOKEN" else "") return (get("CLIENT_ID") or "", get("CLIENT_SECRET") or "", os.getenv(prefix + "REFRESH_TOKEN") or "") def configured(package: str = PACKAGE_NAME) -> bool: return all(_creds(package)) def _access_token(package: str) -> str: with _lock: tok = _tokens.get(package) if tok and time.time() < tok["expires"] - 60: return tok["value"] if not configured(package): raise GooglePlayError(f"Google Play access is not configured for {package}", retryable=True) client_id, client_secret, refresh = _creds(package) try: r = requests.post("https://oauth2.googleapis.com/token", data={ "client_id": client_id, "client_secret": client_secret, "refresh_token": refresh, "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) _tokens[package] = {"value": data["access_token"], "expires": time.time() + int(data.get("expires_in", 3600))} return data["access_token"] def _call(method: str, path: str, package: str = PACKAGE_NAME, **kw) -> requests.Response: if package not in _ENV_PREFIX: raise GooglePlayError(f"Unknown app {package}") url = f"https://androidpublisher.googleapis.com/androidpublisher/v3/applications/{package}{path}" try: return requests.request(method, url, headers={"Authorization": f"Bearer {_access_token(package)}"}, timeout=20, **kw) except GooglePlayError: raise except Exception: raise GooglePlayError("Google Play unreachable", retryable=True) def get_purchase(product_id: str, purchase_token: str, package: str = PACKAGE_NAME) -> 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='')}", package) 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, package: str = PACKAGE_NAME) -> 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", package) return r.status_code in (200, 204) except GooglePlayError: return False def voided_purchases(since_ms: int, package: str = PACKAGE_NAME) -> 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", package, 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