File size: 2,198 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
"""G1 entitlement, G2 receipt validation, G3 store webhooks."""

from typing import Annotated

from fastapi import APIRouter, Depends, Header

from app.core.dependencies import CurrentAccount, Db
from app.core.errors import NotFound
from app.integrations.app_store import AppStoreClient, get_app_store
from app.integrations.play_store import PlayStoreClient, PubSubVerifier, get_play_store, get_pubsub_verifier
from app.modules.billing.entitlement import Entitlement
from app.modules.billing.schemas import AppleWebhookIn, PubSubPushIn, ReceiptIn, ReceiptOut, WebhookAck
from app.modules.billing.service import BillingService

router = APIRouter(prefix="/v1", tags=["billing"])


def get_billing_service(
    db: Db,
    app_store: Annotated[AppStoreClient, Depends(get_app_store)],
    play_store: Annotated[PlayStoreClient, Depends(get_play_store)],
    pubsub: Annotated[PubSubVerifier, Depends(get_pubsub_verifier)],
) -> BillingService:
    return BillingService(db, app_store, play_store, pubsub)


Billing = Annotated[BillingService, Depends(get_billing_service)]


@router.get("/me/entitlement", response_model=Entitlement)
async def get_entitlement(account: CurrentAccount, service: Billing) -> Entitlement:
    return await service.entitlement(account.id)


@router.post("/billing/receipts", response_model=ReceiptOut)
async def submit_receipt(body: ReceiptIn, account: CurrentAccount, service: Billing) -> ReceiptOut:
    return ReceiptOut(entitlement=await service.submit_receipt(account.id, body))


@router.post("/billing/webhooks/apple", response_model=WebhookAck)
async def apple_webhook(body: AppleWebhookIn, service: Billing) -> WebhookAck:
    await service.apple_webhook(body.signed_payload)
    return WebhookAck()


@router.post("/billing/webhooks/google", response_model=WebhookAck)
async def google_webhook(body: PubSubPushIn, service: Billing,
                         authorization: Annotated[str | None, Header()] = None) -> WebhookAck:
    await service.google_webhook(authorization, body.message.data)
    return WebhookAck()


@router.post("/billing/webhooks/{provider}", include_in_schema=False)
async def unknown_webhook(provider: str) -> None:
    raise NotFound()