import stripe from django.conf import settings import logging logger = logging.getLogger(__name__) class StripeService: """Service class to manage Stripe operations with mode awareness""" def __init__(self): # Determine if we're in test mode self.mode = getattr(settings, 'STRIPE_MODE', 'test') self.is_test_mode = self.mode == 'test' # Get appropriate keys based on mode self.api_key = settings.STRIPE_SECRET_KEY self.publishable_key = settings.STRIPE_PUBLISHABLE_KEY self.webhook_secret = settings.STRIPE_WEBHOOK_SECRET self.currency = getattr(settings, 'STRIPE_CURRENCY', 'eur') # Configure Stripe library stripe.api_key = self.api_key # Log initialization in debug mode mode_str = "TEST" if self.is_test_mode else "LIVE" logger.debug(f"Initialized StripeService in {mode_str} mode") def create_checkout_session(self, customer_email=None, line_items=None, success_url=None, cancel_url=None, metadata=None, discounts=None): """Create a Stripe checkout session with the given parameters""" # Initialize session parameters session_params = { 'payment_method_types': ['card'], 'line_items': line_items, 'mode': 'payment', 'success_url': success_url, 'cancel_url': cancel_url, 'metadata': metadata or {}, } # Add customer email if provided if customer_email: session_params['customer_email'] = customer_email # Add discounts if provided if discounts: session_params['discounts'] = discounts # Create and return the session return stripe.checkout.Session.create(**session_params) def verify_webhook_signature(self, payload, signature): """Verify webhook signature using mode-appropriate secret""" try: event = stripe.Webhook.construct_event( payload, signature, self.webhook_secret ) return event except stripe.error.SignatureVerificationError as e: logger.error(f"Webhook signature verification failed: {str(e)}") raise def construct_event_for_testing(self, payload, signature): """Helper method to construct events during testing""" return stripe.Webhook.construct_event( payload, signature, self.webhook_secret ) def get_checkout_session(self, session_id): """Retrieve a checkout session by ID""" return stripe.checkout.Session.retrieve(session_id) def get_payment_intent(self, payment_intent_id): """Retrieve a payment intent by ID""" return stripe.PaymentIntent.retrieve(payment_intent_id) # Create a singleton instance for import and use throughout the app stripe_service = StripeService()