client.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. from typing import AsyncGenerator, Type, TypeAlias, TypeVar
  2. import aiohttp
  3. from django.conf import settings
  4. from pydantic import BaseModel
  5. from apps.organizations_ext.models import Organization
  6. from .schema import (
  7. Customer,
  8. PortalSession,
  9. Price,
  10. PriceListResponse,
  11. ProductExpandedPrice,
  12. ProductExpandedPriceListResponse,
  13. Session,
  14. StripeListResponse,
  15. Subscription,
  16. SubscriptionExpandCustomer,
  17. SubscriptionExpandCustomerResponse,
  18. )
  19. STRIPE_URL = "https://api.stripe.com/v1"
  20. HEADERS = {
  21. "Authorization": f"Bearer {settings.STRIPE_SECRET_KEY}",
  22. "Content-Type": "application/x-www-form-urlencoded",
  23. "Stripe-Version": "2025-01-27.acacia",
  24. }
  25. AIOTupleParams: TypeAlias = list[tuple[str, str]]
  26. AIODictParams: TypeAlias = dict[str, int | str | list[int | str]]
  27. T = TypeVar("T", bound=BaseModel)
  28. def param_helper(data: AIODictParams) -> AIOTupleParams:
  29. """Accept {foo: [1,2]} format and convert aio-friendly to list of tuples"""
  30. params: AIOTupleParams = []
  31. for key, value in data.items():
  32. if isinstance(value, list):
  33. for item in value:
  34. params.append((f"{key}[]", str(item)))
  35. else:
  36. params.append((key, str(value)))
  37. return params
  38. async def stripe_get(
  39. endpoint: str,
  40. params: AIODictParams | AIOTupleParams | None = None,
  41. ) -> str:
  42. """Makes GET requests to the Stripe API."""
  43. if isinstance(params, dict):
  44. params = param_helper(params)
  45. async with aiohttp.ClientSession() as session:
  46. async with session.get(
  47. f"{STRIPE_URL}/{endpoint}", headers=HEADERS, params=params
  48. ) as response:
  49. if response.status != 200:
  50. error_data = await response.json()
  51. raise Exception(
  52. f"Stripe API Error: {response.status} - {error_data.get('error', {}).get('message', 'Unknown error')}"
  53. )
  54. return await response.text()
  55. async def stripe_post(endpoint: str, data: dict) -> str:
  56. """Makes POST requests to the Stripe API. Returns response text"""
  57. async with aiohttp.ClientSession() as session:
  58. async with session.post(
  59. f"{STRIPE_URL}/{endpoint}", headers=HEADERS, data=data
  60. ) as response:
  61. if response.status != 200:
  62. error_data = await response.json()
  63. raise Exception(
  64. f"Stripe API Error: {response.status} - {error_data.get('error', {}).get('message', 'Unknown error')}"
  65. )
  66. return await response.text()
  67. async def _paginated_stripe_get(
  68. endpoint: str,
  69. response_model: Type[StripeListResponse[T]], # Use the generic type here
  70. params: dict[str, AIODictParams] | None = None,
  71. ) -> AsyncGenerator[list[T], None]:
  72. """
  73. Generic function to handle paginated GET requests to the Stripe API.
  74. Args:
  75. endpoint: The Stripe API endpoint (e.g., "products", "subscriptions").
  76. response_model: The Pydantic model for the *entire* response (including has_more and data).
  77. params: Initial query parameters. These will be *updated* with pagination parameters.
  78. Yields:
  79. Lists of the data objects from each page.
  80. """
  81. has_more = True
  82. starting_after: str | None = None
  83. # Create a copy of the params to avoid modifying the original
  84. local_params = params.copy() if params else {}
  85. local_params["limit"] = 100 # Consistent limit
  86. while has_more:
  87. if starting_after:
  88. local_params["starting_after"] = starting_after
  89. result = await stripe_get(endpoint, params=local_params)
  90. response = response_model.model_validate_json(result)
  91. has_more = response.has_more
  92. if has_more and response.data:
  93. starting_after = response.data[-1].id
  94. yield response.data
  95. async def list_products() -> AsyncGenerator[list[ProductExpandedPrice], None]:
  96. """Yield each page of products with associated default price"""
  97. params = {"active": "true", "expand": ["data.default_price"]}
  98. async for page in _paginated_stripe_get(
  99. "products", ProductExpandedPriceListResponse, params
  100. ):
  101. yield page
  102. async def list_subscriptions() -> AsyncGenerator[
  103. list[SubscriptionExpandCustomer], None
  104. ]:
  105. """Yield each subscription with associated price and customer"""
  106. params = {"expand": ["data.items.data.price", "data.customer"]}
  107. async for page in _paginated_stripe_get(
  108. "subscriptions", SubscriptionExpandCustomerResponse, params
  109. ):
  110. yield page
  111. async def list_prices() -> AsyncGenerator[list[Price], None]:
  112. """Yield each price"""
  113. async for page in _paginated_stripe_get("prices", PriceListResponse):
  114. yield page
  115. async def create_customer(organization: Organization) -> Customer:
  116. """
  117. Create a Stripe customer for the given organization, saving the customer ID
  118. to the organization.
  119. """
  120. response = await stripe_post(
  121. "customers",
  122. {
  123. "name": organization.name,
  124. "email": organization.email,
  125. "metadata": {
  126. "organization_id": organization.id,
  127. "organization_slug": organization.slug,
  128. },
  129. },
  130. )
  131. customer = Customer.model_validate_json(response)
  132. organization.stripe_customer_id = customer.id
  133. await organization.asave(update_fields=["stripe_customer_id"])
  134. return customer
  135. async def create_session(
  136. price_id: str, customer_id: str, organization_slug: str
  137. ) -> Session:
  138. domain = settings.GLITCHTIP_URL.geturl()
  139. params = {
  140. "payment_method_types": ["card"],
  141. "line_items": [
  142. {
  143. "price": price_id,
  144. "quantity": 1,
  145. }
  146. ],
  147. "mode": "subscription",
  148. "customer": customer_id,
  149. "automatic_tax": {
  150. "enabled": True,
  151. },
  152. "customer_update": {"address": "auto", "name": "auto"},
  153. "tax_id_collection": {
  154. "enabled": True,
  155. },
  156. "success_url": domain
  157. + "/"
  158. + organization_slug
  159. + "/settings/subscription?session_id={CHECKOUT_SESSION_ID}",
  160. "cancel_url": domain + "",
  161. }
  162. response = await stripe_post("/checkout/sessions", params)
  163. return Session.model_validate_json(response)
  164. async def create_portal_session(customer_id: str, organization_slug: str):
  165. domain = settings.GLITCHTIP_URL.geturl()
  166. params = {
  167. "customer": customer_id,
  168. "return_url": domain
  169. + "/"
  170. + organization_slug
  171. + "/settings/subscription?billing_portal_redirect=true",
  172. }
  173. response = await stripe_post("/billing_portal/sessions", params)
  174. return PortalSession.model_validate_json(response)
  175. async def create_subscription(customer: str, price: str) -> Subscription:
  176. params = {"customer": customer, "items": [{"price": price}]}
  177. response = await stripe_post("/subscriptions", params)
  178. return Subscription.model_validate_json(response)