"""Store purchases and their lifecycle events, recorded as subscription rows. Status rules (EntitlementService counts active/grace rows with expires_at > now as pro): - A cancelled subscription (auto-renew turned off) keeps access until it expires, so it stays 'active' and simply lapses at expires_at. 'cancelled' is therefore never written; ending access is recorded as 'expired' or 'refunded'. - Billing retry without a grace period, on hold and paused are 'expired'; refunds and revocations are 'refunded'. - An update whose expiry is older than the stored one is stale (out-of-order delivery or an old receipt) and ignored. Stable ids: iOS uses originalTransactionId. Android uses the base of the order id ('GPA.1234-...' without the '..N' renewal suffix), which stays the same across renewals of one purchase token. A new token (upgrade or resubscribe) gets a new row; when Google reports it before the app does, the linkedPurchaseToken tells us whose it is. """ import base64 import binascii import json import logging from dataclasses import dataclass, replace from datetime import UTC, datetime from uuid import UUID from sqlalchemy.ext.asyncio import AsyncSession from app.core.config import get_settings from app.core.errors import Conflict, Unauthenticated, Unprocessable, ValidationFailed from app.integrations.app_store import AppleNotification, AppleTransaction, AppStoreClient, InvalidSignedData from app.integrations.play_store import ( InvalidPurchase, InvalidPushToken, PlayStoreClient, PlaySubscription, PubSubVerifier, ) from app.modules.billing.entitlement import Entitlement, EntitlementService from app.modules.billing.models import Subscription from app.modules.billing.repository import SubscriptionRepository from app.modules.billing.schemas import ReceiptIn log = logging.getLogger(__name__) ENDED_APPLE_NOTIFICATIONS = {"EXPIRED", "GRACE_PERIOD_EXPIRED"} REFUND_APPLE_NOTIFICATIONS = {"REFUND", "REVOKE"} PLAY_SUBSCRIPTION_REVOKED = 12 @dataclass(frozen=True) class StoreState: platform: str original_transaction_id: str product_id: str status: str expires_at: datetime def apple_state(tx: AppleTransaction, now: datetime, notification: AppleNotification | None = None) -> StoreState | None: """None when the transaction is not a subscription (no expiry).""" if tx.expires_at is None: return None expires_at = max(tx.expires_at, notification.grace_period_expires_at) if ( notification and notification.grace_period_expires_at) else tx.expires_at kind = notification.type if notification else None if tx.revoked_at is not None or kind in REFUND_APPLE_NOTIFICATIONS: status = "refunded" elif kind in ENDED_APPLE_NOTIFICATIONS: status = "expired" elif kind == "DID_FAIL_TO_RENEW": status = "grace" if notification and notification.subtype == "GRACE_PERIOD" and expires_at > now else "expired" else: status = "active" if expires_at > now else "expired" return StoreState("ios", tx.original_transaction_id, tx.product_id, status, expires_at) def play_state(sub: PlaySubscription, purchase_token: str, pro_product_ids: list[str], now: datetime) -> StoreState | None: """None while the purchase is pending (not paid yet) or has no line items.""" if sub.state in ("PENDING", "PENDING_PURCHASE_CANCELED", "") or not sub.line_items: return None pro_items = [li for li in sub.line_items if li.product_id in pro_product_ids and li.expires_at] item = max(pro_items, key=lambda li: li.expires_at) if pro_items else sub.line_items[0] expires_at = item.expires_at or now if sub.state == "IN_GRACE_PERIOD": status = "grace" elif sub.state in ("ACTIVE", "CANCELED"): status = "active" if expires_at > now else "expired" else: # EXPIRED, ON_HOLD, PAUSED status = "expired" stable_id = sub.latest_order_id.split("..")[0] if sub.latest_order_id else purchase_token return StoreState("android", stable_id, item.product_id, status, expires_at) class BillingService: def __init__(self, db: AsyncSession, app_store: AppStoreClient, play_store: PlayStoreClient, pubsub: PubSubVerifier): self.db = db self.subscriptions = SubscriptionRepository(db) self.app_store = app_store self.play_store = play_store self.pubsub = pubsub async def entitlement(self, account_id: UUID) -> Entitlement: return await EntitlementService(self.db).get(account_id) async def submit_receipt(self, account_id: UUID, body: ReceiptIn) -> Entitlement: settings = get_settings() if body.product_id not in settings.pro_product_ids: raise ValidationFailed(fields={"product_id": "Unknown product."}) field = "signed_transaction" if body.platform == "ios" else "purchase_token" receipt = getattr(body, field) if not receipt: raise ValidationFailed(fields={field: "Required for this platform."}) now = datetime.now(UTC) state: StoreState | None sub: PlaySubscription | None = None try: if body.platform == "ios": state = apple_state(self.app_store.verify_signed_transaction(receipt), now) else: sub = await self.play_store.get_subscription(receipt) state = play_state(sub, receipt, settings.pro_product_ids, now) except (InvalidSignedData, InvalidPurchase) as exc: log.info("receipt rejected: %s", exc) raise _receipt_invalid() from exc if state is None or state.product_id != body.product_id: raise _receipt_invalid() if not await self.subscriptions.insert_if_absent( account_id=account_id, platform=state.platform, product_id=state.product_id, original_transaction_id=state.original_transaction_id, status=state.status, expires_at=state.expires_at): row = await self.subscriptions.lock_by_original_id(state.original_transaction_id) if row is None or row.account_id != account_id: raise Conflict("This purchase belongs to another account.", code="RECEIPT_IN_USE") await self._apply(row, state) if sub is not None and not sub.acknowledged: try: await self.play_store.acknowledge(state.product_id, receipt) except Exception: # the app can acknowledge too; a resulting refund arrives as a webhook log.warning("play acknowledge failed", exc_info=True) return await self.entitlement(account_id) async def apple_webhook(self, signed_payload: str) -> None: try: notification = self.app_store.decode_notification(signed_payload) except InvalidSignedData as exc: log.info("apple notification rejected: %s", exc) raise Unauthenticated("Invalid signature.") from exc if notification.transaction is None: return state = apple_state(notification.transaction, datetime.now(UTC), notification) if state is None: return row = await self.subscriptions.lock_by_original_id(state.original_transaction_id) if row is not None: await self._apply(row, state) async def google_webhook(self, authorization: str | None, message_data: str) -> None: settings = get_settings() token = authorization[7:].strip() if authorization and authorization.lower().startswith("bearer ") else "" try: await self.pubsub.verify(token) except InvalidPushToken as exc: log.info("pubsub push rejected: %s", exc) raise Unauthenticated("Invalid push token.") from exc try: notification = json.loads(base64.b64decode(message_data, validate=True)) except (binascii.Error, ValueError): log.warning("pubsub push with an unreadable message") return if not isinstance(notification, dict) or notification.get("packageName") != settings.google_package_name: return sub_note = notification.get("subscriptionNotification") or {} voided = notification.get("voidedPurchaseNotification") or {} purchase_token = sub_note.get("purchaseToken") or voided.get("purchaseToken") if not purchase_token: return # test notifications and one-time products try: sub = await self.play_store.get_subscription(purchase_token) except InvalidPurchase: return state = play_state(sub, purchase_token, settings.pro_product_ids, datetime.now(UTC)) if state is None: return if sub_note.get("notificationType") == PLAY_SUBSCRIPTION_REVOKED or ( voided and voided.get("orderId") in (None, sub.latest_order_id)): state = replace(state, status="refunded") row = await self.subscriptions.lock_by_original_id(state.original_transaction_id) if row is not None: await self._apply(row, state) elif sub.linked_purchase_token: await self._adopt_linked(sub.linked_purchase_token, state) async def _adopt_linked(self, linked_token: str, state: StoreState) -> None: """A new token (upgrade or resubscribe) belongs to whoever owned the token it replaces.""" try: previous = await self.play_store.get_subscription(linked_token) except InvalidPurchase: return previous_state = play_state(previous, linked_token, get_settings().pro_product_ids, datetime.now(UTC)) if previous_state is None: return owner = await self.subscriptions.first_by(original_transaction_id=previous_state.original_transaction_id) if owner is not None: await self.subscriptions.insert_if_absent( account_id=owner.account_id, platform=state.platform, product_id=state.product_id, original_transaction_id=state.original_transaction_id, status=state.status, expires_at=state.expires_at) async def _apply(self, row: Subscription, state: StoreState) -> None: if state.expires_at < row.expires_at: return await self.subscriptions.update(row, status=state.status, expires_at=state.expires_at, product_id=state.product_id) def _receipt_invalid() -> Unprocessable: return Unprocessable("We couldn't verify this purchase.", code="RECEIPT_INVALID")