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

74 lines
2.3 KiB
JavaScript

import {
hidePayButton,
showPayButton,
showCardError,
showCardSuccess,
stripe,
card,
processing,
} from './common.js';
export function val(plan_id, 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;
stripe.createPaymentMethod({
type: 'card',
card: card,
billing_details: {
email: document.getElementById("cardholder-email").value,
},
}).then((result) => {
stripePaymentMethodHandler(result, plan_id, api);
});
}
function stripePaymentMethodHandler(result, plan_id, api) {
if (result.error) {
showCardError(result.error.message);
} else {
// create a customer and subscribe to plan
let payload = {
product_id: document.getElementById("product_id").value,
plan: plan_id,
payment_method: result.paymentMethod.id,
email: document.getElementById("cardholder-email").value,
last_four: result.paymentMethod.card.last4,
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,
};
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");
// set hidden vars
// submit the form
});
}
}