2.5 KiB
2.5 KiB
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 = <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
-
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
-
Enhanced Stripe Helper (
app/helpers/stripe_helper.rb):- Added
initialize_stripemethod to initialize Stripe only when needed - Updated
safe_stripe_callto automatically initialize Stripe if not already done
- Added
-
Checkout Process Updates:
- Added explicit Stripe initialization in
process_paymentmethod - Added explicit Stripe initialization in
payment_successmethod - Added proper error handling for initialization failures
- Added explicit Stripe initialization in
-
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)
-
Verification:
- Created
bin/test_stripe_config.rbto verify the lazy initialization approach - Confirmed that Stripe is not initialized at startup but can be initialized during checkout
- Created
Code Changes
config/initializers/stripe.rb
- Removed automatic Stripe.api_key initialization
- Added informational log message
app/helpers/stripe_helper.rb
- Added
initialize_stripemethod - Enhanced
safe_stripe_callmethod
app/controllers/events_controller.rb
- Added Stripe initialization in
process_paymentmethod - Added Stripe initialization in
payment_successmethod - 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.