[英]How can I disable the Stripe payment request button until a form is complete?
I have Stripe's payment request button set up on the same page as a form.我在与表单相同的页面上设置了 Stripe 的付款请求按钮。 The form has validation on it.表单上有验证。 I need to be able to disable the payment request button until the form has been completed but I haven't been able to find a way to do this.在表格完成之前,我需要能够禁用付款请求按钮,但我一直无法找到执行此操作的方法。
Payment request button set up:付款请求按钮设置:
<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>
You can perform form validation in an event handler for the click
event of the payment request button.您可以在支付请求按钮的click
事件的事件处理程序中执行表单验证。
element.on('click', handler)
Triggered when the
Element
is clicked.单击Element
时触发。 This event is only emitted from apaymentRequestButton
Element.此事件仅从paymentRequestButton
元素发出。
handler
When called it will be passed an event object with the following properties:调用时,它将传递一个具有以下属性的事件对象:
preventDefault
Calling this function synchronously prevents the browser's payment interface from being shown.同步调用此函数可以防止浏览器的支付界面显示出来。 This can be used to validate the form before the payment interface is shown.这可用于在显示支付界面之前验证表单。
prButton.on('click', function(event) {
if (!myForm.reportValidity()) {
event.preventDefault();
return;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.