File size: 10,622 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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
"""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")