如何从视图中的窗体将Stripe令牌发送到控制器?

时间:2019-04-04 03:54:01

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

我正在尝试建立一个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,而且我对Java语言也很陌生,所以在这里解决该问题的方法很少。

这是我的代码。

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>

1 个答案:

答案 0 :(得分:1)

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

因此,以表单提交按钮为目标并防止默认设置。 e.preventDefault();。 提交有关Stripe令牌的信息。 通过隐藏字段标记<%= hidden_field_tag 'user[token]', '', id: 'token' %>

将返回的令牌插入到参数中