# Stripe Configuration - Lazy Initialization Approach ## Problem The "Retour" link on the collect_names page sometimes displayed a Stripe API key error: ``` Erreur de traitement du paiement : No API key provided. Set your API key using "Stripe.api_key = ". ``` ## Root Cause The error occurred because Stripe was being initialized at application startup, and if there were any configuration issues, it would affect the entire application. ## Solution Implemented - Lazy Initialization 1. **Deferred Stripe Initialization** (`config/initializers/stripe.rb`): - Stripe configuration is loaded at startup but API key is NOT set - Stripe.api_key is only set during the checkout process when needed 2. **Enhanced Stripe Helper** (`app/helpers/stripe_helper.rb`): - Added `initialize_stripe` method to initialize Stripe only when needed - Updated `safe_stripe_call` to automatically initialize Stripe if not already done 3. **Checkout Process Updates**: - Added explicit Stripe initialization in `process_payment` method - Added explicit Stripe initialization in `payment_success` method - Added proper error handling for initialization failures 4. **Benefits of This Approach**: - Stripe is only initialized when actually needed (during checkout) - Application startup is not dependent on Stripe service availability - Payment-related issues are isolated and don't affect other application features - More efficient resource usage (Stripe library only fully loaded during checkout) 5. **Verification**: - Created `bin/test_stripe_config.rb` to verify the lazy initialization approach - Confirmed that Stripe is not initialized at startup but can be initialized during checkout ## Code Changes ### config/initializers/stripe.rb - Removed automatic Stripe.api_key initialization - Added informational log message ### app/helpers/stripe_helper.rb - Added `initialize_stripe` method - Enhanced `safe_stripe_call` method ### app/controllers/events_controller.rb - Added Stripe initialization in `process_payment` method - Added Stripe initialization in `payment_success` method - Updated error handling to use helper methods ## Testing The new approach has been verified to work correctly: - Stripe is not initialized at application startup - Stripe is properly initialized during the checkout process - All Stripe functionality works as expected - Error handling is improved This approach provides better isolation of payment functionality and ensures that issues with Stripe configuration don't affect the rest of the application.