-
Notifications
You must be signed in to change notification settings - Fork 67
/
wc-payment-checkout.js
78 lines (65 loc) · 2.45 KB
/
wc-payment-checkout.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/* global jQuery, Stripe, wc_payment_config */
jQuery( function( $ ) {
'use strict';
var stripe = new Stripe( wc_payment_config.publishableKey, {
stripeAccount: wc_payment_config.accountId,
} );
var elements = stripe.elements();
// Create a card element.
var cardElement = elements.create( 'card', {
hidePostalCode: true,
classes: { base: 'wc-payment-card-mounted' },
} );
// Only attempt to mount the card element once that section of the page has loaded. We can use the updated_checkout
// event for this. This part of the page can also reload based on changes to checkout details, so we call unmount
// first to ensure the card element is re-mounted correctly.
$( document.body ).on( 'updated_checkout', function() {
// Don't re-mount if already mounted in DOM.
if ( $( '#wc-payment-card-element' ).children().length ) {
return;
}
cardElement.unmount();
cardElement.mount( '#wc-payment-card-element' );
} );
// Update the validation state based on the element's state.
cardElement.addEventListener( 'change', function( event ) {
var displayError = jQuery( '#wc-payment-errors' );
if ( event.error ) {
displayError.html( '<ul class="woocommerce-error"><li /></ul>' )
.find( 'li' ).text( event.error.message );
} else {
displayError.empty();
}
} );
// Create payment method on submission.
var paymentMethodGenerated;
$( 'form.checkout' ).on( 'checkout_place_order_woocommerce_payments', function() {
// We'll resubmit the form after populating our payment method, so if this is the second time this event
// is firing we should let the form submission happen.
if ( paymentMethodGenerated ) {
return;
}
stripe.createPaymentMethod( 'card', cardElement )
.then( function( result ) {
var paymentMethod = result.paymentMethod;
var error = result.error;
if ( error ) {
throw error;
}
return paymentMethod;
} )
.then( function( paymentMethod ) {
var id = paymentMethod.id;
// Flag that the payment method has been successfully generated so that we can allow the form
// submission next time.
paymentMethodGenerated = true;
// Populate form with the payment method.
var paymentMethodInput = document.getElementById( 'wc-payment-method' );
paymentMethodInput.value = id;
// Re-submit the form.
$( '.woocommerce-checkout' ).submit();
} );
// Prevent form submission so that we can fire it once a payment method has been generated.
return false;
} );
} );