Completed
Push — master ( 1097c7...2c7ec5 )
by Roy
02:23
created

stripe-apple-pay-single.js ➔ ... ➔ $.then   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 8.8571
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
/* global wc_stripe_apple_pay_single_params, Stripe */
2
Stripe.setPublishableKey( wc_stripe_apple_pay_single_params.key );
3
4
jQuery( function( $ ) {
5
	'use strict';
6
7
	/**
8
	 * Object to handle Stripe payment forms.
9
	 */
10
	var wc_stripe_apple_pay_single = {
11
		/**
12
		 * Get WC AJAX endpoint URL.
13
		 *
14
		 * @param  {String} endpoint Endpoint.
15
		 * @return {String}
16
		 */
17
		getAjaxURL: function( endpoint ) {
18
			return wc_stripe_apple_pay_single_params.ajaxurl
19
				.toString()
20
				.replace( '%%endpoint%%', 'wc_stripe_' + endpoint );
21
		},
22
23
		/**
24
		 * Initialize event handlers and UI state.
25
		 */
26
		init: function() {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
27
			Stripe.applePay.checkAvailability( function( available ) {
28
				if ( available ) {
29
					$( '.apple-pay-button' ).show();
30
				}
31
			});
32
33
			$( document.body ).on( 'click', '.apple-pay-button', function( e ) {
34
				e.preventDefault();
35
36
				var addToCartButton = $( '.single_add_to_cart_button' );
37
38
				// First check if product can be added to cart.
39
				if ( addToCartButton.is( '.disabled' ) ) {
40
					if ( addToCartButton.is( '.wc-variation-is-unavailable' ) ) {
41
						window.alert( wc_add_to_cart_variation_params.i18n_unavailable_text );
0 ignored issues
show
Bug introduced by
The variable wc_add_to_cart_variation_params seems to be never declared. If this is a global, consider adding a /** global: wc_add_to_cart_variation_params */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
42
					} else if ( addToCartButton.is( '.wc-variation-selection-needed' ) ) {
43
						window.alert( wc_add_to_cart_variation_params.i18n_make_a_selection_text );
44
					}
45
46
					return;
47
				}
48
49
				var paymentRequest = {
50
						countryCode: wc_stripe_apple_pay_single_params.country_code,
51
						currencyCode: wc_stripe_apple_pay_single_params.currency_code,
52
						total: {
53
							label: wc_stripe_apple_pay_single_params.label,
54
							amount: 1,
55
							type: 'pending'
56
						},
57
						lineItems: {
58
							label: wc_stripe_apple_pay_single_params.i18n.sub_total,
59
							amount: 1,
60
							type: 'pending'
61
						},
62
						requiredBillingContactFields: ['postalAddress'],
63
						requiredShippingContactFields: 'yes' === wc_stripe_apple_pay_single_params.needs_shipping ? ['postalAddress', 'phone', 'email', 'name'] : ['phone', 'email', 'name']
64
					};
65
66
				var applePaySession = Stripe.applePay.buildSession( paymentRequest, function( result, completion ) {
67
					var data = {
68
						'nonce': wc_stripe_apple_pay_single_params.stripe_apple_pay_nonce,
69
						'result': result
70
					};
71
72
					$.ajax({
73
						type:    'POST',
74
						data:    data,
75
						url:     wc_stripe_apple_pay_single.getAjaxURL( 'apple_pay' ),
76
						success: function( response ) {
77
							if ( 'true' === response.success ) {
78
								completion( ApplePaySession.STATUS_SUCCESS );
0 ignored issues
show
Bug introduced by
The variable ApplePaySession seems to be never declared. If this is a global, consider adding a /** global: ApplePaySession */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
79
								window.location.href = response.redirect;
80
							}
81
82
							if ( 'false' === response.success ) {
83
								completion( ApplePaySession.STATUS_FAILURE );
84
85
								$( '.apple-pay-button' ).before( '<p class="woocommerce-error wc-stripe-apple-pay-error">' + response.msg + '</p>' );
86
87
								// Scroll to error so user can see it.
88
								$( document.body ).animate({ scrollTop: $( '.wc-stripe-apple-pay-error' ).offset().top }, 500 );
89
							}
90
						}
91
					});
92
				});
93
94
				// If shipping is needed -- get shipping methods.
95
				if ( 'yes' === wc_stripe_apple_pay_single_params.needs_shipping ) {
96
					// After the shipping contact/address has been selected
97
					applePaySession.onshippingcontactselected = function( shipping ) {
98
						$.when( wc_stripe_apple_pay_single.generate_cart() ).then( function() {
99
							var data = {
100
								'nonce': wc_stripe_apple_pay_single_params.stripe_apple_pay_get_shipping_methods_nonce,
101
								'address': shipping.shippingContact
102
							};
103
104
							$.ajax({
105
								type:    'POST',
106
								data:    data,
107
								url:     wc_stripe_apple_pay_single.getAjaxURL( 'apple_pay_get_shipping_methods' ),
108
								success: function( response ) {
109
									var total = { 
110
										'label': wc_stripe_apple_pay_single_params.label,
111
										'amount': response.total
112
									};
113
114
									if ( response.total <= 0 ) {
115
										total.amount = 1;
116
										total.type = 'pending';
117
									}
118
119
									if ( 'true' === response.success ) {
120
										applePaySession.completeShippingContactSelection( ApplePaySession.STATUS_SUCCESS, response.shipping_methods, total, response.line_items );
0 ignored issues
show
Bug introduced by
The variable ApplePaySession seems to be never declared. If this is a global, consider adding a /** global: ApplePaySession */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
121
									}
122
123
									if ( 'false' === response.success ) {
124
										applePaySession.completeShippingContactSelection( ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS, response.shipping_methods, total, response.line_items );
125
									}
126
								}
127
							});
128
						});
129
					};
130
131
					// After the shipping method has been selected.
132
					applePaySession.onshippingmethodselected = function( event ) {
133
						var data = {
134
							'nonce': wc_stripe_apple_pay_single_params.stripe_apple_pay_update_shipping_method_nonce,
135
							'selected_shipping_method': event.shippingMethod
136
						};
137
138
						$.ajax({
139
							type:    'POST',
140
							data:    data,
141
							url:     wc_stripe_apple_pay_single.getAjaxURL( 'apple_pay_update_shipping_method' ),
142
							success: function( response ) {
143
								var newTotal = {
144
									'label': wc_stripe_apple_pay_single_params.label,
145
									'amount': parseFloat( response.total ).toFixed(2)
146
								};
147
148
								if ( 'true' === response.success ) {
149
									applePaySession.completeShippingMethodSelection( ApplePaySession.STATUS_SUCCESS, newTotal, response.line_items );
0 ignored issues
show
Bug introduced by
The variable ApplePaySession seems to be never declared. If this is a global, consider adding a /** global: ApplePaySession */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
150
								}
151
152
								if ( 'false' === response.success ) {
153
									applePaySession.completeShippingMethodSelection( ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS, newTotal, response.line_items );
154
								}
155
							}
156
						});
157
					};
158
				}
159
160
				// When payment is selected, we need to fetch cart.
161
				applePaySession.onpaymentmethodselected = function( event ) {
0 ignored issues
show
Unused Code introduced by
The parameter event is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
162
					$.when( wc_stripe_apple_pay_single.generate_cart() ).then( function() {
163
164
						var total = {
165
								label: wc_stripe_apple_pay_single_params.label,
166
								amount: wc_stripe_apple_pay_single_params.total
167
							},
168
							lineItems = wc_stripe_apple_pay_single_params.line_items;
169
170
						applePaySession.completePaymentMethodSelection( total, lineItems );
171
					});
172
				};
173
174
				applePaySession.oncancel = function( event ) {
0 ignored issues
show
Unused Code introduced by
The parameter event is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
175
					wc_stripe_apple_pay_single.clear_cart();
176
				};
177
178
				applePaySession.begin();
179
			});
180
		},
181
182
		get_attributes: function() {
183
			var select = $( '.variations_form' ).find( '.variations select' ),
184
				data   = {},
185
				count  = 0,
186
				chosen = 0;
187
188
			select.each( function() {
189
				var attribute_name = $( this ).data( 'attribute_name' ) || $( this ).attr( 'name' );
190
				var value          = $( this ).val() || '';
191
192
				if ( value.length > 0 ) {
193
					chosen ++;
194
				}
195
196
				count ++;
197
				data[ attribute_name ] = value;
198
			});
199
200
			return {
201
				'count'      : count,
202
				'chosenCount': chosen,
203
				'data'       : data
204
			};			
205
		},
206
207
		generate_cart: function() {
208
			var data = {
209
					'nonce':      wc_stripe_apple_pay_single_params.stripe_apple_pay_cart_nonce,
210
					'qty':        $( '.quantity .qty' ).val(),
211
					'attributes': $( '.variations_form' ).length ? wc_stripe_apple_pay_single.get_attributes().data : []
212
				};
213
214
			return $.ajax({
215
				type:    'POST',
216
				data:    data,
217
				url:     wc_stripe_apple_pay_single.getAjaxURL( 'generate_apple_pay_single' ),
218
				success: function( response ) {
219
					wc_stripe_apple_pay_single_params.total      = response.total;
220
					wc_stripe_apple_pay_single_params.line_items = response.line_items;
221
				}
222
			});
223
		},
224
225
		clear_cart: function() {
226
			var data = {
227
					'nonce': wc_stripe_apple_pay_single_params.stripe_apple_pay_cart_nonce
228
				};
229
230
			return $.ajax({
231
				type:    'POST',
232
				data:    data,
233
				url:     wc_stripe_apple_pay_single.getAjaxURL( 'apple_pay_clear_cart' ),
234
				success: function( response ) {}
0 ignored issues
show
Unused Code introduced by
The parameter response is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
235
			});
236
		}
237
	};
238
239
	wc_stripe_apple_pay_single.init();
240
});
241