如何在表格完成之前禁用 Stripe 付款请求按钮?

tay*_*tay 6 javascript stripe-payments

我在与表单相同的页面上设置了 Stripe 的付款请求按钮。表单上有验证。我需要能够在表格完成之前禁用付款请求按钮,但我无法找到执行此操作的方法。

付款请求按钮设置:

<script src="https://js.stripe.com/v3/"></script>
<div id="payment-request-button">
  <!-- A Stripe Element will be inserted here. -->
</div>
<script>
var stripe = Stripe('KEY');
var paymentRequest = stripe.paymentRequest({
  country: 'US',
  currency: 'usd',
  total: {
    label: 'Demo total',
    amount: 1000,
  },
  requestPayerName: true,
  requestPayerEmail: true,
});

var elements = stripe.elements();
var prButton = elements.create('paymentRequestButton', {
  paymentRequest: paymentRequest,
});

// Check the availability of the Payment Request API first.
paymentRequest.canMakePayment().then(function(result) {
  if (result) {
     prButton.mount('#payment-request-button');
   } else {
     document.getElementById('payment-request-button').style.display = 
 'none';
   }
 });

 paymentRequest.on('token', function(ev) {
   // Send the token to your server to charge it!
   fetch('/charges', {
     method: 'POST',
     body: JSON.stringify({token: ev.token.id}),
     headers: {'content-type': 'application/json'},
  })
  .then(function(response) {
    if (response.ok) {
      // Report to the browser that the payment was successful, prompting
      // it to close the browser payment interface.
      ev.complete('success');
    } else {
      // Report to the browser that the payment failed, prompting it to
      // re-show the payment interface, or show an error message and close
      // the payment interface.
      ev.complete('fail');
    }
  });
});
</script>
Run Code Online (Sandbox Code Playgroud)

fum*_*007 7

您可以在事件处理程序中为click付款请求按钮的事件执行表单验证。

文档

element.on('click', handler)

Element单击时触发。此事件仅从paymentRequestButtonElement发出。

handler

调用时,它将传递一个具有以下属性的事件对象:

preventDefault

同步调用该函数可以防止浏览器的支付界面显示。这可用于在显示支付界面之前验证表单。

例子

prButton.on('click', function(event) {
  if (!myForm.reportValidity()) {
    event.preventDefault();
    return;
  }
});
Run Code Online (Sandbox Code Playgroud)