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

106 lines
3.3 KiB
JavaScript
Raw Normal View History

2024-08-20 12:13:35 +00:00
import {
hidePayButton,
showPayButton,
showError,
showSuccess,
stripe,
card,
processing,
} from './common.js';
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)
.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,
}
}
}).then(function (result) {
if (result.error) {
// card declined, or sth went wrong with the card
showError("card-messages", result.error.message);
showPayButton();
} else if (result.paymentIntent) {
if (result.paymentIntent.status === "succeeded") {
saveTransaction(api, result);
}
}
})
console.log(data);
} catch (err) {
console.log(err);
showCardError("Invalid response from payment gateway!");
showPayButton();
}
});
}
function saveTransaction(api, result) {
let payload = {
amount: parseInt(document.getElementById("amount").value, 10),
currency: result.paymentIntent.currency,
first_name: "",
last_name: "",
email: document.getElementById("cardholder-email").value,
payment_intent: result.paymentIntent.id,
payment_method: result.paymentIntent.payment_method,
};
let token = localStorage.getItem("token");
const requestOptions = {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token,
},
body: JSON.stringify(payload),
};
fetch(api + "/api/admin/virtual-terminal-succeeded", requestOptions)
.then(response => response.json())
.then(function (data) {
console.log(data);
processing.classList.add("d-none");
showSuccess("card-messages", "Trasaction successful!");
document.getElementById("bank-return-code").innerHTML = data.bank_return_code;
document.getElementById("receipt").classList.remove("d-none");
})
}