I have integrated Stripe payment in my ASP.NET MVC app. The checkout button works on desktop and redirects user to Stripe checkout page, but the button doesn't do anything on mobile. I tried Edge and Chrome on iOS and both are not working.
This is my JavaScript in razor page (Cart.cshtml)
<div>
@using (Html.BeginForm("", "Cart", FormMethod.Post))
{
<input type="submit" id="stripe-checkout-button" value="Stripe" />
}
</div>
<script type="text/javascript">
var stripe = Stripe('MyStripePublishKey');
var checkoutButton = document.getElementById('stripe-checkout-button');
checkoutButton.addEventListener('click', function () {
fetch('https://mywebsite.com/Cart/Checkout_Stripe', {
method: 'POST'
})
.then(function(response) {
return response.json();
})
.then(function (session) {
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function(result) {
if (result.error) {
alert(result.error.message);
}
})
.catch(function (error) {
window.location.href = "/Cart/GatewayRedirectFailed";
console.error('Error:', error);
});
});
</script>
The button does submit the form and there is no error. Also I have to mention, the client-side validation happens, because I have a agreement checkbox which is tagged as "required", and there is a pop-over for that checkbox, pressing the button only triggers that validation.
After getting help from Stripe support, they found I can make it work by updating my JavaScript as below:
<script type="text/javascript">
var stripe = Stripe('MyStripePublishKey');
var checkoutButton = document.getElementById('stripe-checkout-button');
checkoutButton.addEventListener('click', function (event) { -- adding event parameter
event.preventDefault(); <<-- this is the key to make it work!
fetch('https://mywebsite.com/Cart/Checkout_Stripe', {
method: 'POST'
})
.then(function(response) {
return response.json();
})
.then(function (session) {
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function(result) {
if (result.error) {
alert(result.error.message);
}
})
.catch(function (error) {
window.location.href = "/Cart/GatewayRedirectFailed";
console.error('Error:', error);
});
});
</script>
Because my form does not have any action
, looks like in iPhone browser it's not working.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.