listojs
Version:
a package for restaurant management
80 lines (69 loc) • 2.72 kB
JavaScript
const stripe = Stripe('pk_test_WWbnKC93qOMARiC4lbirfDrg00CuCspHmW');
const elements = stripe.elements();
function checkout(CHECKOUT_SESSION_ID) {
stripe.redirectToCheckout({
// Make the id field from the Checkout Session creation API response
// available to this file, so you can provide it as parameter here
// instead of the {{CHECKOUT_SESSION_ID}} placeholder.
sessionId: CHECKOUT_SESSION_ID
}).then(function (result) {
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer
// using `result.error.message`.
console.log(JSON.stringify(result));
});
}
// Custom styling can be passed to options when creating an Element.
const style = {
base: {
// Add your base input styles here. For example:
fontSize: '16px',
color: "#32325d",
}
};
// Create an instance of the card Element.
const card = elements.create('card', {style});
// Add an instance of the card Element into the `card-element` <div>.
card.mount('#card-element');
card.addEventListener('change', ({error}) => {
const displayError = document.getElementById('card-errors');
if (error) {
let html = "";
for (let obj in error) {
html += "<p>" + error[obj] + "</p>";
}
displayError.innerHTML = html;
} else {
displayError.innerHTML = '';
}
});
// Create a token or display an error when the form is submitted.
const form = document.getElementById('payment-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const {token, error} = await stripe.createToken(card);
if (error) {
// Inform the customer that there was an error.
const errorElement = document.getElementById('card-errors');
errorElement.textContent = error.message;
} else {
// Send the token to your server.
stripeTokenHandler(token);
}
});
const stripeTokenHandler = (token) => {
// Insert the token ID into the form so it gets submitted to the server
const form = document.getElementById('payment-form');
const hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
}
$(document).on('click', '#checkoutLink', function () {
const id = document.getElementById("sessionID").value;
console.log("Checkout clicked: "+id);
checkout(id);
});