Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stripe w/ Ruby on Rails ENV variables in Javascript

I am not sure how to place my Publishable key into my JavaScript code. When I place the publishable key's value directly into the JavaScript it works fine. When I try to use Environment variables It does not work.

config/initializers/stripe.rb

Rails.configuration.stripe = {
  :publishable_key => ENV['PUBLISHABLE_KEY'],
  :secret_key      => ENV['SECRET_KEY']
}

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

javascripts/charges.js.erb

Stripe.setPublishableKey(<%= Rails.configuration.stripe[:publishable_key] %>);

var stripeResponseHandler = function(status, response) {
  var $form = $('#payment-form');

  if (response.error) {

        $form.find('.payment-errors').text(response.error.message);
        $form.find('button').prop('disabled', false);
    } else {

        var token = response.id;

        $form.append($('<input type="hidden" name="stripeToken" />').val(token));

        $form.get(0).submit();
    }
};

jQuery(function($) {
    $('#payment-form').submit(function(e) {
      var $form = $(this);


      $form.find('button').prop('disabled', true);

      Stripe.createToken($form, stripeResponseHandler);

      return false;
    });
});
like image 896
TonyTau Avatar asked Nov 10 '13 21:11

TonyTau


People also ask

How do I see environment variables in rails?

Use command ENV in rails console. That will return a hash of your environmental values you can access. Alternatively, you can access your environmental variables from your apps root path using the same command and the variables will be returned formatted.

Where is environment JS in rails?

The config/webpack/environment. js file is where the default webpack configuration is imported via @rails/webpacker . The named import environment is an abstraction around the webpack config. It provides its own API to support modification and extension.

What is ENV fetch?

The fetch() method of the ENV class fetches or finds an environment variable. It takes the environment variable's name and returns the value of this environment variable.


1 Answers

Not exactly a solution but I like the Railscast way (http://railscasts.com/episodes/288-billing-with-stripe) of setting the meta tag with an Environment variable and then using Javascript to call upon the value in the meta tag. The bit you want starts at about 4m10s

<%= tag :meta, :name => "stripe-key", :content => STRIPE_PUBLIC_KEY %>

Then the JS code is:

Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'))

I'm not a fan of inserting environment variables into JS directly.

like image 84
tommyd456 Avatar answered Sep 25 '22 17:09

tommyd456