Spaces:
Running
Running
Customer as index to add tokens
Browse files- fireWhale.py +40 -1
- herramientas.py +16 -12
- main.py +8 -9
fireWhale.py
CHANGED
|
@@ -123,4 +123,43 @@ def verificar_token(id_token):
|
|
| 123 |
return uid # Retorna el UID del usuario si el token es válido
|
| 124 |
except auth.InvalidIdTokenError as e:
|
| 125 |
print(f"Token inválido: {e}")
|
| 126 |
-
return None # Retorna None si el token es inválido
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
return uid # Retorna el UID del usuario si el token es válido
|
| 124 |
except auth.InvalidIdTokenError as e:
|
| 125 |
print(f"Token inválido: {e}")
|
| 126 |
+
return None # Retorna None si el token es inválido
|
| 127 |
+
|
| 128 |
+
def encontrar_documento_por_cus(valor_cus):
|
| 129 |
+
"""
|
| 130 |
+
Busca un documento en la colección 'usuario' donde el campo 'cus'
|
| 131 |
+
coincide con el valor_cus especificado.
|
| 132 |
+
|
| 133 |
+
Args:
|
| 134 |
+
valor_cus (str): El valor exacto del campo 'cus' a buscar.
|
| 135 |
+
|
| 136 |
+
Returns:
|
| 137 |
+
tuple: Una tupla (document_id, document_data) si se encuentra,
|
| 138 |
+
o (None, None) si no se encuentra o hay un error.
|
| 139 |
+
Retorna solo el primer documento encontrado si hay múltiples coincidencias.
|
| 140 |
+
"""
|
| 141 |
+
print(f"\n--- Buscando documento en 'usuario' con cus: '{valor_cus}' ---")
|
| 142 |
+
|
| 143 |
+
try:
|
| 144 |
+
# Realizamos la consulta: filtra por documentos donde 'cus' sea igual a valor_cus
|
| 145 |
+
query_results = db.collection('usuario').where(
|
| 146 |
+
filter=firestore.FieldFilter('cus', '==', valor_cus)
|
| 147 |
+
).limit(1).get() # Agregamos .limit(1) porque esperas un único documento
|
| 148 |
+
|
| 149 |
+
if not query_results:
|
| 150 |
+
print(f"❌ No se encontró ningún documento con 'cus' = '{valor_cus}'.")
|
| 151 |
+
return None, None
|
| 152 |
+
|
| 153 |
+
# Si se encuentra, query_results será una lista de instantáneas de documentos
|
| 154 |
+
# Tomamos el primer resultado (ya que usamos limit(1))
|
| 155 |
+
doc_snapshot = query_results[0]
|
| 156 |
+
|
| 157 |
+
doc_id = doc_snapshot.id
|
| 158 |
+
doc_data = doc_snapshot.to_dict()
|
| 159 |
+
|
| 160 |
+
print(f"✔️ Documento encontrado: ID='{doc_id}', Datos: {doc_data}")
|
| 161 |
+
return doc_id, doc_data
|
| 162 |
+
|
| 163 |
+
except Exception as e:
|
| 164 |
+
print(f"❌ Error al buscar documento por 'cus': {e}")
|
| 165 |
+
return None, None
|
herramientas.py
CHANGED
|
@@ -23,7 +23,7 @@ def imprimeTime():
|
|
| 23 |
|
| 24 |
return formatted_time
|
| 25 |
|
| 26 |
-
def registrar_evento(
|
| 27 |
"""
|
| 28 |
Guarda la fecha y hora actual junto con un tipo de evento
|
| 29 |
en un archivo 'registro.txt' en la raíz del proyecto.
|
|
@@ -35,24 +35,28 @@ def registrar_evento(event_type: str):
|
|
| 35 |
fecha = imprimeTime() # Utiliza tu función existente
|
| 36 |
|
| 37 |
# 2. Definir el nombre del archivo de registro
|
| 38 |
-
file_name = "registro.txt"
|
| 39 |
|
| 40 |
# 3. Obtener la ruta completa al archivo en la raíz del proyecto
|
| 41 |
# Esto asume que el script que llama a esta función está en la raíz.
|
| 42 |
-
script_dir = os.path.dirname(os.path.abspath(__file__))
|
| 43 |
-
registro_path = os.path.join(script_dir, file_name)
|
| 44 |
|
| 45 |
# 4. Formatear la línea que se guardará en el archivo
|
| 46 |
# Puedes elegir el formato que prefieras. Un buen formato sería CSV o algo legible.
|
| 47 |
# Por ejemplo: "FECHA_HORA,TIPO_DE_EVENTO\n"
|
| 48 |
-
log_line = f"{fecha},{
|
| 49 |
|
| 50 |
-
fireWhale.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
# 5. Abrir el archivo en modo de añadir ('a') y escribir la línea
|
| 53 |
-
try:
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
except Exception as e:
|
| 58 |
-
|
|
|
|
| 23 |
|
| 24 |
return formatted_time
|
| 25 |
|
| 26 |
+
def registrar_evento(cus: str):
|
| 27 |
"""
|
| 28 |
Guarda la fecha y hora actual junto con un tipo de evento
|
| 29 |
en un archivo 'registro.txt' en la raíz del proyecto.
|
|
|
|
| 35 |
fecha = imprimeTime() # Utiliza tu función existente
|
| 36 |
|
| 37 |
# 2. Definir el nombre del archivo de registro
|
| 38 |
+
#file_name = "registro.txt"
|
| 39 |
|
| 40 |
# 3. Obtener la ruta completa al archivo en la raíz del proyecto
|
| 41 |
# Esto asume que el script que llama a esta función está en la raíz.
|
| 42 |
+
# script_dir = os.path.dirname(os.path.abspath(__file__))
|
| 43 |
+
# registro_path = os.path.join(script_dir, file_name)
|
| 44 |
|
| 45 |
# 4. Formatear la línea que se guardará en el archivo
|
| 46 |
# Puedes elegir el formato que prefieras. Un buen formato sería CSV o algo legible.
|
| 47 |
# Por ejemplo: "FECHA_HORA,TIPO_DE_EVENTO\n"
|
| 48 |
+
#log_line = f"{fecha},{cus}\n"
|
| 49 |
|
| 50 |
+
resultado = fireWhale.encontrar_documento_por_cus(cus)
|
| 51 |
+
print("Ésto es el resultado de buscar el cus:")
|
| 52 |
+
print(resultado)
|
| 53 |
+
|
| 54 |
+
fireWhale.editaDato('usuarios', resultado, 'tokens', 182)
|
| 55 |
|
| 56 |
# 5. Abrir el archivo en modo de añadir ('a') y escribir la línea
|
| 57 |
+
# try:
|
| 58 |
+
# with open(registro_path, 'a') as f:
|
| 59 |
+
# f.write(log_line)
|
| 60 |
+
# print(f"[{fecha}] Evento '{event_type}' registrado con éxito en '{registro_path}'")
|
| 61 |
+
# except Exception as e:
|
| 62 |
+
# print(f"Error al escribir en el archivo de registro '{registro_path}': {e}")
|
main.py
CHANGED
|
@@ -34,8 +34,7 @@ async def webhook_received(request: Request, stripe_signature: str = Header(None
|
|
| 34 |
)
|
| 35 |
# print("Evento construido...")
|
| 36 |
# print(event)
|
| 37 |
-
# print("Evento impreso")
|
| 38 |
-
|
| 39 |
|
| 40 |
except Exception as e:
|
| 41 |
print("Excepción es: ", e)
|
|
@@ -45,20 +44,20 @@ async def webhook_received(request: Request, stripe_signature: str = Header(None
|
|
| 45 |
print("Voy a imprimir el event type:")
|
| 46 |
print(event_type)
|
| 47 |
|
| 48 |
-
if event_type == '
|
| 49 |
-
print('
|
| 50 |
-
herramientas.registrar_evento(event_type)
|
| 51 |
print(event_data)
|
| 52 |
-
print("Ready")
|
| 53 |
-
#time.sleep(80)
|
| 54 |
print(event_data['created'])
|
| 55 |
print(event_data['id'])
|
| 56 |
print(event_data['payment_intent'])
|
| 57 |
print(event_data['payment_method'])
|
| 58 |
print(event_data['receipt_url'])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
-
# autorizacion = sulkuPypi.authorize(19, 'picswap')
|
| 61 |
-
# print("Autorización: ", autorizacion)
|
| 62 |
else:
|
| 63 |
print(f'unhandled event: {event_type}')
|
| 64 |
|
|
|
|
| 34 |
)
|
| 35 |
# print("Evento construido...")
|
| 36 |
# print(event)
|
| 37 |
+
# print("Evento impreso")
|
|
|
|
| 38 |
|
| 39 |
except Exception as e:
|
| 40 |
print("Excepción es: ", e)
|
|
|
|
| 44 |
print("Voy a imprimir el event type:")
|
| 45 |
print(event_type)
|
| 46 |
|
| 47 |
+
if event_type == 'payment_intent.succeeded':
|
| 48 |
+
print('payment intent succeed')
|
|
|
|
| 49 |
print(event_data)
|
| 50 |
+
print("Ready")
|
|
|
|
| 51 |
print(event_data['created'])
|
| 52 |
print(event_data['id'])
|
| 53 |
print(event_data['payment_intent'])
|
| 54 |
print(event_data['payment_method'])
|
| 55 |
print(event_data['receipt_url'])
|
| 56 |
+
print("Customer:")
|
| 57 |
+
cus = event_data['customer']
|
| 58 |
+
print(cus)
|
| 59 |
+
herramientas.registrar_evento(cus)
|
| 60 |
|
|
|
|
|
|
|
| 61 |
else:
|
| 62 |
print(f'unhandled event: {event_type}')
|
| 63 |
|