Skip to content

Instantly share code, notes, and snippets.

@konami99
Created March 30, 2021 03:37
Show Gist options
  • Save konami99/3eb64c370adcac7e54d443eb6660e741 to your computer and use it in GitHub Desktop.
Save konami99/3eb64c370adcac7e54d443eb6660e741 to your computer and use it in GitHub Desktop.
:javascript
var stripe = Stripe("#{campaign.stripe_publishable_key}");
var elements = stripe.elements();
const form = document.getElementById('new_donation');
var cardNumber = elements.create("cardNumber");
var cardExpiry = elements.create("cardExpiry");
var cardCvc = elements.create("cardCvc");
cardNumber.mount('.card-number');
cardExpiry.mount('.card-expiry');
cardCvc.mount('.card-cvc');
cardValidations([cardNumber, cardExpiry, cardCvc]);
form.addEventListener('submit', event => {
event.preventDefault();
var cardErrors = document.getElementsByClassName('card-errors')[0];
cardErrors.textContent = '';
response = fetch("#{stripe_create_intent_url}", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
amount: $('#donation_amount').val(),
has_cover_fee: $('#donation_cover_fees').is(':checked'),
authenticity_token: "#{form_authenticity_token}"
})
})
.then(response => response.json())
.then(data => {
stripe.confirmCardPayment(data.stripe_client_secret, {
payment_method: {
card: cardNumber,
billing_details: {
name: $("#donation_donor_attributes_first_name").val() + ' ' + $("#donation_donor_attributes_last_name").val(),
email: $("#donation_donor_attributes_email").val(),
phone: $("#donation_donor_attributes_phone_number").val(),
address: {
city: $("#donation_donor_attributes_city").val(),
line1: $("#donation_donor_attributes_address1").val(),
line2: $("#donation_donor_attributes_address2").val(),
state: $("#donation_donor_attributes_state").val(),
}
}
}
}).then(function(result) {
if (result.error) {
$('.donation-submit button[type=submit]').first().removeAttr('disabled');
$(event.submitter).find('.spinner-border').toggleClass('d-none');
$(event.submitter).find('.submit-text').toggleClass('d-none');
$("body,html").animate(
{
scrollTop: $("#credit_card").offset().top - 200
},
800
);
cardErrors.textContent = result.error.message;
} else {
if (result.paymentIntent.status === 'requires_capture') {
document.getElementById('stripe_client_secret').value = result.paymentIntent.id;
form.submit();
}
}
});
});
});
function cardValidations(elements) {
elements.forEach(function(element, idx) {
element.on('change', function(event) {
var displayError = document.getElementsByClassName('card-errors')[0];
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment