Moibe commited on
Commit
2d73b8f
·
1 Parent(s): e7fec2d

Last before prod

Browse files
Files changed (7) hide show
  1. .gitignore +2 -1
  2. autenticacion.py +28 -0
  3. globales.py +3 -0
  4. herramientas.py +55 -0
  5. main.py +37 -48
  6. registro.txt +7 -0
  7. requirements.txt +0 -0
.gitignore CHANGED
@@ -1,3 +1,4 @@
1
  /venv/
2
  /__pycache__/
3
- stripe.exe
 
 
1
  /venv/
2
  /__pycache__/
3
+ stripe.exe
4
+ bridges.py
autenticacion.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import socket
3
+
4
+ def defineAmbiente():
5
+ if local_check():
6
+ print("Entorno Local...")
7
+ import bridges
8
+ llave = bridges.llave
9
+ webhook = bridges.webhook
10
+ else:
11
+ print("Entorno remoto listo...")
12
+ llave = os.getenv("STRIPE_KEY") #Acceso a HF
13
+ webhook = os.getenv("STRIPE_WEBHOOK_SECRET")
14
+ print(f"La llave es {llave} y el webhook es {webhook}.")
15
+
16
+ return llave, webhook
17
+
18
+ def local_check():
19
+ hostname = socket.gethostname()
20
+ #r-moibe-nowme
21
+ print("Hostname: ", hostname)
22
+ #Estoy usando el nombre de la app para identificar que estoy corriendola en HF.
23
+ if "-nowme" in hostname:
24
+ print("Ejecutando api en el servidor.")
25
+ return False
26
+ else:
27
+ print("Ejecutando api en local.")
28
+ return True
globales.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ import autenticacion
2
+
3
+ llave, webhook = autenticacion.defineAmbiente()
herramientas.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import pytz
3
+ import os
4
+
5
+ def imprimeTime():
6
+ """
7
+ Devuelve la fecha y hora actual en la zona horaria de la Ciudad de México (GMT-6).
8
+ """
9
+ # 1. Definir la zona horaria de la Ciudad de México
10
+ # Puedes usar 'America/Mexico_City' para que pytz maneje el horario de verano automáticamente.
11
+ mexico_city_tz = pytz.timezone('America/Mexico_City')
12
+
13
+ # 2. Obtener la hora actual en UTC
14
+ utc_now = datetime.now(pytz.utc)
15
+
16
+ # 3. Convertir la hora UTC a la zona horaria deseada
17
+ mexico_city_now = utc_now.astimezone(mexico_city_tz)
18
+
19
+ # 4. Formatear la fecha y hora
20
+ # El formato que deseas es "YYYY-MM-DD HH:MM:SS"
21
+ formatted_time = mexico_city_now.strftime("%Y-%m-%d %H:%M:%S")
22
+
23
+ return formatted_time
24
+
25
+ def registrar_evento(event_type: str):
26
+ """
27
+ Guarda la fecha y hora actual junto con un tipo de evento
28
+ en un archivo 'registro.txt' en la raíz del proyecto.
29
+
30
+ Args:
31
+ event_type (str): Una descripción del tipo de evento a registrar.
32
+ """
33
+ # 1. Obtener la fecha y hora actual en el formato deseado
34
+ fecha = imprimeTime() # Utiliza tu función existente
35
+
36
+ # 2. Definir el nombre del archivo de registro
37
+ file_name = "registro.txt"
38
+
39
+ # 3. Obtener la ruta completa al archivo en la raíz del proyecto
40
+ # Esto asume que el script que llama a esta función está en la raíz.
41
+ script_dir = os.path.dirname(os.path.abspath(__file__))
42
+ registro_path = os.path.join(script_dir, file_name)
43
+
44
+ # 4. Formatear la línea que se guardará en el archivo
45
+ # Puedes elegir el formato que prefieras. Un buen formato sería CSV o algo legible.
46
+ # Por ejemplo: "FECHA_HORA,TIPO_DE_EVENTO\n"
47
+ log_line = f"{fecha},{event_type}\n"
48
+
49
+ # 5. Abrir el archivo en modo de añadir ('a') y escribir la línea
50
+ try:
51
+ with open(registro_path, 'a') as f:
52
+ f.write(log_line)
53
+ print(f"[{fecha}] Evento '{event_type}' registrado con éxito en '{registro_path}'")
54
+ except Exception as e:
55
+ print(f"Error al escribir en el archivo de registro '{registro_path}': {e}")
main.py CHANGED
@@ -1,75 +1,64 @@
1
- import os
2
  import time
3
  import stripe
4
- import uvicorn
5
  from fastapi import FastAPI, Request, Header
6
  import sulkuPypi
 
 
7
 
8
  app = FastAPI()
9
 
