首页 > 解决方案 > 如何在表单完成之前禁用 Stripe 付款请求按钮?

问题描述

我在与表单相同的页面上设置了 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>

标签: javascriptstripe-payments

解决方案


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

文档

element.on('click', handler)

单击时触发Element。此事件仅从paymentRequestButton元素发出。

handler

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

preventDefault

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

例子

prButton.on('click', function(event) {
  if (!myForm.reportValidity()) {
    event.preventDefault();
    return;
  }
});

推荐阅读