habulaj commited on
Commit
f4b70f0
·
verified ·
1 Parent(s): 5f6ca89

Update routes/hello.py

Browse files
Files changed (1) hide show
  1. routes/hello.py +71 -38
routes/hello.py CHANGED
@@ -29,6 +29,59 @@ class AccountRequest(BaseModel):
29
  email: str
30
  name: str # Name of the individual account owner
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  class CreateCustomerRequest(BaseModel):
33
  email: str
34
  phone: str
@@ -68,58 +121,38 @@ def create_customer(
68
  user_id = verify_token(user_token)
69
  logger.info(f"🔹 User verified. user_id: {user_id}")
70
 
 
 
 
 
 
 
 
 
 
 
 
71
  # 🔹 Verificar se já existe um cliente com o mesmo e-mail no Stripe
72
  logger.info(f"🔹 Checking if email {data.email} already exists in Stripe...")
73
-
74
  existing_customers = stripe.Customer.list(email=data.email, limit=1)
75
  if existing_customers.data:
76
  error_message = f"Customer with email {data.email} already exists."
77
  logger.warning(f"⚠️ {error_message}")
78
  raise HTTPException(status_code=400, detail=error_message)
79
 
80
- # 🔹 Logar telefone antes da requisição
81
- logger.info(f"🔹 Checking if phone {data.phone} already exists in Stripe...")
82
-
83
- # 🔹 Buscar todos os clientes e filtrar manualmente pelo telefone (porque o Stripe não suporta busca direta)
84
- all_customers = stripe.Customer.list(limit=100) # Pegamos até 100 clientes para otimizar
85
- existing_customer_by_phone = next(
86
- (customer for customer in all_customers.auto_paging_iter() if customer.phone == data.phone),
87
- None
88
- )
89
-
90
- if existing_customer_by_phone:
91
- error_message = f"Customer with phone {data.phone} already exists."
92
- logger.warning(f"⚠️ {error_message}")
93
- raise HTTPException(status_code=400, detail=error_message)
94
-
95
  # 🔹 Criar o cliente no Stripe
96
- try:
97
- customer = stripe.Customer.create(
98
- email=data.email,
99
- phone=data.phone,
100
- name=data.name
101
- )
102
- except stripe.error.StripeError as e:
103
- error_message = str(e) if str(e) else "An unknown error occurred. Please try again."
104
- logger.error(f"❌ Stripe error: {error_message}")
105
- raise HTTPException(status_code=500, detail=error_message)
106
-
107
  stripe_id = customer.id
108
  logger.info(f"✅ New Stripe customer created: {stripe_id}")
109
 
110
  # 🔹 Atualizar o usuário no Supabase com o stripe_id
111
  update_data = {"stripe_id": stripe_id}
112
-
113
- update_headers = {
114
- "Authorization": f"Bearer {user_token}",
115
- "apikey": SUPABASE_KEY,
116
- "Content-Type": "application/json"
117
- }
118
-
119
  supabase_url = f"{SUPABASE_URL}/rest/v1/User?id=eq.{user_id}"
120
-
121
- response = requests.patch(supabase_url, headers=update_headers, json=update_data)
122
- logger.info(f"🔹 Supabase PATCH response: {response.status_code} - {response.text}")
123
 
124
  if response.status_code not in [200, 204]:
125
  logger.warning(f"⚠️ Rolling back: Deleting Stripe customer {stripe_id} due to Supabase failure.")
@@ -131,7 +164,7 @@ def create_customer(
131
  return {"customer_id": stripe_id}
132
 
133
  except HTTPException as http_err:
134
- raise http_err # Já estruturamos o erro corretamente acima, então só propagamos.
135
 
136
  except Exception as e:
137
  error_message = str(e) if str(e) else "An unknown error occurred. Please try again."
 
29
  email: str
30
  name: str # Name of the individual account owner
31
 
32
+ class CreateCustomerRequest(BaseModel):
33
+ email: str
34
+ phone: str
35
+ name: str
36
+
37
+ def verify_token(user_token: str) -> str:
38
+ """
39
+ Valida o token JWT no Supabase e retorna o user_id se for válido.
40
+ """
41
+ headers = {
42
+ "Authorization": f"Bearer {user_token}",
43
+ "apikey": SUPABASE_KEY,
44
+ "Content-Type": "application/json"
45
+ }
46
+
47
+ response = requests.get(f"{SUPABASE_URL}/auth/v1/user", headers=headers)
48
+
49
+ if response.status_code == 200:
50
+ user_data = response.json()
51
+ user_id = user_data.get("id")
52
+ if not user_id:
53
+ raise HTTPException(status_code=400, detail="Invalid token: User ID not found")
54
+ return user_id
55
+ else:
56
+ raise HTTPException(status_code=401, detail="Invalid or expired token")
57
+
58
+ import os
59
+ import stripe
60
+ import requests
61
+ import logging
62
+ from fastapi import APIRouter, HTTPException, Header
63
+ from pydantic import BaseModel
64
+
65
+ router = APIRouter()
66
+
67
+ # Configuração das chaves do Stripe e Supabase
68
+ stripe.api_key = os.getenv("STRIPE_KEY")
69
+ stripe.api_version = "2023-10-16"
70
+ SUPABASE_URL = "https://ussxqnifefkgkaumjann.supabase.co"
71
+ SUPABASE_KEY = os.getenv("SUPA_KEY")
72
+
73
+ if not stripe.api_key or not SUPABASE_KEY:
74
+ raise ValueError("❌ STRIPE_KEY ou SUPA_KEY não foram definidos no ambiente!")
75
+
76
+ SUPABASE_HEADERS = {
77
+ "apikey": SUPABASE_KEY,
78
+ "Authorization": f"Bearer {SUPABASE_KEY}",
79
+ "Content-Type": "application/json"
80
+ }
81
+
82
+ logging.basicConfig(level=logging.INFO)
83
+ logger = logging.getLogger(__name__)
84
+
85
  class CreateCustomerRequest(BaseModel):
86
  email: str
87
  phone: str
 
121
  user_id = verify_token(user_token)
122
  logger.info(f"🔹 User verified. user_id: {user_id}")
123
 
124
+ # 🔹 Verificar se o usuário já tem um stripe_id no Supabase
125
+ user_data_url = f"{SUPABASE_URL}/rest/v1/User?id=eq.{user_id}"
126
+ response = requests.get(user_data_url, headers=SUPABASE_HEADERS)
127
+
128
+ if response.status_code == 200 and response.json():
129
+ user_data = response.json()[0]
130
+ stripe_id = user_data.get("stripe_id")
131
+ if stripe_id:
132
+ logger.info(f"✅ User already has a Stripe customer: {stripe_id}")
133
+ return {"customer_id": stripe_id}
134
+
135
  # 🔹 Verificar se já existe um cliente com o mesmo e-mail no Stripe
136
  logger.info(f"🔹 Checking if email {data.email} already exists in Stripe...")
 
137
  existing_customers = stripe.Customer.list(email=data.email, limit=1)
138
  if existing_customers.data:
139
  error_message = f"Customer with email {data.email} already exists."
140
  logger.warning(f"⚠️ {error_message}")
141
  raise HTTPException(status_code=400, detail=error_message)
142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  # 🔹 Criar o cliente no Stripe
144
+ customer = stripe.Customer.create(
145
+ email=data.email,
146
+ phone=data.phone,
147
+ name=data.name
148
+ )
 
 
 
 
 
 
149
  stripe_id = customer.id
150
  logger.info(f"✅ New Stripe customer created: {stripe_id}")
151
 
152
  # 🔹 Atualizar o usuário no Supabase com o stripe_id
153
  update_data = {"stripe_id": stripe_id}
 
 
 
 
 
 
 
154
  supabase_url = f"{SUPABASE_URL}/rest/v1/User?id=eq.{user_id}"
155
+ response = requests.patch(supabase_url, headers=SUPABASE_HEADERS, json=update_data)
 
 
156
 
157
  if response.status_code not in [200, 204]:
158
  logger.warning(f"⚠️ Rolling back: Deleting Stripe customer {stripe_id} due to Supabase failure.")
 
164
  return {"customer_id": stripe_id}
165
 
166
  except HTTPException as http_err:
167
+ raise http_err
168
 
169
  except Exception as e:
170
  error_message = str(e) if str(e) else "An unknown error occurred. Please try again."