10
- #Local on Windows.
11
- #stripe.api_key = os.environ["STRIPE_KEY"]
12
- #API_KEY secret.
13
- stripe.api_key = os.getenv("STRIPE_KEY")
14
- webhook_secret = os.getenv("STRIPE_WEBHOOK_SECRET")
15
-
16
- string_key = stripe.api_key
17
  # This is a terrible idea, only used for demo purposes!
18
  app.state.stripe_customer_id = None
19
 
20
  @app.get("/")
21
  def start():
22
-
23
- print(stripe.api_key)
24
- print(webhook_secret)
25
-
26
- autorizacion = sulkuPypi.authorize(19, 'picswap')
27
-
28
- print("Autorización: ", autorizacion)
29
-
30
  return {f"Status":"Deployed"}
31
 
32
  @app.post("/webhook")
33
- async def webhook_received(request: Request, stripe_signature: str = Header(None)):
34
-
35
- #Local on Windows
36
- #webhook_secret = os.environ["STRIPE_WEBHOOK_SECRET"]
37
 
 
 
38
  data = await request.body()
39
- print("Estoy imprimiendo la data del request: ")
40
- print(data)
41
- print("TERMINÉ")
42
 
43
- event = stripe.Webhook.construct_event(
44
- payload=data,
45
- sig_header=stripe_signature,
46
- secret=webhook_secret
47
- )
48
- event_data = event['data']
49
- # print("Ésto es el event data: ")
50
- # print(event_data)
51
 
52
-
 
 
 
 
 
 
 
 
 
 
 
53
  event_type = event['type']
54
  print("Voy a imprimir el event type:")
55
  print(event_type)
56
- time.sleep(2)
57
-
58
- if event_type == 'charge.succeed':
59
  print('charge succeed')
60
- autorizacion = sulkuPypi.authorize(19, 'picswap')
61
- print("Autorización: ", autorizacion)
62
-
 
 
 
 
 
 
 
 
 
63
  else:
64
- print(f'unhandled event: {event_type}')
65
-
66
 
67
  return {"status": "success"}
68
 
69
-
70
-
71
-
72
-
73
-
74
- if __name__ == '__main__':
75
- uvicorn.run("main:app", reload=True)
 
 
1
  import time
2
  import stripe
 
3
  from fastapi import FastAPI, Request, Header
4
  import sulkuPypi
5
+ import globales
6
+ import herramientas
7
 
8
  app = FastAPI()
9
 
10
+ string_key = globales.llave
 
 
 
 
 
 
11
  # This is a terrible idea, only used for demo purposes!
12
  app.state.stripe_customer_id = None
13
 
14
  @app.get("/")
15
  def start():
 
 
 
 
 
 
 
 
16
  return {f"Status":"Deployed"}
17
 
18
  @app.post("/webhook")
19
+ async def webhook_received(request: Request, stripe_signature: str = Header(None)):
 
 
 
20
 
21
+ webhook_secret = globales.webhook
22
+
23
  data = await request.body()
24
+ print("data ready")
 
 
25
 
26
+ print("Construyendo el evento:")
 
 
 
 
 
 
 
27
 
28
+ try:
29
+ event = stripe.Webhook.construct_event(
30
+ payload=data,
31
+ sig_header=stripe_signature,
32
+ secret=webhook_secret
33
+ )
34
+ print("Evento construido...")
35
+
36
+ except Exception as e:
37
+ print("Excepción es: ", e)
38
+
39
+ event_data = event['data']['object']
40
  event_type = event['type']
41
  print("Voy a imprimir el event type:")
42
  print(event_type)
43
+
44
+ if event_type == 'charge.succeeded':
 
45
  print('charge succeed')
46
+ herramientas.registrar_evento(event_type)
47
+ print(event_data)
48
+ print("Ready")
49
+ time.sleep(80)
50
+ print(event_data['created'])
51
+ print(event_data['id'])
52
+ print(event_data['payment_intent'])
53
+ print(event_data['payment_method'])
54
+ print(event_data['receipt_url'])
55
+
56
+ # autorizacion = sulkuPypi.authorize(19, 'picswap')
57
+ # print("Autorización: ", autorizacion)
58
  else:
59
+ print(f'unhandled event: {event_type}')
 
60
 
61
  return {"status": "success"}
62
 
63
+ # if __name__ == '__main__':
64
+ # uvicorn.run("main:app", reload=True)
 
 
 
 
 
registro.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ 2025-05-25 10:48:06,charge.succeeded
2
+ 2025-05-25 10:50:49,charge.succeeded
3
+ 2025-05-25 13:33:46,charge.succeeded
4
+ 2025-05-25 14:29:47,charge.succeeded
5
+ 2025-05-25 14:47:05,charge.succeeded
6
+ 2025-06-08 20:52:35,charge.succeeded
7
+ 2025-07-23 20:01:58,charge.succeeded
requirements.txt CHANGED
Binary files a/requirements.txt and b/requirements.txt differ