Update routes/hello.py
Browse files- routes/hello.py +16 -12
routes/hello.py
CHANGED
@@ -58,7 +58,7 @@ def verify_token(user_token: str) -> str:
|
|
58 |
@router.post("/create_customer")
|
59 |
def create_customer(
|
60 |
data: CreateCustomerRequest,
|
61 |
-
user_token: str = Header(None, alias="User-key")
|
62 |
):
|
63 |
try:
|
64 |
if not user_token:
|
@@ -69,17 +69,25 @@ def create_customer(
|
|
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 |
-
|
73 |
|
|
|
74 |
if existing_customers.data:
|
75 |
error_message = f"Customer with email {data.email} already exists."
|
76 |
logger.warning(f"⚠️ {error_message}")
|
77 |
raise HTTPException(status_code=400, detail=error_message)
|
78 |
|
79 |
-
# 🔹
|
80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
81 |
|
82 |
-
if
|
83 |
error_message = f"Customer with phone {data.phone} already exists."
|
84 |
logger.warning(f"⚠️ {error_message}")
|
85 |
raise HTTPException(status_code=400, detail=error_message)
|
@@ -103,21 +111,17 @@ def create_customer(
|
|
103 |
update_data = {"stripe_id": stripe_id}
|
104 |
|
105 |
update_headers = {
|
106 |
-
"Authorization": f"Bearer {user_token}",
|
107 |
-
"apikey": SUPABASE_KEY,
|
108 |
"Content-Type": "application/json"
|
109 |
}
|
110 |
|
111 |
-
# 🔹 Corrigindo o nome da tabela (User com "U" maiúsculo)
|
112 |
supabase_url = f"{SUPABASE_URL}/rest/v1/User?id=eq.{user_id}"
|
113 |
|
114 |
response = requests.patch(supabase_url, headers=update_headers, json=update_data)
|
115 |
-
|
116 |
-
# 🔹 Logando a resposta para debug
|
117 |
logger.info(f"🔹 Supabase PATCH response: {response.status_code} - {response.text}")
|
118 |
|
119 |
if response.status_code not in [200, 204]:
|
120 |
-
# 🚨 Se a atualização falhar, deletamos o cliente do Stripe!
|
121 |
logger.warning(f"⚠️ Rolling back: Deleting Stripe customer {stripe_id} due to Supabase failure.")
|
122 |
stripe.Customer.delete(stripe_id)
|
123 |
error_message = f"Error updating Supabase: {response.text}"
|
@@ -125,7 +129,7 @@ def create_customer(
|
|
125 |
|
126 |
logger.info(f"✅ Successfully updated user {user_id} with stripe_id {stripe_id}")
|
127 |
return {"customer_id": stripe_id}
|
128 |
-
|
129 |
except HTTPException as http_err:
|
130 |
raise http_err # Já estruturamos o erro corretamente acima, então só propagamos.
|
131 |
|
|
|
58 |
@router.post("/create_customer")
|
59 |
def create_customer(
|
60 |
data: CreateCustomerRequest,
|
61 |
+
user_token: str = Header(None, alias="User-key")
|
62 |
):
|
63 |
try:
|
64 |
if not 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)
|
|
|
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.")
|
126 |
stripe.Customer.delete(stripe_id)
|
127 |
error_message = f"Error updating Supabase: {response.text}"
|
|
|
129 |
|
130 |
logger.info(f"✅ Successfully updated user {user_id} with stripe_id {stripe_id}")
|
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 |
|