简体   繁体   English

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

[英]How do you send a Stripe token to a controller from a form in view?

I'm trying to set up a Stripe form where you can add a card as a current user then it will be used to pay for something automatically when it get saved. 我正在尝试建立一个Stripe表单,您可以在其中添加卡作为当前用户,然后在保存时自动用于支付费用。

I'm having some difficulty trying to get stripeToken to be passed to users_controller's add_card method. 我在尝试将stripeToken传递给users_controller的add_card方法时遇到一些困难。 The error message is: 错误消息是:

Stripe::InvalidRequestError (Invalid source object: must be a dictionary or a non-empty string. See API docs at https://stripe.com/docs '): Stripe :: InvalidRequestError(无效的源对象:必须是字典或非空字符串。请参阅https://stripe.com/docs上的API文档):

I tried checking params.inspect in console and got this: 我尝试在控制台中检查params.inspect并得到了:

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

I think the form isn't just sending stripeToken correctly but I'm a noob at Javascript so little bit lost here how to resolve this. 我认为表单不仅可以正确地发送stripeToken,而且我对Java语言也很陌生,所以在这里如何解决这个问题几乎没有。

Here's my code. 这是我的代码。

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

You need to intercept the form submission and send for the Stripe token. 您需要拦截表单提交并发送Stripe令牌。 Then insert the token into the params in a hidden field. 然后将标记插入到隐藏字段中的参数中。 Then submit the form form.submit(); 然后提交表格form.submit();

So target the form submit button and prevent default. 因此,以表单提交按钮为目标并防止默认设置。 e.preventDefault(); . Submit information for the Stripe token. 提交有关Stripe令牌的信息。 Insert token from return into params by targeting a hidden field tag <%= hidden_field_tag 'user[token]', '', id: 'token' %> 通过以隐藏字段标记为目标,将返回标记插入参数中<%= hidden_field_tag 'user[token]', '', id: 'token' %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 您如何从视图将动作从一个控制器/路由器发送到另一控制器/路由器? - How do you send an action from one controller/router to another from a view? 获取条纹令牌后如何在表单中发送其他用户信息-angular - how do I send additional user information in a form after getting stripe token - angular 如何从ng-click或控制器事件而不是表单提交中触发条纹令牌生成? - How can I trigger stripe token generation from an ng-click or controller event instead of a form submission? AngularJS 和 Stripe:将令牌发送到服务器,将令牌插入到表单中 - AngularJS and Stripe: Send token to server, insert the token into the form 如何在MVC框架的控制器中获取Stripe令牌? - How to get Stripe token in the controller of MVC framework? 如何在Codeigniter中将数据从视图发送到控制器 - How to send data from view to controller in codeigniter LARAVEL:如何将数据从视图发送到控制器 - LARAVEL: how to send data from view to controller 在引导程序验证后,无法从视图向控制器发送引导程序表单 - Not able to send bootstrap form from view to controller after bootstrap validations 条带形式不创建令牌 - Stripe form not creating token 如何将选定的数据从模式弹出窗口发送回父表单并关闭模式 - How do you send selected data back from modal popup to parent form and close modal
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM