| 1 |
"""This module provides Payments API functionalities.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import logging |
| 6 |
from typing import TypedDict |
| 7 |
|
| 8 |
from .api import ApiBase, CloudApiError, api_exception_handler |
| 9 |
|
| 10 |
_LOGGER = logging.getLogger(__name__) |
| 11 |
|
| 12 |
|
| 13 |
class PaymentsApiError(CloudApiError): |
| 14 |
"""Exception raised when handling payments API.""" |
| 15 |
|
| 16 |
|
| 17 |
class BillingInformation(TypedDict): |
| 18 |
"""Billing information from payments API.""" |
| 19 |
|
| 20 |
address: dict[str, str | None] |
| 21 |
name: str |
| 22 |
|
| 23 |
|
| 24 |
class Subscription(TypedDict): |
| 25 |
"""Subscription data from payments API.""" |
| 26 |
|
| 27 |
status: str | None |
| 28 |
trial_end: int | None |
| 29 |
cancel_at_period_end: bool | None |
| 30 |
canceled_at: int | None |
| 31 |
current_period_end: int | None |
| 32 |
|
| 33 |
|
| 34 |
class SubscriptionInfo(TypedDict): |
| 35 |
"""Subscription information from payments API.""" |
| 36 |
|
| 37 |
amount: float |
| 38 |
automatic_tax: bool |
| 39 |
billing_information: BillingInformation |
| 40 |
billing_plan_type: str |
| 41 |
country: str |
| 42 |
currency: str |
| 43 |
customer_exists: bool |
| 44 |
delete_requested: bool |
| 45 |
email: str |
| 46 |
human_description: str |
| 47 |
plan_renewal_date: int | None |
| 48 |
provider: str | None |
| 49 |
renewal_active: bool |
| 50 |
source: dict[str, str | int | None] | None |
| 51 |
subscription: Subscription | None |
| 52 |
tax: float |
| 53 |
|
| 54 |
|
| 55 |
class MigratePaypalAgreementInfo(TypedDict): |
| 56 |
"""Migration information from payments API.""" |
| 57 |
|
| 58 |
url: str |
| 59 |
|
| 60 |
|
| 61 |
class PaymentsApi(ApiBase): |
| 62 |
"""Class to help communicate with the payments API.""" |
| 63 |
|
| 64 |
@api_exception_handler(PaymentsApiError) |
| 65 |
async def subscription_info(self, skip_renew: bool = False) -> SubscriptionInfo: |
| 66 |
"""Get the subscription information.""" |
| 67 |
info: SubscriptionInfo = await self._call_cloud_api(action="subscription_info") |
| 68 |
|
| 69 |
# If subscription info indicates we are subscribed, force a refresh of the token |
| 70 |
if info.get("provider") and not self._cloud.started and not skip_renew: |
| 71 |
_LOGGER.debug( |
| 72 |
"Found disconnected account with valid subscription, connecting" |
| 73 |
) |
| 74 |
await self._cloud.auth.async_renew_access_token() |
| 75 |
|
| 76 |
return info |
| 77 |
|
| 78 |
@api_exception_handler(PaymentsApiError) |
| 79 |
async def migrate_paypal_agreement(self) -> MigratePaypalAgreementInfo: |
| 80 |
"""Migrate a PayPal agreement to the new system.""" |
| 81 |
response: MigratePaypalAgreementInfo = await self._call_cloud_api( |
| 82 |
action="subscription_migrate_paypal", |
| 83 |
method="POST", |
| 84 |
) |
| 85 |
return response |