67 lines
		
	
	
		
			1.8 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
			
		
		
	
	
			67 lines
		
	
	
		
			1.8 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 = {
 | 
						|
            plan: plan_id,
 | 
						|
            payment_method: result.paymentMethod.id,
 | 
						|
            email: document.getElementById("cardholder-email").value,
 | 
						|
            last_four: result.paymentMethod.card.last4,
 | 
						|
        };
 | 
						|
 | 
						|
        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
 | 
						|
            });
 | 
						|
    }
 | 
						|
}
 |