Completed
Push — master ( 467edf...65f5ac )
by Roy
03:10
created

stripe.js ➔ ... ➔ wc_stripe_form.getOwnerDetails   D

Complexity

Conditions 9
Paths 24

Size

Total Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
c 0
b 0
f 0
nc 24
dl 0
loc 44
rs 4.909
nop 0
1
/* global wc_stripe_params */
2
3
jQuery( function( $ ) {
4
	'use strict';
5
6
	var stripe = Stripe( wc_stripe_params.key );
7
8
	if ( 'yes' === wc_stripe_params.use_elements ) {
9
		var elements = stripe.elements(),
10
			stripe_card,
11
			stripe_exp,
12
			stripe_cvc;
13
	}
14
15
	/**
16
	 * Object to handle Stripe elements payment form.
17
	 */
18
	var wc_stripe_form = {
19
		/**
20
		 * Get WC AJAX endpoint URL.
21
		 *
22
		 * @param  {String} endpoint Endpoint.
23
		 * @return {String}
24
		 */
25
		getAjaxURL: function( endpoint ) {
26
			return wc_stripe_params.ajaxurl
27
				.toString()
28
				.replace( '%%endpoint%%', 'wc_stripe_' + endpoint );
29
		},
30
31
		/**
32
		 * Initialize event handlers and UI state.
33
		 */
34
		init: function() {
35
			// Initialize tokenization script if on change payment method page and pay for order page.
36
			if ( 'yes' === wc_stripe_params.is_change_payment_page ) {
37
				$( document.body ).trigger( 'wc-credit-card-form-init' );
38
			}
39
40
			// Stripe Checkout.
41
			this.stripe_checkout_submit = false;
42
43
			// checkout page
44
			if ( $( 'form.woocommerce-checkout' ).length ) {
45
				this.form = $( 'form.woocommerce-checkout' );
46
			}
47
48
			$( 'form.woocommerce-checkout' )
49
				.on(
50
					'checkout_place_order_stripe checkout_place_order_stripe_bancontact checkout_place_order_stripe_sofort checkout_place_order_stripe_giropay checkout_place_order_stripe_ideal checkout_place_order_stripe_alipay checkout_place_order_stripe_sepa checkout_place_order_stripe_bitcoin',
51
					this.onSubmit
52
				);
53
54
			// pay order page
55
			if ( $( 'form#order_review' ).length ) {
56
				this.form = $( 'form#order_review' );
57
			}
58
59
			$( 'form#order_review' )
60
				.on(
61
					'submit',
62
					this.onSubmit
63
				);
64
65
			// add payment method page
66
			if ( $( 'form#add_payment_method' ).length ) {
67
				this.form = $( 'form#add_payment_method' );
68
			}
69
70
			$( 'form#add_payment_method' )
71
				.on(
72
					'submit',
73
					this.onSubmit
74
				);
75
76
			$( 'form.woocommerce-checkout' )
77
				.on(
78
					'change',
79
					'#stripe-bank-country',
80
					this.reset
81
				);
82
83
			$( document )
84
				.on(
85
					'stripeError',
86
					this.onError
87
				)
88
				.on(
89
					'checkout_error',
90
					this.reset
91
				);
92
93
			var elementStyles = {
94
				base: {
95
					iconColor: '#666EE8',
96
					color: '#31325F',
97
					fontSize: '15px',
98
					'::placeholder': {
99
				  		color: '#CFD7E0',
100
					}
101
				}
102
			};
103
104
			var elementClasses = {
105
				focus: 'focused',
106
				empty: 'empty',
107
				invalid: 'invalid',
108
			};
109
110
			if ( 'yes' === wc_stripe_params.use_elements && $( '#stripe-card-element' ).length ) {
111
				elementStyles  = wc_stripe_params.elements_styling ? wc_stripe_params.elements_styling : elementStyles;
112
				elementClasses = wc_stripe_params.elements_classes ? wc_stripe_params.elements_classes : elementClasses;
113
114
				if ( 'yes' === wc_stripe_params.inline_cc_form ) {
115
					stripe_card = elements.create( 'card', { style: elementStyles, hidePostalCode: true } );
0 ignored issues
show
Bug introduced by
The variable elements does not seem to be initialized in case "yes" === wc_stripe_params.use_elements on line 8 is false. Are you sure this can never be the case?
Loading history...
116
117
					stripe_card.addEventListener( 'change', function( event ) {
118
						wc_stripe_form.onCCFormChange();
119
120
						if ( event.error ) {
121
							$( document.body ).trigger( 'stripeError', event );
122
						}
123
					} );
124
				} else {
125
					stripe_card = elements.create( 'cardNumber', { style: elementStyles, classes: elementClasses } );
0 ignored issues
show
Bug introduced by
The variable elements does not seem to be initialized in case "yes" === wc_stripe_params.use_elements on line 8 is false. Are you sure this can never be the case?
Loading history...
126
					stripe_exp  = elements.create( 'cardExpiry', { style: elementStyles, classes: elementClasses } );
127
					stripe_cvc  = elements.create( 'cardCvc', { style: elementStyles, classes: elementClasses } );
128
129
					stripe_card.addEventListener( 'change', function( event ) {
130
						wc_stripe_form.onCCFormChange();
131
132
						if ( event.error ) {
133
							$( document.body ).trigger( 'stripeError', event );
134
						}
135
					} );
136
137
					stripe_exp.addEventListener( 'change', function( event ) {
138
						wc_stripe_form.onCCFormChange();
139
140
						if ( event.error ) {
141
							$( document.body ).trigger( 'stripeError', event );
142
						}
143
					} );
144
145
					stripe_cvc.addEventListener( 'change', function( event ) {
146
						wc_stripe_form.onCCFormChange();
147
148
						if ( event.error ) {
149
							$( document.body ).trigger( 'stripeError', event );
150
						}
151
					} );
152
				}
153
154
				/**
155
				 * Only in checkout page we need to delay the mounting of the
156
				 * card as some AJAX process needs to happen before we do.
157
				 */
158
				if ( wc_stripe_params.is_checkout ) {
159
					$( document.body ).on( 'updated_checkout', function() {
160
						// Don't mount elements a second time.
161
						if ( stripe_card ) {
162
							if ( 'yes' === wc_stripe_params.inline_cc_form ) {
163
								stripe_card.unmount( '#stripe-card-element' );
164
							} else {
165
								stripe_card.unmount( '#stripe-card-element' );
166
								stripe_exp.unmount( '#stripe-exp-element' );
0 ignored issues
show
Bug introduced by
The variable stripe_exp seems to not be initialized for all possible execution paths.
Loading history...
167
								stripe_cvc.unmount( '#stripe-cvc-element' );
0 ignored issues
show
Bug introduced by
The variable stripe_cvc seems to not be initialized for all possible execution paths.
Loading history...
168
							}
169
						}
170
171
						if ( 'yes' === wc_stripe_params.inline_cc_form ) {
172
							stripe_card.mount( '#stripe-card-element' );
173
						} else {
174
							stripe_card.mount( '#stripe-card-element' );
175
							stripe_exp.mount( '#stripe-exp-element' );
176
							stripe_cvc.mount( '#stripe-cvc-element' );
177
						}
178
					});
179
				} else if ( $( 'form#add_payment_method' ).length || $( 'form#order_review' ).length ) {
180
					if ( 'yes' === wc_stripe_params.inline_cc_form ) {
181
						stripe_card.mount( '#stripe-card-element' );
182
					} else {
183
						stripe_card.mount( '#stripe-card-element' );
184
						stripe_exp.mount( '#stripe-exp-element' );
185
						stripe_cvc.mount( '#stripe-cvc-element' );
186
					}
187
				}
188
			}
189
		},
190
191
		// Check to see if Stripe in general is being used for checkout.
192
		isStripeChosen: function() {
193
			return $( '#payment_method_stripe, #payment_method_stripe_bancontact, #payment_method_stripe_sofort, #payment_method_stripe_giropay, #payment_method_stripe_ideal, #payment_method_stripe_alipay, #payment_method_stripe_sepa, #payment_method_stripe_bitcoin' ).is( ':checked' ) || 'new' === $( 'input[name="wc-stripe-payment-token"]:checked' ).val();
194
		},
195
196
		// Currently only support saved cards via credit cards and SEPA. No other payment method.
197
		isStripeSaveCardChosen: function() {
198
			return ( $( '#payment_method_stripe' ).is( ':checked' ) && ( $( 'input[name="wc-stripe-payment-token"]' ).is( ':checked' ) && 'new' !== $( 'input[name="wc-stripe-payment-token"]:checked' ).val() ) ) ||
199
				( $( '#payment_method_stripe_sepa' ).is( ':checked' ) && ( $( 'input[name="wc-stripe_sepa-payment-token"]' ).is( ':checked' ) && 'new' !== $( 'input[name="wc-stripe_sepa-payment-token"]:checked' ).val() ) );
200
		},
201
202
		// Stripe credit card used.
203
		isStripeCardChosen: function() {
204
			return $( '#payment_method_stripe' ).is( ':checked' );
205
		},
206
207
		isBancontactChosen: function() {
208
			return $( '#payment_method_stripe_bancontact' ).is( ':checked' );
209
		},
210
211
		isGiropayChosen: function() {
212
			return $( '#payment_method_stripe_giropay' ).is( ':checked' );
213
		},
214
215
		isIdealChosen: function() {
216
			return $( '#payment_method_stripe_ideal' ).is( ':checked' );
217
		},
218
219
		isSofortChosen: function() {
220
			return $( '#payment_method_stripe_sofort' ).is( ':checked' );
221
		},
222
223
		isAlipayChosen: function() {
224
			return $( '#payment_method_stripe_alipay' ).is( ':checked' );
225
		},
226
227
		isSepaChosen: function() {
228
			return $( '#payment_method_stripe_sepa' ).is( ':checked' );
229
		},
230
231
		isBitcoinChosen: function() {
232
			return $( '#payment_method_stripe_bitcoin' ).is( ':checked' );
233
		},
234
235
		hasSource: function() {
236
			return 0 < $( 'input.stripe-source' ).length;
237
		},
238
239
		// Legacy
240
		hasToken: function() {
241
			return 0 < $( 'input.stripe_token' ).length;
242
		},
243
244
		isMobile: function() {
245
			if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
0 ignored issues
show
Bug introduced by
The variable navigator seems to be never declared. If this is a global, consider adding a /** global: navigator */ 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...
246
				return true;
247
			}
248
249
			return false;
250
		},
251
252
		isStripeModalNeeded: function( e ) {
0 ignored issues
show
Unused Code introduced by
The parameter e 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...
253
			var token = wc_stripe_form.form.find( 'input.stripe_token' ),
254
				$required_inputs;
0 ignored issues
show
Unused Code introduced by
The variable $required_inputs seems to be never used. Consider removing it.
Loading history...
255
256
			// If this is a stripe submission (after modal) and token exists, allow submit.
257
			if ( wc_stripe_form.stripe_submit && token ) {
258
				return false;
259
			}
260
261
			// Don't affect submission if modal is not needed.
262
			if ( ! wc_stripe_form.isStripeChosen() ) {
263
				return false;
264
			}
265
266
			return true;
267
		},
268
269
		block: function() {
270
			if ( wc_stripe_form.isMobile() ) {
271
				$.blockUI({
272
					message: null,
273
					overlayCSS: {
274
						background: '#fff',
275
						opacity: 0.6
276
					}
277
				});
278
			} else {
279
				wc_stripe_form.form.block({
280
					message: null,
281
					overlayCSS: {
282
						background: '#fff',
283
						opacity: 0.6
284
					}
285
				});
286
			}
287
		},
288
289
		unblock: function() {
290
			if ( wc_stripe_form.isMobile() ) {
291
				$.unblockUI();
292
			} else {
293
				wc_stripe_form.form.unblock();
294
			}
295
		},
296
297
		getSelectedPaymentElement: function() {
298
			return $( '.payment_methods input[name="payment_method"]:checked' );
299
		},
300
301
		// Stripe Checkout.
302
		openModal: function() {
303
			// Capture submittal and open stripecheckout
304
			var $form = wc_stripe_form.form,
305
				$data = $( '#stripe-payment-data' ),
306
				token = $form.find( 'input.stripe_token' );
307
308
			token.val( '' );
309
310
			var token_action = function( res ) {
311
				$form.find( 'input.stripe_token' ).remove();
312
				$form.append( '<input type="hidden" class="stripe_token" name="stripe_token" value="' + res.id + '"/>' );
313
				$form.append( "<input type='hidden' class='stripe-checkout-object' name='stripe_checkout_object' value='" + wc_stripe_form.prepareSourceToServer( res ) + "'/>" );
314
				wc_stripe_form.stripe_submit = true;
315
316
				if ( $( 'form#add_payment_method' ).length ) {
317
					$( wc_stripe_form.form ).off( 'submit', wc_stripe_form.form.onSubmit );
318
				}
319
320
				$form.submit();
321
			};
322
323
			StripeCheckout.open({
0 ignored issues
show
Bug introduced by
The variable StripeCheckout seems to be never declared. If this is a global, consider adding a /** global: StripeCheckout */ 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...
324
				key               : wc_stripe_params.key,
325
				billingAddress    : 'yes' === wc_stripe_params.stripe_checkout_require_billing_address,
326
				amount            : $data.data( 'amount' ),
327
				name              : $data.data( 'name' ),
328
				description       : $data.data( 'description' ),
329
				currency          : $data.data( 'currency' ),
330
				image             : $data.data( 'image' ),
331
				bitcoin           : $data.data( 'bitcoin' ),
332
				locale            : $data.data( 'locale' ),
333
				email             : $( '#billing_email' ).val() || $data.data( 'email' ),
334
				panelLabel        : $data.data( 'panel-label' ),
335
				allowRememberMe   : $data.data( 'allow-remember-me' ),
336
				token             : token_action,
337
				closed            : wc_stripe_form.onClose()
338
			});
339
		},
340
341
		// Stripe Checkout.
342
		resetModal: function() {
343
			wc_stripe_form.reset();
344
			wc_stripe_form.stripe_checkout_submit = false;
345
		},
346
347
		// Stripe Checkout.
348
		onClose: function() {
349
			wc_stripe_form.unblock();
350
		},
351
352
		onError: function( e, result ) {
353
			var message = result.error.message,
354
				errorContainer = wc_stripe_form.getSelectedPaymentElement().parent( '.wc_payment_method, .woocommerce-PaymentMethod' ).find( '.stripe-source-errors' );
355
356
			// Customers do not need to know the specifics of the below type of errors
357
			// therefore return a generic localizable error message.
358
			if (
359
				'invalid_request_error' === result.error.type ||
360
				'api_connection_error'  === result.error.type ||
361
				'api_error'             === result.error.type ||
362
				'authentication_error'  === result.error.type ||
363
				'rate_limit_error'      === result.error.type
364
			) {
365
				message = wc_stripe_params.invalid_request_error;
366
			}
367
368
			if ( 'card_error' === result.error.type && wc_stripe_params.hasOwnProperty( result.error.code ) ) {
369
				message = wc_stripe_params[ result.error.code ];
370
			}
371
372
			if ( 'validation_error' === result.error.type && wc_stripe_params.hasOwnProperty( result.error.code ) ) {
373
				message = wc_stripe_params[ result.error.code ];
374
			}
375
376
			wc_stripe_form.reset();
377
			console.log( result.error.message ); // Leave for troubleshooting.
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
378
			$( errorContainer ).html( '<ul class="woocommerce_error woocommerce-error wc-stripe-error"><li>' + message + '</li></ul>' );
379
			wc_stripe_form.unblock();
380
		},
381
382
		getOwnerDetails: function() {
383
			var first_name = $( '#billing_first_name' ).length ? $( '#billing_first_name' ).val() : wc_stripe_params.billing_first_name,
384
				last_name  = $( '#billing_last_name' ).length ? $( '#billing_last_name' ).val() : wc_stripe_params.billing_last_name,
385
				extra_details = { owner: { name: '', address: {}, email: '', phone: '' } };
386
387
			extra_details.owner.name = first_name;
388
389
			if ( first_name && last_name ) {
390
				extra_details.owner.name = first_name + ' ' + last_name;
391
			}
392
393
			extra_details.owner.email = $( '#billing_email' ).val();
394
			extra_details.owner.phone = $( '#billing_phone' ).val();
395
396
			/* Stripe does not like empty string values so
397
			 * we need to remove the parameter if we're not
398
			 * passing any value.
399
			 */
400
			if ( 0 >= extra_details.owner.phone.length ) {
401
				delete extra_details.owner.phone;
402
			}
403
404
			if ( 0 >= extra_details.owner.email.length ) {
405
				delete extra_details.owner.email;
406
			}
407
408
			if ( $( '#billing_address_1' ).length > 0 ) {
409
				extra_details.owner.address.line1       = $( '#billing_address_1' ).val();
410
				extra_details.owner.address.line2       = $( '#billing_address_2' ).val();
411
				extra_details.owner.address.state       = $( '#billing_state' ).val();
412
				extra_details.owner.address.city        = $( '#billing_city' ).val();
413
				extra_details.owner.address.postal_code = $( '#billing_postcode' ).val();
414
				extra_details.owner.address.country     = $( '#billing_country' ).val();
415
			} else if ( wc_stripe_params.billing_address_1 ) {
416
				extra_details.owner.address.line1       = wc_stripe_params.billing_address_1;
417
				extra_details.owner.address.line2       = wc_stripe_params.billing_address_2;
418
				extra_details.owner.address.state       = wc_stripe_params.billing_state;
419
				extra_details.owner.address.city        = wc_stripe_params.billing_city;
420
				extra_details.owner.address.postal_code = wc_stripe_params.billing_postcode;
421
				extra_details.owner.address.country     = wc_stripe_params.billing_country;
422
			}
423
424
			return extra_details;
425
		},
426
427
		createSource: function() {
428
			var extra_details = wc_stripe_form.getOwnerDetails(),
429
				source_type   = 'card';
430
431
			if ( wc_stripe_form.isBancontactChosen() ) {
432
				source_type = 'bancontact';
433
			}
434
435
			if ( wc_stripe_form.isSepaChosen() ) {
436
				source_type = 'sepa_debit';
437
			}
438
439
			if ( wc_stripe_form.isIdealChosen() ) {
440
				source_type = 'ideal';
441
			}
442
443
			if ( wc_stripe_form.isSofortChosen() ) {
444
				source_type = 'sofort';
445
			}
446
447
			if ( wc_stripe_form.isBitcoinChosen() ) {
448
				source_type = 'bitcoin';
449
			}
450
451
			if ( wc_stripe_form.isGiropayChosen() ) {
452
				source_type = 'giropay';
453
			}
454
455
			if ( wc_stripe_form.isAlipayChosen() ) {
456
				source_type = 'alipay';
457
			}
458
459
			if ( 'card' === source_type ) {
460
				stripe.createSource( stripe_card, extra_details ).then( wc_stripe_form.sourceResponse );
461
			} else {
462
				switch ( source_type ) {
0 ignored issues
show
Coding Style introduced by
As per coding-style, switch statements should have a default case.
Loading history...
463
					case 'bancontact':
464
					case 'giropay':
465
					case 'ideal':
466
					case 'sofort':
467
					case 'alipay':
468
						// These redirect flow payment methods need this information to be set at source creation.
469
						extra_details.amount               = $( '#stripe-' + source_type + '-payment-data' ).data( 'amount' );
470
						extra_details.currency             = $( '#stripe-' + source_type + '-payment-data' ).data( 'currency' );
471
						extra_details.redirect             = { return_url: wc_stripe_params.return_url };
472
473
						if ( wc_stripe_params.statement_descriptor ) {
474
							extra_details.statement_descriptor = wc_stripe_params.statement_descriptor;
475
						}
476
477
						break;
478
				}
479
480
				// Handle special inputs that are unique to a payment method.
481
				switch ( source_type ) {
0 ignored issues
show
Coding Style introduced by
As per coding-style, switch statements should have a default case.
Loading history...
482
					case 'sepa_debit':
483
						extra_details.currency = $( '#stripe-' + source_type + '-payment-data' ).data( 'currency' );
484
						extra_details.owner.name = $( '#stripe-sepa-owner' ).val();
485
						extra_details.sepa_debit = { iban: $( '#stripe-sepa-iban' ).val() };
486
						break;
487
					case 'ideal':
488
						extra_details.ideal = { bank: $( '#stripe-ideal-bank' ).val() };
489
						break;
490
					case 'sofort':
491
						extra_details.sofort = { country: $( '#stripe-sofort-country' ).val() };
492
						break;
493
					case 'bitcoin':
494
					case 'alipay':
495
						extra_details.currency = $( '#stripe-' + source_type + '-payment-data' ).data( 'currency' );
496
						extra_details.amount = $( '#stripe-' + source_type + '-payment-data' ).data( 'amount' );
497
						break;
498
				}
499
500
				extra_details.type = source_type;
501
502
				stripe.createSource( extra_details ).then( wc_stripe_form.sourceResponse );
503
			}
504
		},
505
506
		sourceResponse: function( response ) {
507
			if ( response.error ) {
508
				$( document.body ).trigger( 'stripeError', response );
509
			} else if ( 'no' === wc_stripe_params.allow_prepaid_card && 'card' === response.source.type && 'prepaid' === response.source.card.funding ) {
510
				response.error = { message: wc_stripe_params.no_prepaid_card_msg };
511
512
				$( document.body ).trigger( 'stripeError', response );
513
			} else {
514
				wc_stripe_form.processStripeResponse( response.source );
515
			}
516
		},
517
518
		// Legacy
519
		createToken: function() {
520
			var card       = $( '#stripe-card-number' ).val(),
521
				cvc        = $( '#stripe-card-cvc' ).val(),
522
				expires    = $( '#stripe-card-expiry' ).payment( 'cardExpiryVal' ),
523
				first_name = $( '#billing_first_name' ).length ? $( '#billing_first_name' ).val() : wc_stripe_params.billing_first_name,
524
				last_name  = $( '#billing_last_name' ).length ? $( '#billing_last_name' ).val() : wc_stripe_params.billing_last_name,
525
				data       = {
526
					number   : card,
527
					cvc      : cvc,
528
					exp_month: parseInt( expires.month, 10 ) || 0,
529
					exp_year : parseInt( expires.year, 10 ) || 0
530
				};
531
532
			if ( first_name && last_name ) {
533
				data.name = first_name + ' ' + last_name;
534
			}
535
536
			if ( $( '#billing_address_1' ).length > 0 ) {
537
				data.address_line1   = $( '#billing_address_1' ).val();
538
				data.address_line2   = $( '#billing_address_2' ).val();
539
				data.address_state   = $( '#billing_state' ).val();
540
				data.address_city    = $( '#billing_city' ).val();
541
				data.address_zip     = $( '#billing_postcode' ).val();
542
				data.address_country = $( '#billing_country' ).val();
543
			} else if ( wc_stripe_params.billing_address_1 ) {
544
				data.address_line1   = wc_stripe_params.billing_address_1;
545
				data.address_line2   = wc_stripe_params.billing_address_2;
546
				data.address_state   = wc_stripe_params.billing_state;
547
				data.address_city    = wc_stripe_params.billing_city;
548
				data.address_zip     = wc_stripe_params.billing_postcode;
549
				data.address_country = wc_stripe_params.billing_country;
550
			}
551
			Stripe.setPublishableKey( wc_stripe_params.key );
0 ignored issues
show
Bug introduced by
The variable Stripe seems to be never declared. If this is a global, consider adding a /** global: Stripe */ 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...
552
			Stripe.createToken( data, wc_stripe_form.onStripeTokenResponse );
553
		},
554
555
		// Legacy
556
		onStripeTokenResponse: function( status, response ) {
557
			if ( response.error ) {
558
				$( document ).trigger( 'stripeError', response );
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
559
			} else {
560
				// check if we allow prepaid cards
561
				if ( 'no' === wc_stripe_params.allow_prepaid_card && 'prepaid' === response.card.funding ) {
562
					response.error = { message: wc_stripe_params.no_prepaid_card_msg };
563
564
					$( document ).trigger( 'stripeError', { response: response } );
565
566
					return false;
567
				}
568
569
				// token contains id, last4, and card type
570
				var token = response.id;
571
572
				// insert the token into the form so it gets submitted to the server
573
				wc_stripe_form.form.append( "<input type='hidden' class='stripe_token' name='stripe_token' value='" + token + "'/>" );
574
575
				if ( $( 'form#add_payment_method' ).length ) {
576
					$( wc_stripe_form.form ).off( 'submit', wc_stripe_form.form.onSubmit );
577
				}
578
579
				wc_stripe_form.form.submit();
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
580
			}
581
		},
582
583
		onSubmit: function( e ) {
584
			if ( wc_stripe_form.isStripeChosen() && ! wc_stripe_form.isStripeSaveCardChosen() && ! wc_stripe_form.hasSource() && ! wc_stripe_form.hasToken() ) {
585
				e.preventDefault();
586
587
				// Stripe Checkout.
588
				if ( 'yes' === wc_stripe_params.is_stripe_checkout && wc_stripe_form.isStripeModalNeeded() && wc_stripe_form.isStripeCardChosen() ) {
589
					// Since in mobile actions cannot be deferred, no dynamic validation applied.
590
					if ( wc_stripe_form.isMobile() ) {
591
						wc_stripe_form.openModal();
592
					} else {
593
						wc_stripe_form.validateCheckout( 'modal' );
594
					}
595
596
					return false;
597
				}
598
599
				wc_stripe_form.block();
600
601
				// Process legacy card token.
602
				if ( wc_stripe_form.isStripeCardChosen() && 'no' === wc_stripe_params.use_elements ) {
603
					wc_stripe_form.createToken();
604
					return false;
605
				}
606
607
				if (
608
					wc_stripe_form.isBancontactChosen() ||
609
					wc_stripe_form.isGiropayChosen() ||
610
					wc_stripe_form.isIdealChosen() ||
611
					wc_stripe_form.isAlipayChosen()
612
				) {
613
					if ( $( 'form#order_review' ).length ) {
614
						$( 'form#order_review' )
615
							.off(
616
								'submit',
617
								this.onSubmit
618
							);
619
620
						wc_stripe_form.form.submit();
621
					}
622
623
					return true;
624
				}
625
626
				if ( wc_stripe_form.isSofortChosen() ) {
627
					// Check if Sofort bank country is chosen before proceed.
628
					if ( '-1' === $( '#stripe-bank-country' ).val() ) {
629
						var error = { error: { message: wc_stripe_params.no_bank_country_msg } };
630
						$( document.body ).trigger( 'stripeError', error );
631
						return false;
632
					}
633
634
					if ( $( 'form#order_review' ).length ) {
635
						$( 'form#order_review' )
636
							.off(
637
								'submit',
638
								this.onSubmit
639
							);
640
641
						wc_stripe_form.form.submit();
642
					}
643
644
					return true;
645
				}
646
647
				wc_stripe_form.validateCheckout();
648
649
				// Prevent form submitting
650
				return false;
651
			} else if ( $( 'form#add_payment_method' ).length ) {
0 ignored issues
show
Complexity Best Practice introduced by
There is no return statement if $("form#add_payment_method").length is false. Are you sure this is correct? If so, consider adding return; explicitly.

This check looks for functions where a return statement is found in some execution paths, but not in all.

Consider this little piece of code

function isBig(a) {
    if (a > 5000) {
        return "yes";
    }
}

console.log(isBig(5001)); //returns yes
console.log(isBig(42)); //returns undefined

The function isBig will only return a specific value when its parameter is bigger than 5000. In any other case, it will implicitly return undefined.

This behaviour may not be what you had intended. In any case, you can add a return undefined to the other execution path to make the return value explicit.

Loading history...
652
				e.preventDefault();
653
654
				// Stripe Checkout.
655
				if ( 'yes' === wc_stripe_params.is_stripe_checkout && wc_stripe_form.isStripeModalNeeded() && wc_stripe_form.isStripeCardChosen() ) {
656
					wc_stripe_form.openModal();
657
658
					return false;
659
				}
660
661
				if ( wc_stripe_form.isSepaChosen() ) {
662
					// Check if SEPA owner is filled before proceed.
663
					if ( '' === $( '#stripe-sepa-owner' ).val() ) {
664
						$( document.body ).trigger( 'stripeError', { error: { message: wc_stripe_params.no_sepa_owner_msg } } );
665
						return false;
666
					}
667
668
					// Check if SEPA IBAN is filled before proceed.
669
					if ( '' === $( '#stripe-sepa-iban' ).val() ) {
670
						$( document.body ).trigger( 'stripeError', { error: { message: wc_stripe_params.no_sepa_iban_msg } } );
671
						return false;
672
					}
673
				}
674
675
				wc_stripe_form.block();
676
677
				// Process legacy card token.
678
				if ( wc_stripe_form.isStripeCardChosen() && 'no' === wc_stripe_params.use_elements ) {
679
					wc_stripe_form.createToken();
680
					return false;
681
				}
682
683
				wc_stripe_form.createSource();
684
				return false;
685
			}
686
		},
687
688
		onCCFormChange: function() {
689
			wc_stripe_form.reset();
690
		},
691
692
		prepareSourceToServer: function( source ) {
693
			var preparedSource = {
694
				id:      source.id,
695
				card:    source.card ? source.card : '',
696
				bitcoin: source.bitcoin ? source.bitcoin : '',
697
				flow:    source.flow,
698
				object:  source.object,
699
				status:  source.status,
700
				type:    source.type,
701
				usage:   source.usage
702
			};
703
704
			return preparedSource;
705
		},
706
707
		processStripeResponse: function( source ) {
708
			wc_stripe_form.reset();
709
710
			// Insert the Source into the form so it gets submitted to the server.
711
			wc_stripe_form.form.append( "<input type='hidden' class='stripe-source' name='stripe_source' value='" + JSON.stringify( wc_stripe_form.prepareSourceToServer( source ) ) + "'/>" );
712
713
			if ( $( 'form#add_payment_method' ).length ) {
714
				$( wc_stripe_form.form ).off( 'submit', wc_stripe_form.form.onSubmit );
715
			}
716
717
			wc_stripe_form.form.submit();
718
		},
719
720
		reset: function() {
721
			$( '.wc-stripe-error, .stripe-source, .stripe_token, .stripe-checkout-object' ).remove();
722
723
			// Stripe Checkout.
724
			if ( 'yes' === wc_stripe_params.is_stripe_checkout ) {
725
				wc_stripe_form.stripe_submit = false;
726
			}
727
		},
728
729
		getRequiredFields: function() {
730
			return wc_stripe_form.form.find( '.form-row.validate-required > input, .form-row.validate-required > select' );
731
		},
732
733
		validateCheckout: function( type ) {
734
			if ( typeof type === 'undefined' ) {
735
				type = '';
736
			}
737
738
			var data = {
739
				'nonce': wc_stripe_params.stripe_nonce,
740
				'required_fields': wc_stripe_form.getRequiredFields().serialize(),
741
				'all_fields': wc_stripe_form.form.serialize(),
742
				'source_type': wc_stripe_form.getSelectedPaymentElement().val(),
743
				'is_add_payment_page': wc_stripe_params.is_add_payment_method_page
744
			};
745
746
			$.ajax({
747
				type:		'POST',
748
				url:		wc_stripe_form.getAjaxURL( 'validate_checkout' ),
749
				data:		data,
750
				dataType:   'json',
751
				success:	function( result ) {
752
					if ( 'success' === result ) {
753
						// Stripe Checkout.
754
						if ( 'modal' === type ) {
755
							wc_stripe_form.openModal();
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
756
						} else {
757
							if ( wc_stripe_form.isSepaChosen() ) {
758
								// Check if SEPA owner is filled before proceed.
759
								if ( '' === $( '#stripe-sepa-owner' ).val() ) {
760
									$( document.body ).trigger( 'stripeError', { error: { message: wc_stripe_params.no_sepa_owner_msg } } );
761
									return false;
762
								}
763
764
								// Check if SEPA IBAN is filled before proceed.
765
								if ( '' === $( '#stripe-sepa-iban' ).val() ) {
766
									$( document.body ).trigger( 'stripeError', { error: { message: wc_stripe_params.no_sepa_iban_msg } } );
767
									return false;
768
								}
769
							}
770
771
							wc_stripe_form.createSource();
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
772
						}
773
					} else if ( result.messages ) {
0 ignored issues
show
Complexity Best Practice introduced by
There is no return statement if result.messages is false. Are you sure this is correct? If so, consider adding return; explicitly.

This check looks for functions where a return statement is found in some execution paths, but not in all.

Consider this little piece of code

function isBig(a) {
    if (a > 5000) {
        return "yes";
    }
}

console.log(isBig(5001)); //returns yes
console.log(isBig(42)); //returns undefined

The function isBig will only return a specific value when its parameter is bigger than 5000. In any other case, it will implicitly return undefined.

This behaviour may not be what you had intended. In any case, you can add a return undefined to the other execution path to make the return value explicit.

Loading history...
774
						wc_stripe_form.resetModal();
775
						wc_stripe_form.reset();
776
						wc_stripe_form.submitError( result.messages );
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
777
					}
778
				}
779
			});
780
		},
781
782
		submitError: function( error_message ) {
783
			$( '.woocommerce-NoticeGroup-checkout, .woocommerce-error, .woocommerce-message' ).remove();
784
			wc_stripe_form.form.prepend( '<div class="woocommerce-NoticeGroup woocommerce-NoticeGroup-checkout">' + error_message + '</div>' );
785
			wc_stripe_form.form.removeClass( 'processing' ).unblock();
786
			wc_stripe_form.form.find( '.input-text, select, input:checkbox' ).blur();
787
			$( 'html, body' ).animate({
788
				scrollTop: ( $( 'form.checkout' ).offset().top - 100 )
789
			}, 1000 );
790
			$( document.body ).trigger( 'checkout_error' );
791
			wc_stripe_form.unblock();
792
		}
793
	};
794
795
	wc_stripe_form.init();
796
} );
797