Spaces:
Sleeping
Sleeping
Crear Cliente
Browse files- app.py +52 -7
- funciones.py +51 -2
- globales.py +1 -2
app.py
CHANGED
|
@@ -1,9 +1,7 @@
|
|
| 1 |
import funciones
|
| 2 |
-
from fastapi import FastAPI, Form
|
| 3 |
-
from fastapi import FastAPI
|
| 4 |
from fastapi.responses import JSONResponse
|
| 5 |
-
from
|
| 6 |
-
from typing import Optional # Importa Optional
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
|
@@ -19,12 +17,59 @@ async def health_check():
|
|
| 19 |
"""
|
| 20 |
return JSONResponse(content={"status": "ok"}, status_code=200)
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
@app.post("/creaLinkSesion/")
|
| 23 |
async def creaLinkSesion(
|
| 24 |
price_id: str = Form(...), # Sigue siendo requerido, enviado como Form si la petici贸n es multipart/form-data
|
| 25 |
customer_email: Optional[str] = Form(None), # Ahora opcional, valor por defecto None
|
| 26 |
customer_id: Optional[str] = Form(None) # Ahora opcional, valor por defecto None
|
| 27 |
):
|
| 28 |
-
return funciones.create_checkout_session(price_id, customer_email, customer_id)
|
| 29 |
-
|
| 30 |
-
|
|
|
|
| 1 |
import funciones
|
| 2 |
+
from fastapi import FastAPI, Form, HTTPException
|
|
|
|
| 3 |
from fastapi.responses import JSONResponse
|
| 4 |
+
from typing import Optional
|
|
|
|
| 5 |
|
| 6 |
app = FastAPI()
|
| 7 |
|
|
|
|
| 17 |
"""
|
| 18 |
return JSONResponse(content={"status": "ok"}, status_code=200)
|
| 19 |
|
| 20 |
+
@app.post("/creaCliente/")
|
| 21 |
+
async def creaCliente(
|
| 22 |
+
email: str = Form(...),
|
| 23 |
+
name: Optional[str] = Form(None),
|
| 24 |
+
description: Optional[str] = Form(None),
|
| 25 |
+
phone: Optional[str] = Form(None),
|
| 26 |
+
# Si quieres pasar metadata, podr铆as recibirla como un JSON string y luego parsearla
|
| 27 |
+
# o como m煤ltiples campos de formulario si sabes cu谩les ser谩n.
|
| 28 |
+
# Por simplicidad aqu铆, no incluiremos metadata compleja directamente en Form,
|
| 29 |
+
# pero es posible extenderlo.
|
| 30 |
+
):
|
| 31 |
+
"""
|
| 32 |
+
Crea un nuevo cliente (Customer) en Stripe utilizando los datos proporcionados.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
email (str): El correo electr贸nico del cliente.
|
| 36 |
+
name (str, opcional): El nombre del cliente.
|
| 37 |
+
description (str, opcional): Una descripci贸n para el cliente.
|
| 38 |
+
phone (str, opcional): El n煤mero de tel茅fono del cliente.
|
| 39 |
+
|
| 40 |
+
Returns:
|
| 41 |
+
dict: Un diccionario con el ID del cliente de Stripe si la creaci贸n fue exitosa.
|
| 42 |
+
O un error si la creaci贸n fall贸.
|
| 43 |
+
"""
|
| 44 |
+
try:
|
| 45 |
+
# Llama a la funci贸n create_stripe_customer que definimos previamente.
|
| 46 |
+
customer = funciones.create_stripe_customer(
|
| 47 |
+
email=email,
|
| 48 |
+
name=name,
|
| 49 |
+
description=description,
|
| 50 |
+
phone=phone
|
| 51 |
+
# Si quieres a帽adir metadata, aqu铆 la pasar铆as si la recibes en el Form.
|
| 52 |
+
# Por ejemplo: metadata={"origen": "FastAPI", "username": some_username_variable}
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
if customer:
|
| 56 |
+
return {"message": "Cliente creado exitosamente", "customer_id": customer.id, "customer_email": customer.email}
|
| 57 |
+
else:
|
| 58 |
+
# Si la funci贸n retorna None, significa que hubo un error interno
|
| 59 |
+
raise HTTPException(status_code=500, detail="No se pudo crear el cliente en Stripe. Verifica los logs del servidor.")
|
| 60 |
+
|
| 61 |
+
except HTTPException as e:
|
| 62 |
+
# Re-lanza HTTPException para que FastAPI la maneje directamente
|
| 63 |
+
raise e
|
| 64 |
+
except Exception as e:
|
| 65 |
+
# Captura cualquier otra excepci贸n no esperada
|
| 66 |
+
raise HTTPException(status_code=500, detail=f"Ocurri贸 un error inesperado al procesar la solicitud: {str(e)}")
|
| 67 |
+
|
| 68 |
+
|
| 69 |
@app.post("/creaLinkSesion/")
|
| 70 |
async def creaLinkSesion(
|
| 71 |
price_id: str = Form(...), # Sigue siendo requerido, enviado como Form si la petici贸n es multipart/form-data
|
| 72 |
customer_email: Optional[str] = Form(None), # Ahora opcional, valor por defecto None
|
| 73 |
customer_id: Optional[str] = Form(None) # Ahora opcional, valor por defecto None
|
| 74 |
):
|
| 75 |
+
return funciones.create_checkout_session(price_id, customer_email, customer_id)
|
|
|
|
|
|
funciones.py
CHANGED
|
@@ -21,11 +21,11 @@ def create_checkout_session(price_id, customer_email=None, customer_id=None):
|
|
| 21 |
'price': price_id,
|
| 22 |
'quantity': 1,
|
| 23 |
}],
|
| 24 |
-
'mode': '
|
| 25 |
'success_url': 'https://app.splashmix.ink/', #'https://tudominio.com/gracias?session_id={CHECKOUT_SESSION_ID}'
|
| 26 |
'cancel_url': 'https://app.splashmix.ink/',
|
| 27 |
'locale': 'fr', #'es' # Establece el idioma del checkout a espa帽ol
|
| 28 |
-
'client_reference_id': '
|
| 29 |
}
|
| 30 |
|
| 31 |
# Opciones para el cliente
|
|
@@ -58,4 +58,53 @@ def create_checkout_session(price_id, customer_email=None, customer_id=None):
|
|
| 58 |
return None
|
| 59 |
except Exception as e:
|
| 60 |
print(f"Ocurri贸 un error inesperado al crear la Checkout Session: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
return None
|
|
|
|
| 21 |
'price': price_id,
|
| 22 |
'quantity': 1,
|
| 23 |
}],
|
| 24 |
+
'mode': 'payment', #payment Para pagos 煤nicos (one-time payment) o #subscription
|
| 25 |
'success_url': 'https://app.splashmix.ink/', #'https://tudominio.com/gracias?session_id={CHECKOUT_SESSION_ID}'
|
| 26 |
'cancel_url': 'https://app.splashmix.ink/',
|
| 27 |
'locale': 'fr', #'es' # Establece el idioma del checkout a espa帽ol
|
| 28 |
+
'client_reference_id': 'HERC'
|
| 29 |
}
|
| 30 |
|
| 31 |
# Opciones para el cliente
|
|
|
|
| 58 |
return None
|
| 59 |
except Exception as e:
|
| 60 |
print(f"Ocurri贸 un error inesperado al crear la Checkout Session: {e}")
|
| 61 |
+
return None
|
| 62 |
+
|
| 63 |
+
def create_stripe_customer(email, name=None, description=None, phone=None, metadata=None):
|
| 64 |
+
"""
|
| 65 |
+
Crea un nuevo cliente en Stripe.
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
email (str): La direcci贸n de correo electr贸nico del cliente.
|
| 69 |
+
(Altamente recomendado para identificar al cliente).
|
| 70 |
+
name (str, opcional): El nombre completo del cliente.
|
| 71 |
+
description (str, opcional): Una descripci贸n arbitraria del cliente para tus registros.
|
| 72 |
+
phone (str, opcional): El n煤mero de tel茅fono del cliente.
|
| 73 |
+
metadata (dict, opcional): Un diccionario de pares clave-valor para almacenar datos personalizados.
|
| 74 |
+
(Ej. {'user_id_interno': 'XYZ789'}).
|
| 75 |
+
|
| 76 |
+
Returns:
|
| 77 |
+
stripe.Customer: El objeto Customer creado por Stripe si es exitoso.
|
| 78 |
+
None: Si ocurre un error.
|
| 79 |
+
"""
|
| 80 |
+
try:
|
| 81 |
+
customer_params = {
|
| 82 |
+
'email': email,
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
if name:
|
| 86 |
+
customer_params['name'] = name
|
| 87 |
+
if description:
|
| 88 |
+
customer_params['description'] = description
|
| 89 |
+
if phone:
|
| 90 |
+
customer_params['phone'] = phone
|
| 91 |
+
if metadata:
|
| 92 |
+
customer_params['metadata'] = metadata
|
| 93 |
+
|
| 94 |
+
# Llamada a la API de Stripe para crear el cliente
|
| 95 |
+
customer = stripe.Customer.create(**customer_params)
|
| 96 |
+
|
| 97 |
+
print(f"Cliente creado exitosamente. ID del Cliente: {customer.id}")
|
| 98 |
+
print(f"Email: {customer.email}")
|
| 99 |
+
if 'name' in customer and customer.name:
|
| 100 |
+
print(f"Nombre: {customer.name}")
|
| 101 |
+
return customer
|
| 102 |
+
|
| 103 |
+
except stripe.error.StripeError as e:
|
| 104 |
+
# Manejo de errores espec铆ficos de la API de Stripe
|
| 105 |
+
print(f"Error de Stripe al crear el cliente: {e}")
|
| 106 |
+
return None
|
| 107 |
+
except Exception as e:
|
| 108 |
+
# Manejo de cualquier otro error inesperado
|
| 109 |
+
print(f"Ocurri贸 un error inesperado al crear el cliente: {e}")
|
| 110 |
return None
|
globales.py
CHANGED
|
@@ -1,6 +1,5 @@
|
|
| 1 |
import autenticacion
|
| 2 |
|
| 3 |
-
version = "0.
|
| 4 |
-
|
| 5 |
llave = autenticacion.defineAmbiente()
|
| 6 |
|
|
|
|
| 1 |
import autenticacion
|
| 2 |
|
| 3 |
+
version = "0.1.1" #remote env check
|
|
|
|
| 4 |
llave = autenticacion.defineAmbiente()
|
| 5 |
|