Created
June 17, 2020 13:11
-
-
Save manshu/4a453d43b917a8663acee92123f443e0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var stripe = Stripe( | |
document.head.querySelector('meta[name="stripeKey"]').content | |
); | |
var elements = stripe.elements(); | |
var card = elements.create("card"); | |
card.mount("#card"); | |
card.addEventListener("change", function(event) { | |
var displayError = document.getElementById("cardErrors"); | |
if (event.error) { | |
displayError.textContent = event.error.message; | |
} else { | |
displayError.textContent = ""; | |
} | |
}); | |
const form = document.getElementById('paymentForm'); | |
const payButton = document.getElementById('payButton'); | |
const name = document.getElementById('name'); | |
const paymentIntentInput = document.getElementById('payment_intent'); | |
form.addEventListener('submit', function(event) { | |
event.preventDefault(); | |
payButton.disabled = true | |
createPaymentIntent().then(function(paymentIntent) { | |
paymentIntentInput.value = paymentIntent.id; | |
if (paymentIntent.errors) { | |
showErrors(paymentIntent.errors); | |
} else { | |
errorMessages.innerText = ''; | |
confirmPaymentIntent(paymentIntent).then(function() { | |
submitForm(paymentIntent); | |
}); | |
} | |
}); | |
}); | |
function submitForm(paymentIntent) { | |
payButton.disabled = false | |
form.submit(); | |
} | |
function confirmPaymentIntent(paymentIntent) { | |
return stripe.confirmCardPayment( | |
paymentIntent.clientSecret, { | |
payment_method: { | |
card: card, | |
billing_details: { | |
name: name.value, | |
email: email.value, | |
} | |
}, | |
} | |
); | |
} | |
var errorMessages = document.getElementById('error-messages'); | |
function showErrors(errors) { | |
if (errors.title) { | |
title.classList.add('is-invalid'); | |
titleError.innerText = errors.title.join(" "); | |
} | |
errorMessages.innerText = JSON.stringify(errors, null, 2) | |
} | |
function createPaymentIntent() { | |
return fetch('/create-order', { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
'X-CSRF-TOKEN': document.getElementsByName('_token')[0].value, | |
'X-Requested-With': 'XMLHttpRequest', | |
}, | |
body: JSON.stringify({ | |
name: name.value, | |
email: email.value, | |
slug: "{{ $product->slug }}", | |
}), | |
}) | |
.then((response) => response.json()) | |
.catch((error) => { | |
console.error('Error:', error); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment