Moibe commited on
Commit
f2528b2
1 Parent(s): 25f6e7d

Endpoint creaCliente listo!

Browse files
Files changed (2) hide show
  1. app.py +12 -9
  2. funciones.py +64 -19
app.py CHANGED
@@ -4,6 +4,8 @@ from fastapi.responses import JSONResponse
4
  from typing import Optional
5
  from fastapi.middleware.cors import CORSMiddleware
6
 
 
 
7
  app = FastAPI()
8
 
9
  # Configuraci贸n de CORS
@@ -43,21 +45,20 @@ async def creaCliente(
43
  site: Optional[str] = Form(None),
44
  ):
45
  """
46
- Busca un cliente existente en Stripe por email.
47
- Si no existe, lo crea con el email, Firebase User ID y site.
48
 
49
  Args:
50
  email (str): El correo electr贸nico del cliente.
51
- firebase_user (str, opcional): El ID de usuario de Firebase asociado.
52
  site (str, opcional): El nombre del sitio de origen.
53
 
54
  Returns:
55
  dict: Un diccionario con el ID del cliente de Stripe (existente o nuevo)
56
- si la operaci贸n fue exitosa, indicando si fue encontrado o creado.
57
  O un error si la operaci贸n fall贸.
58
  """
59
  try:
60
- # Llama a la funci贸n 'create_stripe_customer' y desempaca la tupla
61
  customer_result = funciones.create_stripe_customer(
62
  email=email,
63
  firebase_user=firebase_user,
@@ -68,16 +69,18 @@ async def creaCliente(
68
  customer, status = customer_result # Desempaca el objeto customer y el estado
69
 
70
  message_text = ""
71
- if status == "found":
72
- message_text = "Cliente existente encontrado exitosamente."
 
 
73
  elif status == "created":
74
  message_text = "Nuevo cliente creado exitosamente."
75
  else:
76
- message_text = "Operaci贸n de cliente exitosa." # Fallback por si acaso
77
 
78
  response_data = {
79
  "message": message_text,
80
- "status": status, # Agregamos el estado expl铆citamente tambi茅n
81
  "customer_id": customer.id,
82
  "customer_email": customer.email
83
  }
 
4
  from typing import Optional
5
  from fastapi.middleware.cors import CORSMiddleware
6
 
7
+ #FUTURE: Quiz谩 en el futuro cambiarla de Form a Json con Pydantic.
8
+
9
  app = FastAPI()
10
 
11
  # Configuraci贸n de CORS
 
45
  site: Optional[str] = Form(None),
46
  ):
47
  """
48
+ Busca un cliente existente en Stripe, priorizando el Firebase User ID.
49
+ Si no existe, lo busca por email. Si tampoco existe, lo crea.
50
 
51
  Args:
52
  email (str): El correo electr贸nico del cliente.
53
+ firebase_user (str, opcional): El ID de usuario de Firebase asociado. **Identificador principal.**
54
  site (str, opcional): El nombre del sitio de origen.
55
 
56
  Returns:
57
  dict: Un diccionario con el ID del cliente de Stripe (existente o nuevo)
58
+ si la operaci贸n fue exitosa, indicando c贸mo fue encontrado o si fue creado.
59
  O un error si la operaci贸n fall贸.
60
  """
61
  try:
 
62
  customer_result = funciones.create_stripe_customer(
63
  email=email,
64
  firebase_user=firebase_user,
 
69
  customer, status = customer_result # Desempaca el objeto customer y el estado
70
 
71
  message_text = ""
72
+ if status == "found_by_firebase_user":
73
+ message_text = "Cliente existente encontrado exitosamente por Firebase User ID."
74
+ elif status == "found_by_email":
75
+ message_text = "Cliente existente encontrado exitosamente por email."
76
  elif status == "created":
77
  message_text = "Nuevo cliente creado exitosamente."
78
  else:
79
+ message_text = "Operaci贸n de cliente exitosa." # Fallback
80
 
81
  response_data = {
82
  "message": message_text,
83
+ "status": status, # Agregamos el estado espec铆fico tambi茅n
84
  "customer_id": customer.id,
85
  "customer_email": customer.email
86
  }
funciones.py CHANGED
@@ -28,12 +28,16 @@ def create_checkout_session(price_id, customer_email=None, customer_id=None):
28
  'client_reference_id': 'HERC'
29
  }
30
 
 
 
31
  # Opciones para el cliente
32
- if customer_id:
33
- session_params['customer'] = customer_id
34
  elif customer_email:
35
  session_params['customer_email'] = customer_email
 
36
  else:
 
37
  # Si no se provee ni customer_id ni customer_email, Stripe puede crear uno si es necesario
38
  # O podr铆as pedir el email en el formulario de Checkout.
39
  pass
@@ -62,49 +66,90 @@ def create_checkout_session(price_id, customer_email=None, customer_id=None):
62
 
63
  def create_stripe_customer(email, firebase_user=None, site=None):
64
  """
65
- Busca un cliente existente en Stripe por su email.
66
- Si el cliente no existe, lo crea con los datos proporcionados.
 
67
 
68
  Args:
69
  email (str): La direcci贸n de correo electr贸nico del cliente.
70
- (Se usar谩 para buscar si el cliente ya existe).
71
- firebase_user (str, opcional): El ID de usuario de Firebase. Se agregar谩 a 'metadata'.
 
72
  site (str, opcional): El nombre del sitio de origen. Se agregar谩 a 'metadata'.
73
 
74
  Returns:
75
- tuple: (stripe.Customer, str) donde el string indica "found" o "created".
76
  None: Si ocurre un error.
77
  """
78
  try:
79
- # --- 1. Intentar buscar un cliente existente por email ---
80
- existing_customers = stripe.Customer.list(email=email, limit=1)
81
-
82
- if existing_customers.data:
83
- customer = existing_customers.data[0]
84
- print(f"Cliente existente encontrado por email. ID: {customer.id}")
85
- return customer, "found" # Retorna el cliente y el estado "found"
86
 
87
- # --- 2. Si el cliente no existe, crearlo ---
88
- print(f"Cliente con email '{email}' no encontrado. Creando nuevo cliente...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
  customer_params = {
91
  'email': email,
92
  }
93
 
94
- # Construir el diccionario de metadata con firebase_user y site
95
  customer_metadata = {}
96
  if firebase_user:
97
  customer_metadata['firebase_user'] = firebase_user
98
  if site:
99
  customer_metadata['site'] = site
100
 
101
- if customer_metadata: # Solo agregar metadata si no est谩 vac铆a
102
  customer_params['metadata'] = customer_metadata
103
 
104
  customer = stripe.Customer.create(**customer_params)
105
 
106
  print(f"Nuevo cliente creado exitosamente. ID: {customer.id}")
107
- return customer, "created" # Retorna el cliente y el estado "created"
108
 
109
  except stripe.error.StripeError as e:
110
  print(f"Error de Stripe al buscar o crear el cliente: {e}")
 
28
  'client_reference_id': 'HERC'
29
  }
30
 
31
+ print("Estoy por entrar a checar el customer id que es: ", customer_id)
32
+
33
  # Opciones para el cliente
34
+ if customer_id:
35
+ session_params['customer'] = customer_id
36
  elif customer_email:
37
  session_params['customer_email'] = customer_email
38
+ print("Sal铆 del elif")
39
  else:
40
+ print("Entr茅 al else...")
41
  # Si no se provee ni customer_id ni customer_email, Stripe puede crear uno si es necesario
42
  # O podr铆as pedir el email en el formulario de Checkout.
43
  pass
 
66
 
67
  def create_stripe_customer(email, firebase_user=None, site=None):
68
  """
69
+ Busca un cliente existente en Stripe, priorizando el Firebase User ID usando Customer.search.
70
+ Si el cliente no existe por Firebase User ID, intenta buscar por email.
71
+ Si el cliente tampoco existe por email, lo crea.
72
 
73
  Args:
74
  email (str): La direcci贸n de correo electr贸nico del cliente.
75
+ (Se usar谩 para buscar si el cliente ya existe si no se encuentra por Firebase UID).
76
+ firebase_user (str, opcional): El ID de usuario de Firebase. **Identificador principal para la b煤squeda.**
77
+ Se agregar谩 a 'metadata'.
78
  site (str, opcional): El nombre del sitio de origen. Se agregar谩 a 'metadata'.
79
 
80
  Returns:
81
+ tuple: (stripe.Customer, str) donde el string indica "found_by_firebase_user", "found_by_email" o "created".
82
  None: Si ocurre un error.
83
  """
84
  try:
85
+ customer_found_status = None
86
+ found_customer = None
 
 
 
 
 
87
 
88
+ # --- 1. Intentar buscar un cliente existente por firebase_user (PRIORIDAD ALTA con Customer.search) ---
89
+ if firebase_user:
90
+ # Usamos stripe.Customer.search para buscar en metadata.
91
+ # Aseg煤rate de escapar comillas si el firebase_user pudiera contenerlas,
92
+ # aunque los UIDs de Firebase no suelen tenerlas.
93
+ search_query = f"metadata['firebase_user']:'{firebase_user}'"
94
+ print(f"Buscando cliente con query: {search_query}") # Para depuraci贸n
95
+
96
+ # search retorna un StripeSearchResultObject, que se itera como una lista
97
+ existing_customers_by_firebase = stripe.Customer.search(query=search_query, limit=1)
98
+
99
+ if existing_customers_by_firebase.data:
100
+ found_customer = existing_customers_by_firebase.data[0]
101
+ customer_found_status = "found_by_firebase_user"
102
+ print(f"Cliente existente encontrado por Firebase User ID. ID: {found_customer.id}")
103
+
104
+ # --- 2. Si no se encontr贸 por firebase_user, intentar buscar por email ---
105
+ if not found_customer:
106
+ print(f"Cliente no encontrado por Firebase UID. Buscando por email: {email}") # Para depuraci贸n
107
+ existing_customers_by_email = stripe.Customer.list(email=email, limit=1)
108
+ if existing_customers_by_email.data:
109
+ found_customer = existing_customers_by_email.data[0]
110
+ customer_found_status = "found_by_email"
111
+ print(f"Cliente existente encontrado por email. ID: {found_customer.id}")
112
+
113
+ # Opcional: Si lo encontraste por email pero tiene un firebase_user nuevo o nulo, actual铆zalo
114
+ # o si el site difiere, tambi茅n actualizarlo.
115
+ updated_metadata = found_customer.metadata.copy() if found_customer.metadata is not None else {}
116
+
117
+ needs_update = False
118
+ if firebase_user and updated_metadata.get('firebase_user') != firebase_user:
119
+ updated_metadata['firebase_user'] = firebase_user
120
+ needs_update = True
121
+ if site and updated_metadata.get('site') != site:
122
+ updated_metadata['site'] = site
123
+ needs_update = True
124
+
125
+ if needs_update:
126
+ print(f"Actualizando metadata para cliente {found_customer.id}")
127
+ found_customer = stripe.Customer.modify(found_customer.id, metadata=updated_metadata)
128
+
129
+ # Si se encontr贸 un cliente (por cualquiera de los m茅todos), lo retornamos
130
+ if found_customer:
131
+ return found_customer, customer_found_status
132
+
133
+ # --- 3. Si el cliente no existe (ni por firebase_user ni por email), crearlo ---
134
+ print(f"Cliente con email '{email}' y/o firebase_user '{firebase_user}' no encontrado. Creando nuevo cliente...")
135
 
136
  customer_params = {
137
  'email': email,
138
  }
139
 
 
140
  customer_metadata = {}
141
  if firebase_user:
142
  customer_metadata['firebase_user'] = firebase_user
143
  if site:
144
  customer_metadata['site'] = site
145
 
146
+ if customer_metadata:
147
  customer_params['metadata'] = customer_metadata
148
 
149
  customer = stripe.Customer.create(**customer_params)
150
 
151
  print(f"Nuevo cliente creado exitosamente. ID: {customer.id}")
152
+ return customer, "created"
153
 
154
  except stripe.error.StripeError as e:
155
  print(f"Error de Stripe al buscar o crear el cliente: {e}")