Cancelled
Push — master ( 86817a...a519f9 )
by Roy
38s queued 38s
created

assets/js/stripe-apple-pay-single.js (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
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 );
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.00',
55
							type: 'pending'
56
						},
57
						lineItems: [{
58
							label: wc_stripe_apple_pay_single_params.i18n.sub_total,
59
							amount: '1.00',
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 );
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
				}, function( error ) {
93
					var data = {
94
						'nonce': wc_stripe_apple_pay_single_params.stripe_apple_pay_nonce,
95
						'errors': error.message
96
					};
97
98
					$.ajax({
99
						type:    'POST',
100
						data:    data,
101
						url:     wc_stripe_apple_pay_single.getAjaxURL( 'log_apple_pay_errors' )
102
					});
103
				});
104
105
				// If shipping is needed -- get shipping methods.
106
				if ( 'yes' === wc_stripe_apple_pay_single_params.needs_shipping ) {
107
					// After the shipping contact/address has been selected
108
					applePaySession.onshippingcontactselected = function( shipping ) {
109
						$.when( wc_stripe_apple_pay_single.generate_cart() ).then( function() {
110
							var data = {
111
								'nonce': wc_stripe_apple_pay_single_params.stripe_apple_pay_get_shipping_methods_nonce,
112
								'address': shipping.shippingContact
113
							};
114
115
							$.ajax({
116
								type:    'POST',
117
								data:    data,
118
								url:     wc_stripe_apple_pay_single.getAjaxURL( 'apple_pay_get_shipping_methods' ),
119
								success: function( response ) {
120
									var total = { 
121
										'label': wc_stripe_apple_pay_single_params.label,
122
										'amount': response.total
123
									};
124
125
									if ( response.total <= 0 ) {
126
										total.amount = 1;
127
										total.type = 'pending';
128
									}
129
130
									if ( 'true' === response.success ) {
131
										applePaySession.completeShippingContactSelection( ApplePaySession.STATUS_SUCCESS, response.shipping_methods, total, response.line_items );
132
									}
133
134
									if ( 'false' === response.success ) {
135
										applePaySession.completeShippingContactSelection( ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS, response.shipping_methods, total, response.line_items );
136
									}
137
								}
138
							});
139
						});
140
					};
141
142
					// After the shipping method has been selected.
143
					applePaySession.onshippingmethodselected = function( event ) {
144
						var data = {
145
							'nonce': wc_stripe_apple_pay_single_params.stripe_apple_pay_update_shipping_method_nonce,
146
							'selected_shipping_method': event.shippingMethod
147
						};
148
149
						$.ajax({
150
							type:    'POST',
151
							data:    data,
152
							url:     wc_stripe_apple_pay_single.getAjaxURL( 'apple_pay_update_shipping_method' ),
153
							success: function( response ) {
154
								var newTotal = {
155
									'label': wc_stripe_apple_pay_single_params.label,
156
									'amount': parseFloat( response.total ).toFixed(2)
157
								};
158
159
								if ( 'true' === response.success ) {
160
									applePaySession.completeShippingMethodSelection( ApplePaySession.STATUS_SUCCESS, newTotal, response.line_items );
161
								}
162
163
								if ( 'false' === response.success ) {
164
									applePaySession.completeShippingMethodSelection( ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS, newTotal, response.line_items );
165
								}
166
							}
167
						});
168
					};
169
				}
170
171
				// When payment is selected, we need to fetch cart.
172
				applePaySession.onpaymentmethodselected = function( event ) {
173
					$.when( wc_stripe_apple_pay_single.generate_cart() ).then( function() {
174
175
						var total = {
176
								label: wc_stripe_apple_pay_single_params.label,
177
								amount: wc_stripe_apple_pay_single_params.total
178
							},
179
							lineItems = wc_stripe_apple_pay_single_params.line_items;
180
181
						applePaySession.completePaymentMethodSelection( total, lineItems );
182
					});
183
				};
184
185
				applePaySession.oncancel = function( event ) {
186
					wc_stripe_apple_pay_single.clear_cart();
187
				};
188
189
				applePaySession.begin();
190
			});
191
		},
192
193
		get_attributes: function() {
194
			var select = $( '.variations_form' ).find( '.variations select' ),
195
				data   = {},
196
				count  = 0,
197
				chosen = 0;
198
199
			select.each( function() {
200
				var attribute_name = $( this ).data( 'attribute_name' ) || $( this ).attr( 'name' );
201
				var value          = $( this ).val() || '';
202
203
				if ( value.length > 0 ) {
204
					chosen ++;
205
				}
206
207
				count ++;
208
				data[ attribute_name ] = value;
209
			});
210
211
			return {
212
				'count'      : count,
213
				'chosenCount': chosen,
214
				'data'       : data
215
			};			
216
		},
217
218
		generate_cart: function() {
219
			var data = {
220
					'nonce':      wc_stripe_apple_pay_single_params.stripe_apple_pay_cart_nonce,
221
					'qty':        $( '.quantity .qty' ).val(),
222
					'attributes': $( '.variations_form' ).length ? wc_stripe_apple_pay_single.get_attributes().data : []
223
				};
224
225
			return $.ajax({
226
				type:    'POST',
227
				data:    data,
228
				url:     wc_stripe_apple_pay_single.getAjaxURL( 'generate_apple_pay_single' ),
229
				success: function( response ) {
230
					wc_stripe_apple_pay_single_params.total      = response.total;
231
					wc_stripe_apple_pay_single_params.line_items = response.line_items;
232
				}
233
			});
234
		},
235
236
		clear_cart: function() {
237
			var data = {
238
					'nonce': wc_stripe_apple_pay_single_params.stripe_apple_pay_cart_nonce
239
				};
240
241
			return $.ajax({
242
				type:    'POST',
243
				data:    data,
244
				url:     wc_stripe_apple_pay_single.getAjaxURL( 'apple_pay_clear_cart' ),
245
				success: function( response ) {}
246
			});
247
		}
248
	};
249
250
	wc_stripe_apple_pay_single.init();
251
});
252