对如何正确使用密钥感到困惑

时间:2015-09-03 20:58:54

标签: ruby-on-rails environment-variables stripe-payments

因此,在我寻求集成Stripe的过程中,我发现自己对如何正确使用密钥和环境变量感到困惑。根据我的理解,我不想在任何公共场所明确地包含我的密钥,而应该使用环境变量。但是当我用ENV代替实际的硬编码密钥时它似乎不起作用。我做错了什么,但是什么?这就是我所拥有的。在我的secret.yml文件中:

development:
  secret_key_base: xxxxxxxxxxxxxxx

  secret_key: sk_test_JlKC4V7nmCQ0sE4iNAVyoAxA
  publishable_key: pk_test_KfCg1YmVXwBYyEdPEWnfibF8

  stripe_live_publishable_key: pk_live_pxxxxxxxxxxxxxx
  stripe_live_secret_key: sk_live_jxxxxxxxxxxxxx

test:
  secret_key_base: a38exxxxxxxxxxxxxxxx

# Do not keep production secrets in the repository,
# instead read values from the environment.
production:
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
#test
  secret_key: <%= ENV["SECRET_KEY"] %>
  publishable_key: <%= ENV["PUBLISHABLE_KEY"] %>
# live
  stripe_live_publishable_key: <%= ENV["STRIPE_LIVE_PRODUCTION_KEY"] %>
  stripe_live_secret_key: <%= ENV["STRIPE_LIVE_SECRET_KEY"] %>

和/initialize/stripe.rb我有:

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

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

在我的付款表格中,我有以下内容: Stripe.setPublishableKey('<%= 'sk_test_JlKC4V7nmCQ0sE4iNAVyoAxA'%>');

它的工作方式是这样的,但除非我误解,否则是不安全的(好吧,现在它只是一个测试键,但是当我使用实时密钥进行生产时我需要知道这一点)。然而,当我尝试使用:

Stripe.setPublishableKey('<%= ENV['PUBLISHABLE_KEY'] %>');

我收到错误: Uncaught Error: You did not set a valid publishable key. Call Stripe.setPublishableKey() with your publishable key.

或当我尝试:

Stripe.setPublishableKey('<%= :publishable_key %>');

我在控制台中收到错误401 (Unauthorized)

我怎么认为你在使用ENV [KEY]这样我就不需要在明显的时候写出我的钥匙了?

更新 这是我的表格,其中密钥最​​公开:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
  <title>Contribution Form</title>

  <!-- The required Stripe lib -->
  <script type="text/javascript" src="https://js.stripe.com/v2/"></script>

  <!-- jQuery is used only for this example; it isn't required to use Stripe -->
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

  <script type="text/javascript">
    // This identifies your website in the createToken call below
    Stripe.setPublishableKey('STRIPE_TEST_PUBLISHABLE_KEY'); //<====How should this line look?

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

      if (response.error) {
        // Show the errors on the form
        $form.find('.payment-errors').text(response.error.message);
        $form.find('button').prop('disabled', false);
      } else {
        // token contains id, last4, and card type
        var token = response.id;
        // Insert the token into the form so it gets submitted to the server
        $form.append($('<input type="hidden" name="stripeToken" />').val(token));
        // and re-submit
        $form.get(0).submit();
      }
    };

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

        // Disable the submit button to prevent repeated clicks
        $form.find('button').prop('disabled', true);

        Stripe.card.createToken({
            number: $('.card-number').val(),
            cvc: $('.card-cvc').val(),
            exp_month: $('.card-expiry-month').val(),
            exp_year: $('.card-expiry-year').val()}, stripeResponseHandler);

        // Prevent the form from submitting with the default action
        return false;
      });
    });
  </script>
</head>
<body>

<!--  form -->
<div class="container">
    <div class="row Row one">
        <div class="col-sm-12 col-md-10">
        <h1>Make your contribution</h1>
           <%= form_for @project, url: project_charges_path, :html => {:id => "payment-form"}, method: 'post' do |f| %>

                <%= f.hidden_field :user_id, :value => current_user.id %>
                <%= f.hidden_field :@project_id, :value => @project.id %>


                <div class= "field">
                  <%= label_tag :card_number, "Credit Card Number" %><br>
                  <%= text_field_tag :card_number, nil, name: nil, class: ' card-number form-control', :required => true %><br>
                </div>

                <div class= "field">
                  <%= label_tag :card_code, "Security Code (cvc)" %><br>
                  <%= text_field_tag :card_code, nil, name: nil, class: 'card-cvc form-control', :required => true %><br>
                </div>

                <div class= "field">
                  <%= label_tag :card_month, "Expiration" %>
                  <%= select_month nil, {add_month_numbers: true}, {name: nil, class: "card-expiry-month"} %>
                  <%= select_year nil, {start_year: Date.today.year, end_year: Date.today.year+15}, {name: nil, class: "card-expiry-year"}%>
                </div>


                <div class= "field">
                    <%= label_tag :amount, "Amount" %><br>
                    <%= text_field_tag :amount %> 
                </div> 

                <div class= "field">
                    <%= label_tag :comments, "Add a comment?" %><br>
                    <%= text_area_tag :comments %> 
                </div>                 

                <div class= "actions">
                  <%= f.submit 'Submit', :class => 'contribution-submit' %>
                </div>

          <div id="stripe_error">
              <noscript>JavaScript is not enabled and is required for this form. First enable it in your web browser settings.</noscript>
          </div>

          <% end %> 
        </div>
    </div>
    <!-- <div class="row"></div> -->
</div>


</body>
</html>

2 个答案:

答案 0 :(得分:4)

生产中的环境变量更多地与应用程序服务器有关,而不是与rails应用程序有关。对我来说,看起来你所做的一切似乎都是正确的,只需要在生产模式中设置变量。

对于Heroku:

heroku config:set STRIPE_PERISHABLE_KEY=<your key here>
heroku config:set STRIPE_SECRET_KEY=<your key here>

对于Passenger(nginx或apache):

在带乘客的服务器/网站定义中,您可以添加乘客环境变量。

passenger_env_var STRIPE_PERISHABLE_KEY '<your key here>';
passenger_env_var STRIPE_SECRET_KEY '<your key here>';

*请注意,对于Apache,您在键和值之间使用=符号,并且值周围没有引号。

答案 1 :(得分:0)

ENV变量通过终端设置。这不是'最佳实践',但我将我的密钥设置在.bash_profile中。还有一些宝石可以为您管理您的环境。

这是一个实现yaml的流行的:

https://github.com/laserlemon/figaro

以下是向.bash_profile

添加密钥的示例
## Work Keys
export STRIPE_KEY="pk_test_somekey"
export STRIPE_SECRET="sk_test_somekey"

然后在ruby中你可以像这样访问变量:

ENV["STRIPE_KEY"]
ENV["STRIPE_SECRET"]

通过创建新的终端实例,您需要在完成此操作后刷新环境。所以退出终端并重新启动服务器!