简体   繁体   中英

Cannot verify CSRF token for Stripe Payments [Rails 4]

I'm currently using the default Stripe Form that is given to you on their website. Everything else seems to work outside of processing a proper authorization token for users when making transactions. I will post below the code for all methods and the form as well.

users_controller.rb

  def info
    @subscription = current_user.subscription
  end

  def charge
    token = params["stripeToken"]
    customer = Stripe::Customer.create(
      source: token,
      plan: 'gbsubscriptionlevel1',
      email: current_user.email
    )

    current_user.subscription.stripe_user_id = customer.id
    current_user.subscription.active = true
    current_user.subscription.save

    redirect_to users_info_path
  end

routes.rb

get '/users/info', to: 'users#info'
post '/users/charge', to: 'users#charge'

_stripe_form.html.erb

<div class="container">
  <form action="/users/charge" method="POST" id="payment-form">
    <span class="payment-errors"></span>

    <div class="row">
      <div class="col-xs-4">
        <label>
          <span>Card Number</span>
          <input class="form-control" type="text" size="20" data-stripe="number"/>
        </label>
      </div>
    </div>

    <div class="row">
      <div class="col-xs-1">
        <label>
          <span>CVC</span>
          <input class="form-control" type="text" size="4" data-stripe="cvc"/>
        </label>
      </div>
    </div>

    <div class="row">
      <div class="col-xs-1">
        <label>MM</label>
        <input class="form-control" type="text" size="2" data-stripe="exp-month" placeholder="01"/>
      </div>
      <div class="col-xs-1">
        <label>YYYY</label>
        <input class="form-control" type="text" size="3" data-stripe="exp-year" placeholder="2020"/>
      </div>
    </div>

    <div class="row">
      <div class="col-xs-1">
        <br/>
        <button class="btn btn-primary-outline" type="submit">Create Subscription</button>
      </div>
    </div>
  </form>

  <script type="text/javascript" src="https://js.stripe.com/v2/"></script>


  <script type="text/javascript">
    // This identifies your website in the createToken call below
    Stripe.setPublishableKey('pk_test_tmBNNUvHTmtWXLhSL1q647iH');
    //
    function stripeResponseHandler(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 {
        // response contains id and card, which contains additional card details
        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 submit
        $form.get(0).submit();
      }
    }

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

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

        Stripe.card.createToken($form, stripeResponseHandler);

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

Stacktrace output

Started POST "/users/charge" for 127.0.0.1 at 2016-02-10 12:11:07 -0500
Processing by UsersController#charge as HTML
Can't verify CSRF token authenticity
Completed 422 Unprocessable Entity in 0ms (ActiveRecord: 0.0ms)

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
  actionpack (4.2.3) lib/action_controller/metal/request_forgery_protection.rb:181:in `handle_unverified_request'
  actionpack (4.2.3) lib/action_controller/metal/request_forgery_protection.rb:209:in `handle_unverified_request'
  devise (3.5.6) lib/devise/controllers/helpers.rb:257:in `handle_unverified_request'
  actionpack (4.2.3) lib/action_controller/metal/request_forgery_protection.rb:204:in `verify_authenticity_token'

This might not be the best solution but you can ignore the error with

protect_from_forgery with: :null_session

placed in your controller.

The better solution would be to build the form using the rails form helper.

Essentially form_tag's do not automatically generate CSRF tokens, unless explicitly told to do so, however neither do form_for tag's, as they chopped that in Rails 4 .

I resolved the issue by adding a hidden input in my forms.

<input type="hidden" value="<%= form_authenticity_token() %>"name="authenticity_token"/>

Here's an example:

<%= form_tag("/payments/create", remote: true) do %>
   <%= render partial: "shared/stripe_checkout_button" %>
   <%= hidden_field_tag(:product_id, @product.id) %>
   <input type="hidden" value="<%= form_authenticity_token() %>"name="authenticity_token"/>
<% end %>

The main reason they chopped automatic generation of CSRF tokens has to do with people fragment-caching because the authenticity token would be wrong on subsequent requests when the form was pulled from the cache.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM