'Stripe API key missing in controller

I am trying to setup Stripe checkout as described in this GoRails episode

I have defined the publishable_key and secret_key in application.yml using the figaro gem so in my config/initializers/stripe.rb I have this code

Rails.configuration.stripe = {
  :publishable_key => ENV["public_key"],
  :secret_key      => ENV["private_key"]
}

Stripe.api_key = Rails.configuration.stripe[:secret_key]

puts Rails.configuration.stripe[:publishable_key]
puts Rails.configuration.stripe[:secret_key]
puts Stripe.api_key

Now, I know that up to this point everything is fine because the keys are printed in the console when the server starts.

However, when the action goes to the controller I get a message saying

"No API key provided. Set your API key using "Stripe.api_key = ". You can generate API keys from the Stripe web interface. See https://stripe.com/api for details, or email [email protected] if you have any questions."

The only way I can make it work is by re-setting the stripe API key inside the controller action by

class CheckoutsController < ApplicationController
  
  def show
    Stripe.api_key = Rails.configuration.stripe[:secret_key] #<---Have to re-set the API key

    current_user.set_payment_processor :stripe
    
    @checkout_session = current_user.payment_processor.checkout(
      # mode: "payment",
      # line_items: "price_1KuweRFkaCcck7q2JSu01hHi"
      mode: "subscription",
      line_items: "price_1KuyuVFkaCcck7q23EJLLpra"
      )    
  end  
end

Why doesn't the controller recognize something that was defined in the initializer?



Solution 1:[1]

This is a variable scope issue. The stripe instance used in your controller is different than the one in your initializer. I would follow that video more closely from the beginning and use the same strategy that's used there.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 codename_duchess