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;
});
});
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With