首页 > 解决方案 > 如何将 Stripe 令牌从视图中的表单发送到控制器?

问题描述

我正在尝试设置一个 Stripe 表单,您可以在其中添加一张卡作为当前用户,然后它将用于在保存时自动支付某些东西。

我在尝试将 stripeToken 传递给 users_controller 的 add_card 方法时遇到了一些困难。错误信息是:

Stripe::InvalidRequestError(无效的源对象:必须是字典或非空字符串。请参阅 https://stripe.com/docs上的 API 文档):

我尝试在控制台中检查 params.inspect 并得到了这个:

Processing by UsersController#add_card as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"P6wj9wnt+lDPcGPIypewIBVVzXG56WFV4y1xcGBLFwHmznxoO++lmroUEL8hOIX5Wio5N+B8kXkzj0noOgsO/w=="} 

我认为表单不仅仅是正确发送 stripeToken,而且我是 Javascript 的菜鸟,所以在这里有点迷失如何解决这个问题。

这是我的代码。

用户控制器.rb

  def add_card
if current_user.stripe_uid.blank?
  customer = Stripe::Customer.create(
    email: current_user.email
  )
  current_user.stripe_uid = customer.id
  current_user.save

      # Add Credit Card to Stripe
      customer.sources.create(source: params[:stripeToken])
      customer.save
    else
      customer = Stripe::Customer.retrieve(current_user.stripe_uid)
      customer.source = params[:stripeToken]
      customer.save
    end



   flash[:notice] = "Your card is saved."
    redirect_to payment_method_path
  rescue Stripe::CardError => e
    flash[:alert] = e.message
    redirect_to payment_method_path
  end

付款.html.erb:

<%= form_tag("/add_card", method: "post", id: "add-card") do %>
  <%= hidden_field_tag :authenticity_token, form_authenticity_token -%>
<script src="https://js.stripe.com/v3/"></script>
  <div class="form-row">
    <label for="card-element">
      <!-- A Stripe Element will be inserted here. -->
      Credit or debit card
      <div id="card-element"></div
    </label>

    <!-- Used to display form errors. -->
    <div id="card-errors" role="alert"></div>
  </div>

  <button>Add Card</button>
<% end %>
<script>
// Create a Stripe client.
var stripe = Stripe('<%= Rails.configuration.stripe{:publishable_key} %>');

// Create an instance of Elements.
var elements = stripe.elements();

// Custom styling can be passed to options when creating an Element.
// (Note that this demo uses a wider set of styles than the guide below.)
var style = {
  base: {
    color: '#32325d',
    fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
    fontSmoothing: 'antialiased',
    fontSize: '16px',
    '::placeholder': {
      color: '#aab7c4'
    }
  },
  invalid: {
    color: '#fa755a',
    iconColor: '#fa755a'
  }
};

// Create an instance of the card Element.
var card = elements.create('card', {style: style});

// Add an instance of the card Element into the `card-element` <div>.
card.mount('#card-element');

// Handle real-time validation errors from the card Element.
card.addEventListener('change', function(event) {
  var displayError = document.getElementById('card-errors');
  if (event.error) {
    displayError.textContent = event.error.message;
  } else {
    displayError.textContent = '';
  }
});

// Handle form submission.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
  event.preventDefault();

  stripe.createToken(card).then(function(result) {
    if (result.error) {
      // Inform the user if there was an error.
      var errorElement = document.getElementById('card-errors');
      errorElement.textContent = result.error.message;
    } else {
      // Send the token to your server.
      stripeTokenHandler(result.token);
    }
  });
});

// Submit the form with the token ID.
function stripeTokenHandler(token) {
  // Insert the token ID into the form so it gets submitted to the server
  var form = document.getElementById('add_card-form');
  var hiddenInput = document.createElement('input');
  hiddenInput.setAttribute('type', 'hidden');
  hiddenInput.setAttribute('name', 'stripeToken');
  hiddenInput.setAttribute('value', token.id);
  form.appendChild(hiddenInput);

  // Submit the form
  form.submit();
}
</script>

标签: javascriptruby-on-railsstripe-payments

解决方案


您需要拦截表单提交并发送 Stripe 令牌。然后将令牌插入隐藏字段中的参数中。然后提交表格 form.submit();

所以定位表单提交按钮并防止默认。e.preventDefault();. 提交 Stripe 令牌的信息。通过定位隐藏字段标签将返回的令牌插入参数<%= hidden_field_tag 'user[token]', '', id: 'token' %>


推荐阅读