|
4 | 4 | """ |
5 | 5 | Funciones de utilidad interna para la aplicación de cuentas (accounts). |
6 | 6 | """ |
| 7 | +import time |
7 | 8 | from django.contrib import messages |
8 | 9 | from django.utils import timezone |
| 10 | +from django.conf import settings |
| 11 | +import stripe |
9 | 12 | from rides.models import Ride |
10 | 13 | from .models import UserProfile |
11 | 14 | from .forms import UserProfileForm |
|
16 | 19 | get_user_age, update_last_activity |
17 | 20 | ) |
18 | 21 |
|
| 22 | +# Configurar la API de Stripe |
| 23 | +stripe.api_key = settings.STRIPE_SECRET_KEY |
| 24 | + |
19 | 25 | def get_user_and_profile(request, username): |
20 | 26 | """ |
21 | 27 | Obtiene un usuario y su perfil dado un nombre de usuario. |
@@ -203,3 +209,145 @@ def get_vehicle_fields(profile): |
203 | 209 | bool(profile.vehicle_year), |
204 | 210 | bool(profile.vehicle_color) |
205 | 211 | ] |
| 212 | + |
| 213 | +def create_stripe_customer(user): |
| 214 | + """ |
| 215 | + Crea un cliente de Stripe para un usuario. |
| 216 | + |
| 217 | + Args: |
| 218 | + user: Objeto User de Django |
| 219 | + |
| 220 | + Returns: |
| 221 | + str: ID del cliente de Stripe creado, o None si hay error |
| 222 | + """ |
| 223 | + try: |
| 224 | + customer = stripe.Customer.create( |
| 225 | + email=user.email, |
| 226 | + name=f"{user.first_name} {user.last_name}" if (user.first_name and user.last_name) else user.username, |
| 227 | + metadata={ |
| 228 | + 'user_id': str(user.id), |
| 229 | + 'username': user.username |
| 230 | + } |
| 231 | + ) |
| 232 | + return customer.id |
| 233 | + except Exception as e: |
| 234 | + print(f"Error al crear cliente de Stripe: {str(e)}") |
| 235 | + return None |
| 236 | + |
| 237 | +def create_stripe_connect_account(user): |
| 238 | + """ |
| 239 | + Crea una cuenta de Stripe Connect para un usuario. |
| 240 | + |
| 241 | + Args: |
| 242 | + user: Objeto User de Django |
| 243 | + |
| 244 | + Returns: |
| 245 | + str: ID de la cuenta de Stripe Connect creada, o None si hay error |
| 246 | + """ |
| 247 | + try: |
| 248 | + if not user.email or user.email.strip() == '': |
| 249 | + print(f"Error: El usuario {user.username} no tiene un correo electrónico válido") |
| 250 | + return None |
| 251 | + |
| 252 | + try: |
| 253 | + stripe.Account.list(limit=1) |
| 254 | + print(f"Verificación de permisos de Stripe Connect: OK") |
| 255 | + except stripe.error.PermissionError as perm_error: |
| 256 | + print(f"Error de permisos en Stripe Connect: {str(perm_error)}") |
| 257 | + print("La API key no tiene permisos para crear cuentas Connect") |
| 258 | + return None |
| 259 | + except Exception as check_error: |
| 260 | + print(f"Error al verificar permisos de Stripe Connect: {str(check_error)}") |
| 261 | + |
| 262 | + account = stripe.Account.create( |
| 263 | + type="standard", # Más simple que 'express' y requiere menos configuración |
| 264 | + country="ES", # España |
| 265 | + email=user.email.strip(), |
| 266 | + business_type="individual", |
| 267 | + metadata={ |
| 268 | + 'user_id': str(user.id), |
| 269 | + 'username': user.username |
| 270 | + } |
| 271 | + ) |
| 272 | + |
| 273 | + print(f"Cuenta Stripe Connect creada con éxito: {account.id}") |
| 274 | + return account.id |
| 275 | + |
| 276 | + except stripe.error.InvalidRequestError as e: |
| 277 | + print(f"Error de solicitud inválida al crear cuenta de Stripe Connect: {str(e)}") |
| 278 | + return None |
| 279 | + except stripe.error.AuthenticationError as e: |
| 280 | + print(f"Error de autenticación en Stripe: {str(e)}") |
| 281 | + return None |
| 282 | + except stripe.error.APIConnectionError as e: |
| 283 | + print(f"Error de conexión con la API de Stripe: {str(e)}") |
| 284 | + return None |
| 285 | + except stripe.error.StripeError as e: |
| 286 | + print(f"Error general de Stripe al crear cuenta Connect: {str(e)}") |
| 287 | + return None |
| 288 | + except Exception as e: |
| 289 | + print(f"Error inesperado al crear cuenta de Stripe Connect: {str(e)}") |
| 290 | + return None |
| 291 | + |
| 292 | +def associate_stripe_accounts_to_user(user): |
| 293 | + """ |
| 294 | + Crea y asocia cuentas de Stripe a un usuario. |
| 295 | + |
| 296 | + Args: |
| 297 | + user: Objeto User de Django |
| 298 | + |
| 299 | + Returns: |
| 300 | + tuple: (customer_id, account_id) o (None, None) si hay error |
| 301 | + """ |
| 302 | + try: |
| 303 | + profile = user.profile |
| 304 | + |
| 305 | + if profile.stripe_customer_id and profile.stripe_account_id: |
| 306 | + return profile.stripe_customer_id, profile.stripe_account_id |
| 307 | + |
| 308 | + if not profile.stripe_customer_id: |
| 309 | + customer_id = create_stripe_customer(user) |
| 310 | + if customer_id: |
| 311 | + profile.stripe_customer_id = customer_id |
| 312 | + |
| 313 | + if not profile.stripe_account_id: |
| 314 | + account_id = create_stripe_connect_account(user) |
| 315 | + if account_id: |
| 316 | + profile.stripe_account_id = account_id |
| 317 | + |
| 318 | + if profile.stripe_customer_id or profile.stripe_account_id: |
| 319 | + profile.save(update_fields=['stripe_customer_id', 'stripe_account_id']) |
| 320 | + |
| 321 | + return profile.stripe_customer_id, profile.stripe_account_id |
| 322 | + except Exception as e: |
| 323 | + print(f"Error al asociar cuentas de Stripe al usuario: {str(e)}") |
| 324 | + return None, None |
| 325 | + |
| 326 | +def create_stripe_onboarding_link(user): |
| 327 | + """ |
| 328 | + Crea un enlace de onboarding para que el usuario complete su registro en Stripe Connect. |
| 329 | + |
| 330 | + Args: |
| 331 | + user: Objeto User de Django |
| 332 | + |
| 333 | + Returns: |
| 334 | + str: URL del enlace de onboarding, o None si hay error |
| 335 | + """ |
| 336 | + try: |
| 337 | + profile = user.profile |
| 338 | + |
| 339 | + if not profile.stripe_account_id: |
| 340 | + print(f"Error: El usuario {user.username} no tiene una cuenta de Stripe Connect") |
| 341 | + return None |
| 342 | + |
| 343 | + account_link = stripe.AccountLink.create( |
| 344 | + account=profile.stripe_account_id, |
| 345 | + refresh_url=f"https://{settings.ALLOWED_HOSTS[0]}/accounts/settings/", |
| 346 | + return_url=f"https://{settings.ALLOWED_HOSTS[0]}/accounts/settings/", |
| 347 | + type="account_onboarding", |
| 348 | + ) |
| 349 | + |
| 350 | + return account_link.url |
| 351 | + except Exception as e: |
| 352 | + print(f"Error al crear enlace de onboarding de Stripe: {str(e)}") |
| 353 | + return None |
0 commit comments