udemy-go-web-2/static/js/stripe.js

80 lines
2.7 KiB
JavaScript
Raw Normal View History

2024-08-11 20:51:34 +00:00
import {
hidePayButton,
showPayButton,
showCardError,
showCardSuccess,
stripe,
card,
processing,
} from './common.js';
2024-08-11 20:51:34 +00:00
export function val(api) {
let form = document.getElementById("charge_form");
if (form.checkValidity() === false) {
this.event.preventDefault();
this.event.stopPropagation();
form.classList.add("was-validated");
return;
}
form.classList.add("was-validated");
hidePayButton();
let amountToCharge = document.getElementById("amount").value;
console.log(amountToCharge);
let payload = {
amount: amountToCharge,
currency: 'eur',
};
const requestOptions = {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
};
fetch(api + "/api/payment-intent", requestOptions)
2024-08-11 20:51:34 +00:00
.then(response => response.text())
.then(response => {
let data;
try {
data = JSON.parse(response);
stripe.confirmCardPayment(data.client_secret, {
payment_method: {
card: card,
billing_details: {
name: document.getElementById("cardholder-name").value,
}
}
2024-08-11 20:51:34 +00:00
}).then(function (result) {
if (result.error) {
// card declined, or sth went wrong with the card
showCardError(result.error.message);
showPayButton();
} else if (result.paymentIntent) {
if (result.paymentIntent.status === "succeeded") {
// we have charged the card
document.getElementById("payment_intent").value = result.paymentIntent.id;
document.getElementById("payment_method").value = result.paymentIntent.payment_method;
document.getElementById("payment_amount").value = result.paymentIntent.amount;
document.getElementById("payment_currency").value = result.paymentIntent.currency;
processing.classList.add("d-none");
showCardSuccess();
document.getElementById("charge_form").submit();
}
2024-08-11 20:51:34 +00:00
}
})
console.log(data);
} catch (err) {
console.log(err);
showCardError("Invalid response from payment gateway!");
showPayButton();
}
});
}