Stripe w / Ruby on Rails ENV variables in Javascript

I am not sure how to put my published key in my JavaScript code. When I put the published key value directly in JavaScript, it works fine. When I try to use environment variables, this does not work.

configurations / 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;
    });
});
+4
source share
3 answers

, Railscast (http://railscasts.com/episodes/288-billing-with-stripe) , Javascript . , , 4 10

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

JS:

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

JS .

+3

, , . , ?

PUBLISHABLE_KEY = pk _ #### _ ################ SECRET_KEY = sk _ #### _ ############### ## rails s

0

, Stripe Javascript , , gon JS:

#app/controllers/your_controller.rb
gon.push({
  :user_id => 1,
  :user_role => "admin"
})

#app/assets/javascripts/your_javascript.js
gon.variable_name

:

<head>
  <title>some title</title>
  <%= include_gon %>
  <!-- include your action js code -->
  ...

To load ENV variables even during development, I would use a gem calledFigaro , which basically allows you to load ENV variables in any state

#app/config/application.yml
YOUR_ENV_VAR: 'information'
0
source

All Articles