【问题标题】:How do you send a Stripe token to a controller from a form in view?如何将 Stripe 令牌从视图中的表单发送到控制器?
【发布时间】:2019-08-25 17:11:01
【问题描述】:

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

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

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

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

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

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

这是我的代码。

user_controller.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

payment.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>

【问题讨论】:

    标签: javascript ruby-on-rails stripe-payments


    【解决方案1】:

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

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

    【讨论】:

    • 我没有使用 iban,那是用于银行帐户的。这是信用卡,对不起,应该在帖子中澄清这一点。不确定我是否了解如何拦截表单提交,您知道您可以参考我的任何文档吗?
    • 这个概念应该仍然适用。从条带返回的令牌,您需要应用于隐藏字段标签并插入到参数中。我只使用 iban 作为参考,因为那是我的实现。它很容易成为id: 'cc-token'
    猜你喜欢
    • 2016-12-03
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 2016-03-21
    相关资源
    最近更新 更多