gateway/modules/shared/stripeClient.py

53 lines
1.4 KiB
Python

# Copyright (c) 2025 Patrick Motsch
# All rights reserved.
"""
Central Stripe SDK initialization.
All Stripe interactions MUST use getStripeClient() to ensure consistent
API key, API version, and fallback handling across billing and subscription flows.
"""
import logging
import json
from typing import Any, Dict, Optional
logger = logging.getLogger(__name__)
_stripeInitialized = False
def stripeToDict(obj) -> Dict[str, Any]:
"""Convert a Stripe object to a plain dict, compatible with all stripe-python versions."""
if isinstance(obj, dict):
return obj
if hasattr(obj, "to_dict_recursive"):
return obj.to_dict_recursive()
if hasattr(obj, "to_dict"):
return obj.to_dict()
try:
return json.loads(str(obj))
except (json.JSONDecodeError, TypeError):
return dict(obj)
def getStripeClient():
"""
Initialize and return the configured Stripe SDK module.
Raises ValueError if no Stripe secret key is configured.
"""
import stripe
from modules.shared.configuration import APP_CONFIG
apiVersion = APP_CONFIG.get("STRIPE_API_VERSION")
if apiVersion:
stripe.api_version = apiVersion
secretKey = APP_CONFIG.get("STRIPE_SECRET_KEY_SECRET") or APP_CONFIG.get("STRIPE_SECRET_KEY")
if not secretKey:
raise ValueError("STRIPE_SECRET_KEY_SECRET not configured")
stripe.api_key = secretKey
return stripe