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

78 lines
2.6 KiB
JavaScript
Raw Normal View History

2024-08-11 20:58:06 +00:00
import {
hidePayButton,
showPayButton,
2024-08-13 20:46:26 +00:00
showError,
showSuccess,
2024-08-11 20:58:06 +00:00
stripe,
card,
processing,
} from './common.js';
2024-08-12 11:31:16 +00:00
export function val(plan_id, api) {
2024-08-11 20:58:06 +00:00
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();
2024-08-12 11:31:16 +00:00
// let amountToCharge = document.getElementById("amount").value;
2024-08-11 20:58:06 +00:00
stripe.createPaymentMethod({
type: 'card',
card: card,
billing_details: {
email: document.getElementById("cardholder-email").value,
},
2024-08-12 11:31:16 +00:00
}).then((result) => {
stripePaymentMethodHandler(result, plan_id, api);
});
2024-08-11 20:58:06 +00:00
}
2024-08-12 11:31:16 +00:00
function stripePaymentMethodHandler(result, plan_id, api) {
2024-08-11 20:58:06 +00:00
if (result.error) {
2024-08-13 20:46:26 +00:00
showError("card-messages", result.error.message);
2024-08-11 20:58:06 +00:00
} else {
// create a customer and subscribe to plan
2024-08-12 11:31:16 +00:00
let payload = {
2024-08-12 17:10:27 +00:00
product_id: document.getElementById("product_id").value,
2024-08-12 11:31:16 +00:00
plan: plan_id,
payment_method: result.paymentMethod.id,
email: document.getElementById("cardholder-email").value,
last_four: result.paymentMethod.card.last4,
2024-08-12 17:10:27 +00:00
card_brand: result.paymentMethod.card.brand,
expiry_month: result.paymentMethod.card.exp_month,
expiry_year: result.paymentMethod.card.exp_year,
first_name: document.getElementById("first-name").value,
last_name: document.getElementById("last-name").value,
amount: document.getElementById("amount").value,
2024-08-12 11:31:16 +00:00
};
const requestOptions = {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
};
fetch(api + "/api/create-customer-and-subscribe-to-plan", requestOptions)
.then(response => response.json())
.then(function (data) {
console.log(data);
processing.classList.add("d-none");
2024-08-13 20:46:26 +00:00
showSuccess("card-messages", "Transaction successful!");
2024-08-12 17:23:44 +00:00
sessionStorage.first_name = document.getElementById("first-name").value;
sessionStorage.last_name = document.getElementById("last-name").value;
sessionStorage.amount = document.getElementById("amount").value;
sessionStorage.last_four = result.paymentMethod.card.last4;
location.href = "/receipt/bronze";
2024-08-12 11:31:16 +00:00
});
2024-08-11 20:58:06 +00:00
}
}