Stripe.js和Elements-卡错误导致无法随后提交表单

时间:2018-07-13 18:08:24

标签: ruby-on-rails stripe.js

使用stripe documentation提供的代码,在提供了不正确的卡信息或没有提供卡信息之后,提交了表单并进行了修复,然后提交按钮对随后的表单提交无响应。任何帮助将不胜感激。

js:

var stripe = Stripe('pk_test_redacted');
var elements = stripe.elements();

// Custom styling can be passed to options when creating an Element.
var style = {
  base: {
    // Add your base input styles here. For example:
    fontSize: '16px',
    color: "#767171",
    iconColor: "#767171"
  }
};

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

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

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

// Create a token or display an error when the form is submitted.
var form = document.getElementById('shipping_form');
form.addEventListener('submit', function (event) {
  event.preventDefault();

  stripe.createToken(card).then(function (result) {
    if (result.error) {
      // Inform the customer that 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);
    }
  });
});

function stripeTokenHandler(token) {
  // Insert the token ID into the form so it gets submitted to the server
  var form = document.getElementById('shipping_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();
}

HTML / ERB:

<div id="card-element"></div>
<div class="form-entry checkout-submit">
  <%= f.submit "Submit Order", class: "btn-green btn-fill", id: 'cart-submit' %>
</div>
<div id="card-errors" role="alert"></div>

0 个答案:

没有答案