habulaj commited on
Commit
0377ccd
·
verified ·
1 Parent(s): 453d7ba

Update routes/subscription.py

Browse files
Files changed (1) hide show
  1. routes/subscription.py +15 -72
routes/subscription.py CHANGED
@@ -1,73 +1,3 @@
1
- import stripe
2
- import logging
3
- import json
4
- from datetime import datetime
5
- import pytz
6
- import os
7
- import requests
8
- import asyncio
9
- import jwt
10
- from fastapi import APIRouter, HTTPException, Request, Header
11
- from pydantic import BaseModel
12
-
13
- router = APIRouter()
14
-
15
- logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
16
- logger = logging.getLogger(__name__)
17
-
18
- # 🔥 Pegando as chaves do ambiente
19
- stripe.api_key = os.getenv("STRIPE_KEY") # Lendo do ambiente
20
- stripe.api_version = "2023-10-16"
21
-
22
- # 🔥 Supabase Configuração com Secrets
23
- SUPABASE_URL = "https://ussxqnifefkgkaumjann.supabase.co"
24
- SUPABASE_KEY = os.getenv("SUPA_KEY") # Lendo do ambiente
25
-
26
- if not stripe.api_key or not SUPABASE_KEY:
27
- raise ValueError("❌ STRIPE_KEY ou SUPA_KEY não foram definidos no ambiente!")
28
-
29
- SUPABASE_HEADERS = {
30
- "apikey": SUPABASE_KEY,
31
- "Authorization": f"Bearer {SUPABASE_KEY}",
32
- "Content-Type": "application/json"
33
- }
34
-
35
- class UserIDRequest(BaseModel):
36
- user_id: str
37
-
38
- class CheckSubscriptionRequest(BaseModel):
39
- stylist_id: str
40
- user_id: str # Agora recebemos diretamente o user_id
41
-
42
- class SubscriptionRequest(BaseModel):
43
- id: str # ID do estilista
44
-
45
- class CreatePriceRequest(BaseModel):
46
- amount: int # Valor em centavos (ex: 2500 para R$25,00)
47
- emergency_price: int # Valor de emergência (ex: 500 para R$5,00)
48
- consultations: int # Número de consultas (ex: 3)
49
-
50
- def verify_token(user_token: str) -> str:
51
- """
52
- Valida o token JWT no Supabase e retorna o user_id se for válido.
53
- """
54
- headers = {
55
- "Authorization": f"Bearer {user_token}",
56
- "apikey": SUPABASE_KEY,
57
- "Content-Type": "application/json"
58
- }
59
-
60
- response = requests.get(f"{SUPABASE_URL}/auth/v1/user", headers=headers)
61
-
62
- if response.status_code == 200:
63
- user_data = response.json()
64
- user_id = user_data.get("id")
65
- if not user_id:
66
- raise HTTPException(status_code=400, detail="Invalid token: User ID not found")
67
- return user_id
68
- else:
69
- raise HTTPException(status_code=401, detail="Invalid or expired token")
70
-
71
  @router.post("/subscription_details")
72
  async def subscription_details(data: SubscriptionRequest):
73
  try:
@@ -120,7 +50,19 @@ async def subscription_details(data: SubscriptionRequest):
120
  payment_info = "No default payment method found"
121
 
122
  # Pegando o stylist_id dos metadados
123
- stylist_id = subscription["metadata"].get("stylist_id", "N/A")
 
 
 
 
 
 
 
 
 
 
 
 
124
 
125
  return {
126
  "status": subscription_status,
@@ -129,7 +71,8 @@ async def subscription_details(data: SubscriptionRequest):
129
  "next_invoice_amount": f"{next_invoice_amount} {currency}" if next_invoice_amount else "N/A",
130
  "next_billing_date": next_billing_date,
131
  "payment_method": payment_info,
132
- "stylist_id": stylist_id
 
133
  }
134
 
135
  except stripe.error.StripeError as e:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  @router.post("/subscription_details")
2
  async def subscription_details(data: SubscriptionRequest):
3
  try:
 
50
  payment_info = "No default payment method found"
51
 
52
  # Pegando o stylist_id dos metadados
53
+ stylist_id = subscription["metadata"].get("stylist_id", None)
54
+
55
+ # Buscar avatar do stylist no Supabase
56
+ stylist_avatar = None
57
+ if stylist_id:
58
+ response = requests.get(
59
+ f"{SUPABASE_URL}/rest/v1/User?id=eq.{stylist_id}&select=avatar",
60
+ headers=SUPABASE_HEADERS
61
+ )
62
+ if response.status_code == 200:
63
+ data = response.json()
64
+ if data and "avatar" in data[0]:
65
+ stylist_avatar = data[0]["avatar"]
66
 
67
  return {
68
  "status": subscription_status,
 
71
  "next_invoice_amount": f"{next_invoice_amount} {currency}" if next_invoice_amount else "N/A",
72
  "next_billing_date": next_billing_date,
73
  "payment_method": payment_info,
74
+ "stylist_id": stylist_id,
75
+ "stylist_avatar": stylist_avatar # Retorna a URL da imagem ou None
76
  }
77
 
78
  except stripe.error.StripeError as e: