Payment Plugins for Stripe WooCommerce - Version 3.2.3

Version Description

  • Fixed - 3DS pop up on order pay page
  • Fixed - One time use coupon error when 3DS triggered on checkout page
  • Fixed - Formatting in class-wc-stripe-admin-notices.php
  • Added - Apple Pay, GPay, Payment Request, do not request shipping address or shipping options on checkout page if customer has already filled out shipping fields
Download this release

Release Info

Developer mr.clayton
Plugin Icon wp plugin Payment Plugins for Stripe WooCommerce
Version 3.2.3
Comparing to
See all releases

Code changes from version 3.2.2 to 3.2.3

assets/js/frontend/applepay-checkout.js CHANGED
@@ -39,8 +39,8 @@
39
 
40
  ApplePay.prototype.updated_checkout = function () {
41
  if (this.can_pay) {
42
- this.create_button();
43
- $(this.container).show();
44
  }
45
  }
46
 
@@ -58,7 +58,9 @@
58
 
59
  ApplePay.prototype.on_token_received = function () {
60
  wc_stripe.CheckoutGateway.prototype.on_token_received.apply(this, arguments);
61
- this.maybe_set_ship_to_different();
 
 
62
  this.fields.toFormFields({update_shipping_method: false});
63
  if (this.checkout_fields_valid()) {
64
  this.get_form().submit();
39
 
40
  ApplePay.prototype.updated_checkout = function () {
41
  if (this.can_pay) {
42
+ this.createPaymentRequest();
43
+ wc_stripe.ApplePay.prototype.canMakePayment.apply(this, arguments);
44
  }
45
  }
46
 
58
 
59
  ApplePay.prototype.on_token_received = function () {
60
  wc_stripe.CheckoutGateway.prototype.on_token_received.apply(this, arguments);
61
+ if (this.payment_request_options.requestShipping) {
62
+ this.maybe_set_ship_to_different();
63
+ }
64
  this.fields.toFormFields({update_shipping_method: false});
65
  if (this.checkout_fields_valid()) {
66
  this.get_form().submit();
assets/js/frontend/credit-card.js CHANGED
@@ -10,9 +10,10 @@
10
  wc_stripe.CheckoutGateway.call(this);
11
  window.addEventListener('hashchange', this.hashChange.bind(this));
12
  wc_stripe.credit_card = this;
 
13
  }
14
 
15
- const elementClasses = {
16
  focus: 'focused',
17
  empty: 'empty',
18
  invalid: 'invalid'
@@ -178,23 +179,15 @@
178
  if (this.is_gateway_selected()) {
179
  var match = e.newURL.match(/response=(.*)/);
180
  if (match) {
181
- var obj = JSON.parse(window.atob(match[1]));
182
- this.stripe.handleCardAction(obj.client_secret).then(function (result) {
183
- if (result.error) {
184
- this.payment_token_received = false;
185
- this.submit_error(result.error);
186
- this.sync_payment_intent(obj.order_id, obj.client_secret).catch(function (response) {
187
- this.submit_error(response.message);
188
- }.bind(this));
189
- return;
190
  }
191
- var $form = $(this.token_selector).closest('form');
192
- $form.unblock().removeClass('processing');
193
- $form.submit();
194
- }.bind(this)).catch(function (error) {
195
- this.submit_error(error.message);
196
- }.bind(this))
197
- return false;
198
  }
199
  return true;
200
  }
@@ -223,17 +216,19 @@
223
  } else {
224
  if (!this.payment_token_received && !this.is_saved_method_selected()) {
225
  e.preventDefault();
226
- this.stripe.createPaymentMethod({
227
- type: 'card',
228
- card: this.is_custom_form() ? this.cardNumber : this.card,
229
- billing_details: this.get_billing_details()
230
- }).then(function (result) {
231
- if (result.error) {
232
- this.submit_error(result.error);
233
- return;
234
- }
235
- this.on_token_received(result.paymentMethod);
236
- }.bind(this))
 
 
237
  }
238
  }
239
  }
@@ -425,6 +420,72 @@
425
  return this.is_add_payment_method_page() || this.is_change_payment_method();
426
  }
427
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428
  new CC();
429
 
430
  }(jQuery, window.wc_stripe))
10
  wc_stripe.CheckoutGateway.call(this);
11
  window.addEventListener('hashchange', this.hashChange.bind(this));
12
  wc_stripe.credit_card = this;
13
+ this.has3DSecureParams();
14
  }
15
 
16
+ var elementClasses = {
17
  focus: 'focused',
18
  empty: 'empty',
19
  invalid: 'invalid'
179
  if (this.is_gateway_selected()) {
180
  var match = e.newURL.match(/response=(.*)/);
181
  if (match) {
182
+ try {
183
+ var obj = JSON.parse(window.atob(match[1]));
184
+ if (obj && obj.hasOwnProperty('client_secret')) {
185
+ history.pushState({}, '', window.location.pathname);
186
+ this.handle_card_action(obj);
 
 
 
 
187
  }
188
+ } catch (err) {
189
+
190
+ }
 
 
 
 
191
  }
192
  return true;
193
  }
216
  } else {
217
  if (!this.payment_token_received && !this.is_saved_method_selected()) {
218
  e.preventDefault();
219
+ if (this.checkout_fields_valid()) {
220
+ this.stripe.createPaymentMethod({
221
+ type: 'card',
222
+ card: this.is_custom_form() ? this.cardNumber : this.card,
223
+ billing_details: this.get_billing_details()
224
+ }).then(function (result) {
225
+ if (result.error) {
226
+ this.submit_error(result.error);
227
+ return;
228
+ }
229
+ this.on_token_received(result.paymentMethod);
230
+ }.bind(this))
231
+ }
232
  }
233
  }
234
  }
420
  return this.is_add_payment_method_page() || this.is_change_payment_method();
421
  }
422
 
423
+ CC.prototype.has3DSecureParams = function () {
424
+ if (this.is_gateway_selected() && this.get_page() === 'order_pay') {
425
+ if (window.location.hash && typeof window.location.hash === 'string') {
426
+ var match = window.location.hash.match(/response=(.*)/);
427
+ try {
428
+ var obj = JSON.parse(window.atob(match[1]));
429
+ if (obj && obj.hasOwnProperty('client_secret')) {
430
+ $('[name="terms"]').prop('checked', true);
431
+ this.handle_card_action(obj);
432
+ }
433
+ } catch (err) {
434
+
435
+ }
436
+ }
437
+ }
438
+ }
439
+
440
+ CC.prototype.handle_card_action = function (obj) {
441
+ try {
442
+ this.stripe.handleCardAction(obj.client_secret).then(function (result) {
443
+ if (result.error) {
444
+ this.payment_token_received = false;
445
+ this.submit_error(result.error);
446
+ this.sync_payment_intent(obj.order_id, obj.client_secret).catch(function (response) {
447
+ this.submit_error(response.message);
448
+ }.bind(this));
449
+ return;
450
+ }
451
+ if (this.get_page() === 'checkout' && $('.woocommerce-remove-coupon').length) {
452
+ // coupons so process via REST
453
+ this.submit_checkout_order();
454
+ } else {
455
+ var $form = this.get_form();
456
+ $form.unblock().removeClass('processing');
457
+ $form.submit();
458
+ }
459
+ }.bind(this)).catch(function (error) {
460
+ this.submit_error(error.message);
461
+ }.bind(this))
462
+ return false;
463
+ } catch (err) {
464
+
465
+ }
466
+ }
467
+
468
+ CC.prototype.submit_checkout_order = function () {
469
+ $.ajax({
470
+ method: 'POST',
471
+ url: this.params.routes.checkout_payment,
472
+ dataType: 'json',
473
+ data: $.extend({}, this.fields.toJson(), {'wp_rest_nonce': this.params.rest_nonce})
474
+ }).done(function (result) {
475
+ if (result.result && result.result === 'success') {
476
+ window.location = result.redirect;
477
+ } else {
478
+ if (result.messages) {
479
+ this.submit_error(result.messages);
480
+ } else {
481
+ this.submit_error(wc_checkout_params.i18n_checkout_error);
482
+ }
483
+ }
484
+ }.bind(this)).fail(function () {
485
+
486
+ }.bind(this))
487
+ }
488
+
489
  new CC();
490
 
491
  }(jQuery, window.wc_stripe))
assets/js/frontend/googlepay-checkout.js CHANGED
@@ -66,7 +66,9 @@
66
 
67
  GPay.prototype.on_token_received = function () {
68
  wc_stripe.CheckoutGateway.prototype.on_token_received.apply(this, arguments);
69
- this.maybe_set_ship_to_different();
 
 
70
  this.fields.toFormFields({update_shipping_method: false});
71
  if (this.checkout_fields_valid()) {
72
  this.get_form().submit();
66
 
67
  GPay.prototype.on_token_received = function () {
68
  wc_stripe.CheckoutGateway.prototype.on_token_received.apply(this, arguments);
69
+ if (this.payment_request_options.shippingAddressRequired) {
70
+ this.maybe_set_ship_to_different();
71
+ }
72
  this.fields.toFormFields({update_shipping_method: false});
73
  if (this.checkout_fields_valid()) {
74
  this.get_form().submit();
assets/js/frontend/local-payment.js CHANGED
@@ -17,7 +17,7 @@
17
 
18
  $(document.body).on('click', '#place_order', this.place_order.bind(this));
19
 
20
- if ($(document.body).is('.woocommerce-order-pay')) {
21
  $('#order_review').on('submit', this.process_order_pay.bind(this));
22
  }
23
 
17
 
18
  $(document.body).on('click', '#place_order', this.place_order.bind(this));
19
 
20
+ if (this.get_page() === 'order_pay') {
21
  $('#order_review').on('submit', this.process_order_pay.bind(this));
22
  }
23
 
assets/js/frontend/payment-request.js CHANGED
@@ -48,9 +48,6 @@
48
  this.cart_calculation(variation.variation_id).then(function () {
49
  if (this.is_variable_product() && $(this.container).is('.processingFoundVariation')) {
50
  this.createPaymentRequest();
51
- if (this.paymentRequestButton) {
52
- this.paymentRequestButton.destroy();
53
- }
54
  this.createPaymentRequestButton();
55
  wc_stripe.PaymentRequest.prototype.canMakePayment.apply(this, arguments).then(function () {
56
  this.enable_payment_button();
@@ -132,14 +129,6 @@
132
  }.bind(this))
133
  }
134
 
135
- /**
136
- * New paymentRequest is needed since cart might have changed.
137
- * @return {[type]} [description]
138
- */
139
- PaymentRequest.prototype.init_payment_request = function () {
140
- this.paymentRequestButton.destroy();
141
- }
142
-
143
  /**
144
  * [updated_html description]
145
  * @return {[type]} [description]
@@ -149,7 +138,6 @@
149
  this.can_pay = false;
150
  }
151
  if (this.can_pay) {
152
- this.paymentRequestButton.destroy();
153
  this.initialize();
154
  }
155
  }
@@ -234,8 +222,9 @@
234
  */
235
  PaymentRequest.prototype.updated_checkout = function () {
236
  if (this.can_pay) {
237
- $(this.container).show();
238
- this.create_button();
 
239
  }
240
  }
241
 
@@ -252,7 +241,9 @@
252
  PaymentRequest.prototype.on_token_received = function () {
253
  wc_stripe.CheckoutGateway.prototype.on_token_received.apply(this, arguments);
254
  this.fields.toFormFields();
255
- this.maybe_set_ship_to_different();
 
 
256
  if (this.checkout_fields_valid()) {
257
  this.get_form().submit();
258
  }
48
  this.cart_calculation(variation.variation_id).then(function () {
49
  if (this.is_variable_product() && $(this.container).is('.processingFoundVariation')) {
50
  this.createPaymentRequest();
 
 
 
51
  this.createPaymentRequestButton();
52
  wc_stripe.PaymentRequest.prototype.canMakePayment.apply(this, arguments).then(function () {
53
  this.enable_payment_button();
129
  }.bind(this))
130
  }
131
 
 
 
 
 
 
 
 
 
132
  /**
133
  * [updated_html description]
134
  * @return {[type]} [description]
138
  this.can_pay = false;
139
  }
140
  if (this.can_pay) {
 
141
  this.initialize();
142
  }
143
  }
222
  */
223
  PaymentRequest.prototype.updated_checkout = function () {
224
  if (this.can_pay) {
225
+ this.createPaymentRequest();
226
+ this.createPaymentRequestButton();
227
+ wc_stripe.PaymentRequest.prototype.canMakePayment.apply(this, arguments);
228
  }
229
  }
230
 
241
  PaymentRequest.prototype.on_token_received = function () {
242
  wc_stripe.CheckoutGateway.prototype.on_token_received.apply(this, arguments);
243
  this.fields.toFormFields();
244
+ if (this.payment_request_options.requestShipping) {
245
+ this.maybe_set_ship_to_different();
246
+ }
247
  if (this.checkout_fields_valid()) {
248
  this.get_form().submit();
249
  }
assets/js/frontend/wc-stripe.js CHANGED
@@ -1,1945 +1,2003 @@
1
- (function (window, $) {
2
- window.wc_stripe = {};
3
- var stripe = null;
4
-
5
- if (typeof wc_stripe_checkout_fields === 'undefined') {
6
- window.wc_stripe_checkout_fields = [];
7
- }
8
-
9
- wc_stripe.BaseGateway = function (params, container) {
10
- this.params = params;
11
- this.gateway_id = this.params.gateway_id;
12
- this.container = typeof container === 'undefined' ? 'li.payment_method_'.concat(this.gateway_id) : container;
13
-
14
- if (!$(this.container).length) {
15
- this.container = '.payment_method_'.concat(this.gateway_id);
16
- }
17
-
18
- this.token_selector = this.params.token_selector;
19
- this.saved_method_selector = this.params.saved_method_selector;
20
- this.payment_token_received = false;
21
- this.stripe = stripe;
22
- this.elements = stripe.elements($.extend({}, {
23
- locale: 'auto'
24
- }, this.get_element_options()));
25
- this.fields = checkoutFields;
26
- this.initialize();
27
- };
28
-
29
- wc_stripe.BaseGateway.prototype.get_page = function () {
30
- return wc_stripe_params_v3.page;
31
- };
32
-
33
- wc_stripe.BaseGateway.prototype.set_nonce = function (value) {
34
- this.fields.set(this.gateway_id + '_token_key', value);
35
- $(this.token_selector).val(value);
36
- };
37
- /**
38
- * [get_element_options description]
39
- * @return {[type]} [description]
40
- */
41
-
42
-
43
- wc_stripe.BaseGateway.prototype.get_element_options = function () {
44
- return {};
45
- };
46
-
47
- wc_stripe.BaseGateway.prototype.initialize = function () {
48
- };
49
- /**
50
- * @return {[type]}
51
- */
52
-
53
-
54
- wc_stripe.BaseGateway.prototype.create_button = function () {
55
- };
56
- /**
57
- * @returns {Boolean}
58
- */
59
-
60
-
61
- wc_stripe.BaseGateway.prototype.is_gateway_selected = function () {
62
- return $('[name="payment_method"]:checked').val() === this.gateway_id;
63
- };
64
- /**
65
- * @returns {Boolean}
66
- */
67
-
68
-
69
- wc_stripe.BaseGateway.prototype.is_saved_method_selected = function () {
70
- return this.is_gateway_selected() && $('[name="' + this.gateway_id + '_payment_type_key"]:checked').val() === 'saved';
71
- };
72
- /**
73
- * @return {Boolean}
74
- */
75
-
76
-
77
- wc_stripe.BaseGateway.prototype.has_checkout_error = function () {
78
- return $('#wc_stripe_checkout_error').length > 0 && this.is_gateway_selected();
79
- };
80
- /**
81
- * @param {[type]}
82
- * @return {[type]}
83
- */
84
-
85
-
86
- wc_stripe.BaseGateway.prototype.submit_error = function (message) {
87
- message = this.get_error_message(message);
88
-
89
- if (message.indexOf('</ul>') == -1) {
90
- message = '<div class="woocommerce-error">' + message + '</div>';
91
- }
92
-
93
- this.submit_message(message);
94
- };
95
-
96
- wc_stripe.BaseGateway.prototype.submit_error_code = function (code) {
97
- console.log(code);
98
- };
99
-
100
- wc_stripe.BaseGateway.prototype.get_error_message = function (message) {
101
- if (typeof message == 'object' && message.code) {
102
- if (wc_stripe_messages[message.code]) {
103
- message = wc_stripe_messages[message.code];
104
- } else {
105
- message = message.message;
106
- }
107
- }
108
-
109
- return message;
110
- };
111
- /**
112
- * @param {[type]}
113
- * @return {[type]}
114
- */
115
-
116
-
117
- wc_stripe.BaseGateway.prototype.submit_message = function (message) {
118
- $('.woocommerce-error, .woocommerce-message, .woocommerce-info').remove();
119
- var $container = $(this.message_container);
120
-
121
- if ($container.closest('form').length) {
122
- $container = $container.closest('form');
123
- }
124
-
125
- $container.prepend(message);
126
- $container.removeClass('processing').unblock();
127
- $container.find('.input-text, select, input:checkbox').blur();
128
-
129
- if ($.scroll_to_notices) {
130
- $.scroll_to_notices($container);
131
- } else {
132
- $('html, body').animate({
133
- scrollTop: $container.offset().top - 100
134
- }, 1000);
135
- }
136
- };
137
-
138
- wc_stripe.BaseGateway.prototype.get_first_name = function (prefix) {
139
- return $('#' + prefix + '_first_name').val();
140
- };
141
-
142
- wc_stripe.BaseGateway.prototype.get_last_name = function (prefix) {
143
- return $('#' + prefix + '_last_name').val();
144
- };
145
- /**
146
- * Return true if the source should be saved.
147
- *
148
- * @returns {Boolean}
149
- */
150
-
151
-
152
- wc_stripe.BaseGateway.prototype.should_save_method = function () {
153
- return $('#' + this.gateway_id + '_save_source_key').is(':checked');
154
- };
155
-
156
- wc_stripe.BaseGateway.prototype.is_add_payment_method_page = function () {
157
- return this.get_page() === 'add_payment_method' || $(document.body).hasClass('woocommerce-add-payment-method');
158
- };
159
-
160
- wc_stripe.BaseGateway.prototype.is_change_payment_method = function () {
161
- return this.get_page() === 'change_payment_method';
162
- };
163
-
164
- wc_stripe.BaseGateway.prototype.get_selected_payment_method = function () {
165
- return $(this.saved_method_selector).val();
166
- };
167
-
168
- wc_stripe.BaseGateway.prototype.needs_shipping = function () {
169
- return this.get_gateway_data().needs_shipping;
170
- };
171
-
172
- wc_stripe.BaseGateway.prototype.get_currency = function () {
173
- return this.get_gateway_data().currency;
174
- };
175
-
176
- wc_stripe.BaseGateway.prototype.get_gateway_data = function () {
177
- return $(this.container).find(".woocommerce_".concat(this.gateway_id, "_gateway_data")).data('gateway');
178
- };
179
-
180
- wc_stripe.BaseGateway.prototype.set_gateway_data = function (data) {
181
- $(this.container).find(".woocommerce_".concat(this.gateway_id, "_gateway_data")).data('gateway', data);
182
- };
183
- /**
184
- * [get_customer_name description]
185
- * @return String
186
- */
187
-
188
-
189
- wc_stripe.BaseGateway.prototype.get_customer_name = function (prefix) {
190
- return this.fields.get(prefix + '_first_name') + ' ' + this.fields.get(prefix + '_last_name');
191
- };
192
- /**
193
- * [get_customer_email description]
194
- * @return {String} [description]
195
- */
196
-
197
-
198
- wc_stripe.BaseGateway.prototype.get_customer_email = function () {
199
- return this.fields.get('billing_email');
200
- };
201
- /**
202
- * Returns a string representation of an address.
203
- * @param {[type]}
204
- * @return {[type]}
205
- */
206
-
207
-
208
- wc_stripe.BaseGateway.prototype.get_address_field_hash = function (prefix) {
209
- var params = ['_first_name', '_last_name', '_address_1', '_address_2', '_postcode', '_city', '_state', '_country'];
210
- var hash = '';
211
-
212
- for (var i = 0; i < params.length; i++) {
213
- hash += this.fields.get(prefix + params[i]) + '_';
214
- }
215
-
216
- return hash;
217
- };
218
- /**
219
- * @return {[type]}
220
- */
221
-
222
-
223
- wc_stripe.BaseGateway.prototype.block = function () {
224
- if ($().block) {
225
- $.blockUI({
226
- message: null,
227
- overlayCSS: {
228
- background: '#fff',
229
- opacity: 0.6
230
- }
231
- });
232
- }
233
- ;
234
- }
235
- /**
236
- * @return {[type]}
237
- */
238
-
239
-
240
- wc_stripe.BaseGateway.prototype.unblock = function () {
241
- if ($().block) {
242
- $.unblockUI();
243
- }
244
- };
245
- /**
246
- * @return {[type]}
247
- */
248
-
249
-
250
- wc_stripe.BaseGateway.prototype.get_form = function () {
251
- return $(this.token_selector).closest('form');
252
- };
253
- /**
254
- * @return {[type]}
255
- */
256
-
257
-
258
- wc_stripe.BaseGateway.prototype.get_total_price = function () {
259
- return this.get_gateway_data().total;
260
- };
261
-
262
- wc_stripe.BaseGateway.prototype.get_total_price_cents = function () {
263
- return this.get_gateway_data().total_cents;
264
- };
265
- /**
266
- * @return {[type]}
267
- */
268
-
269
-
270
- wc_stripe.BaseGateway.prototype.set_total_price = function (total) {
271
- var data = this.get_gateway_data();
272
- data.total = total;
273
- this.set_gateway_data(data);
274
- };
275
- /**
276
- * @return {[type]}
277
- */
278
-
279
-
280
- wc_stripe.BaseGateway.prototype.set_total_price_cents = function (total) {
281
- var data = this.get_gateway_data();
282
- data.total_cents = total;
283
- this.set_gateway_data(data);
284
- };
285
- /**
286
- * [set_payment_method description]
287
- * @param {[type]} payment_method [description]
288
- */
289
-
290
-
291
- wc_stripe.BaseGateway.prototype.set_payment_method = function (payment_method) {
292
- $('[name="payment_method"][value="' + payment_method + '"]').prop("checked", true).trigger('click');
293
- };
294
- /**
295
- * [set_shipping_methods description]
296
- */
297
-
298
-
299
- wc_stripe.BaseGateway.prototype.set_selected_shipping_methods = function (shipping_methods) {
300
- this.fields.set('shipping_method', shipping_methods);
301
-
302
- if (shipping_methods && $('[name^="shipping_method"]').length) {
303
- for (var i in shipping_methods) {
304
- var method = shipping_methods[i];
305
- $('[name="shipping_method[' + i + ']"][value="' + method + '"]').prop("checked", true).trigger('change');
306
- }
307
- }
308
- };
309
- /**
310
- * @param {[type]}
311
- * @return {[type]}
312
- */
313
-
314
-
315
- wc_stripe.BaseGateway.prototype.on_token_received = function (paymentMethod) {
316
- this.payment_token_received = true;
317
- this.set_nonce(paymentMethod.id);
318
- this.process_checkout();
319
- };
320
-
321
- wc_stripe.BaseGateway.prototype.createPaymentRequest = function () {
322
- try {
323
- this.paymentRequest = stripe.paymentRequest(this.get_payment_request_options());
324
- } catch (err) {
325
- this.submit_error(err.message);
326
- return;
327
- }
328
-
329
- if (this.needs_shipping()) {
330
- this.paymentRequest.on('shippingaddresschange', this.update_shipping_address.bind(this));
331
- this.paymentRequest.on('shippingoptionchange', this.update_shipping_method.bind(this));
332
- }
333
-
334
- this.paymentRequest.on('paymentmethod', this.on_payment_method_received.bind(this));
335
- };
336
- /**
337
- * @return {[Object]}
338
- */
339
-
340
-
341
- wc_stripe.BaseGateway.prototype.get_payment_request_options = function () {
342
- var options = {
343
- country: this.params.country_code,
344
- currency: this.get_currency().toLowerCase(),
345
- total: {
346
- amount: this.get_total_price_cents(),
347
- label: this.params.total_label,
348
- pending: true
349
- },
350
- requestPayerName: true,
351
- requestPayerEmail: this.fields.requestFieldInWallet('billing_email'),
352
- requestPayerPhone: this.fields.requestFieldInWallet('billing_phone'),
353
- requestShipping: this.needs_shipping()
354
- };
355
- var displayItems = this.get_display_items(),
356
- shippingOptions = this.get_shipping_options();
357
-
358
- if (displayItems) {
359
- options.displayItems = displayItems;
360
- }
361
-
362
- if (this.needs_shipping() && shippingOptions) {
363
- options.shippingOptions = shippingOptions;
364
- }
365
-
366
- return options;
367
- };
368
- /**
369
- * @return {[Object]}
370
- */
371
-
372
-
373
- wc_stripe.BaseGateway.prototype.get_payment_request_update = function (data) {
374
- var options = {
375
- currency: this.get_currency().toLowerCase(),
376
- total: {
377
- amount: parseInt(this.get_total_price_cents()),
378
- label: this.params.total_label,
379
- pending: true
380
- }
381
- };
382
- var displayItems = this.get_display_items(),
383
- shippingOptions = this.get_shipping_options();
384
-
385
- if (displayItems) {
386
- options.displayItems = displayItems;
387
- }
388
-
389
- if (this.needs_shipping() && shippingOptions) {
390
- options.shippingOptions = shippingOptions;
391
- }
392
-
393
- if (data) {
394
- options = $.extend(true, {}, options, data);
395
- }
396
-
397
- return options;
398
- };
399
- /**
400
- * @return {[type]}
401
- */
402
-
403
-
404
- wc_stripe.BaseGateway.prototype.get_display_items = function () {
405
- return this.get_gateway_data().items;
406
- };
407
- /**
408
- * @return {[type]}
409
- */
410
-
411
-
412
- wc_stripe.BaseGateway.prototype.set_display_items = function (items) {
413
- var data = this.get_gateway_data();
414
- data.items = items;
415
- this.set_gateway_data(data);
416
- };
417
- /**
418
- * Return an array of shipping options for display in the Google payment sheet
419
- * @return {[type]}
420
- */
421
-
422
-
423
- wc_stripe.BaseGateway.prototype.get_shipping_options = function () {
424
- return this.get_gateway_data().shipping_options;
425
- };
426
- /**
427
- * Update the shipping options.
428
- * @param {[type]}
429
- */
430
-
431
-
432
- wc_stripe.BaseGateway.prototype.set_shipping_options = function (items) {
433
- var data = this.get_gateway_data();
434
- data.shipping_options = items;
435
- this.set_gateway_data(data);
436
- };
437
- /**
438
- * Maps an address from the Browser address format to WC format.
439
- * @param {[type]}
440
- * @return {[type]}
441
- */
442
-
443
-
444
- wc_stripe.BaseGateway.prototype.map_address = function (address) {
445
- return {
446
- city: address.city,
447
- postcode: address.postalCode,
448
- state: address.region,
449
- country: address.country
450
- };
451
- };
452
- /**
453
- * @param {[type]}
454
- * @return {[type]}
455
- */
456
-
457
-
458
- wc_stripe.BaseGateway.prototype.on_payment_method_received = function (paymentResponse) {
459
- try {
460
- this.payment_response = paymentResponse;
461
- this.populate_checkout_fields(paymentResponse);
462
- paymentResponse.complete("success");
463
- this.on_token_received(paymentResponse.paymentMethod);
464
- } catch (err) {
465
- window.alert(err);
466
- }
467
- };
468
- /**
469
- * @return {[type]}
470
- */
471
-
472
-
473
- wc_stripe.BaseGateway.prototype.populate_checkout_fields = function (data) {
474
- this.set_nonce(data.paymentMethod.id);
475
- this.update_addresses(data);
476
- };
477
- /**
478
- * @param {[type]}
479
- * @return {[type]}
480
- */
481
-
482
-
483
- wc_stripe.BaseGateway.prototype.update_addresses = function (data) {
484
- if (data.payerName) {
485
- this.fields.set('name', data.payerName, 'billing');
486
- }
487
-
488
- if (data.payerEmail) {
489
- this.fields.set('email', data.payerEmail, 'billing');
490
- }
491
-
492
- if (data.payerPhone) {
493
- this.fields.set('phone', data.payerPhone, 'billing');
494
- }
495
-
496
- if (data.shippingAddress) {
497
- this.populate_shipping_fields(data.shippingAddress);
498
- }
499
-
500
- if (data.paymentMethod.billing_details.address) {
501
- this.populate_billing_fields(data.paymentMethod.billing_details.address);
502
- }
503
- };
504
-
505
- wc_stripe.BaseGateway.prototype.populate_address_fields = function (address, prefix) {
506
- for (var k in address) {
507
- this.fields.set(k, address[k], prefix);
508
- }
509
- }
510
-
511
- wc_stripe.BaseGateway.prototype.populate_billing_fields = function (address) {
512
- this.populate_address_fields(address, 'billing');
513
- }
514
-
515
- wc_stripe.BaseGateway.prototype.populate_shipping_fields = function (address) {
516
- this.populate_address_fields(address, 'shipping');
517
- }
518
-
519
- wc_stripe.BaseGateway.prototype.address_mappings = function () {
520
- return new wc_stripe.CheckoutFields();
521
- };
522
-
523
- wc_stripe.BaseGateway.prototype.ajax_before_send = function (xhr) {
524
- if (this.params.user_id > 0) {
525
- xhr.setRequestHeader('X-WP-Nonce', this.params.rest_nonce);
526
- }
527
- };
528
- /**
529
- * @return {[type]}
530
- */
531
-
532
-
533
- wc_stripe.BaseGateway.prototype.process_checkout = function () {
534
- return new Promise(function () {
535
- this.block();
536
- $.ajax({
537
- url: this.params.routes.checkout,
538
- method: 'POST',
539
- dataType: 'json',
540
- data: $.extend({}, this.serialize_fields(), {
541
- payment_method: this.gateway_id,
542
- page_id: this.get_page()
543
- }),
544
- beforeSend: this.ajax_before_send.bind(this)
545
- }).done(function (result) {
546
- if (result.reload) {
547
- window.location.reload();
548
- return;
549
- }
550
-
551
- if (result.result === 'success') {
552
- window.location = result.redirect;
553
- } else {
554
- if (result.messages) {
555
- this.submit_error(result.messages);
556
- }
557
-
558
- this.unblock();
559
- }
560
- }.bind(this)).fail(function (xhr, textStatus, errorThrown) {
561
- this.unblock();
562
- this.submit_error(errorThrown);
563
- }.bind(this));
564
- }.bind(this));
565
- };
566
- /**
567
- * @return {[type]}
568
- */
569
-
570
-
571
- wc_stripe.BaseGateway.prototype.serialize_form = function ($form) {
572
- var formData = $form.find('input').filter(function (i, e) {
573
- if ($(e).is('[name^="add-to-cart"]')) {
574
- return false;
575
- }
576
-
577
- return true;
578
- }.bind(this)).serializeArray(),
579
- data = {};
580
-
581
- for (var i in formData) {
582
- var obj = formData[i];
583
- data[obj.name] = obj.value;
584
- }
585
-
586
- data.payment_method = this.gateway_id;
587
- return data;
588
- };
589
-
590
- wc_stripe.BaseGateway.prototype.serialize_fields = function () {
591
- return $.extend({}, this.fields.toJson(), $(document.body).triggerHandler('wc_stripe_process_checkout_data', [this, this.fields]));
592
- };
593
- /**
594
- * @param {[type]}
595
- * @return {[type]}
596
- */
597
-
598
-
599
- wc_stripe.BaseGateway.prototype.map_shipping_methods = function (shippingData) {
600
- var methods = {};
601
-
602
- if (shippingData !== "default") {
603
- var matches = shippingData.match(/^([\w+]):(.+)$/);
604
-
605
- if (matches.length > 1) {
606
- methods[matches[1]] = matches[2];
607
- }
608
- }
609
-
610
- return methods;
611
- };
612
- /**
613
- * [maybe_set_ship_to_different description]
614
- * @return {[type]} [description]
615
- */
616
-
617
-
618
- wc_stripe.BaseGateway.prototype.maybe_set_ship_to_different = function () {
619
- // if shipping and billing address are different,
620
- // set the ship to different address option.
621
- if ($('[name="ship_to_different_address"]').length) {
622
- $('[name="ship_to_different_address"]').prop('checked', this.get_address_field_hash("billing") !== this.get_address_field_hash("shipping")).trigger('change');
623
- }
624
- };
625
-
626
- wc_stripe.BaseGateway.prototype.update_shipping_address = function (ev) {
627
- return new Promise(function (resolve, reject) {
628
- $.ajax({
629
- url: this.params.routes.shipping_address,
630
- method: 'POST',
631
- dataType: 'json',
632
- data: {
633
- address: this.map_address(ev.shippingAddress),
634
- payment_method: this.gateway_id,
635
- page_id: this.get_page()
636
- },
637
- beforeSend: this.ajax_before_send.bind(this)
638
- }).done(function (response) {
639
- if (response.code) {
640
- ev.updateWith(response.data.newData);
641
- reject(response.data);
642
- } else {
643
- ev.updateWith(response.data.newData);
644
- this.fields.set('shipping_method', data.shipping_method);
645
- resolve(response.data);
646
- }
647
- }.bind(this)).fail(function () {
648
- }.bind(this));
649
- }.bind(this));
650
- };
651
- /**
652
- * @return {[@event]}
653
- */
654
-
655
-
656
- wc_stripe.BaseGateway.prototype.update_shipping_method = function (ev) {
657
- return new Promise(function (resolve, reject) {
658
- $.ajax({
659
- url: this.params.routes.shipping_method,
660
- method: 'POST',
661
- dataType: 'json',
662
- data: {
663
- shipping_method: ev.shippingOption.id,
664
- payment_method: this.gateway_id,
665
- page_id: this.get_page()
666
- },
667
- beforeSend: this.ajax_before_send.bind(this)
668
- }).done(function (response) {
669
- if (response.code) {
670
- ev.updateWith(response.data.newData);
671
- reject(response.data);
672
- } else {
673
- this.set_selected_shipping_methods(response.data.shipping_methods);
674
- ev.updateWith(response.data.newData);
675
- resolve(response.data);
676
- }
677
- }.bind(this)).fail(function (xhr, textStatus, errorThrown) {
678
- this.submit_error(errorThrown);
679
- }.bind(this));
680
- }.bind(this));
681
- };
682
- /********** Checkout Gateway ********/
683
-
684
- /**
685
- * @constructor
686
- */
687
-
688
-
689
- wc_stripe.CheckoutGateway = function () {
690
- this.message_container = 'li.payment_method_' + this.gateway_id;
691
- this.banner_container = 'li.banner_payment_method_' + this.gateway_id;
692
- $(document.body).on('update_checkout', this.update_checkout.bind(this));
693
- $(document.body).on('updated_checkout', this.updated_checkout.bind(this));
694
- $(document.body).on('cfw_updated_checkout', this.updated_checkout.bind(this));
695
- $(document.body).on('checkout_error', this.checkout_error.bind(this));
696
- $(this.token_selector).closest('form').on('checkout_place_order_' + this.gateway_id, this.checkout_place_order.bind(this)); // events for showing gateway payment buttons
697
-
698
- $(document.body).on('wc_stripe_new_method_' + this.gateway_id, this.on_show_new_methods.bind(this));
699
- $(document.body).on('wc_stripe_saved_method_' + this.gateway_id, this.on_show_saved_methods.bind(this));
700
- $(document.body).on('wc_stripe_payment_method_selected', this.on_payment_method_selected.bind(this));
701
-
702
- if (this.banner_enabled()) {
703
- if ($('.woocommerce-billing-fields').length) {
704
- $('.wc-stripe-banner-checkout').css('max-width', $('.woocommerce-billing-fields').outerWidth(true));
705
- }
706
- }
707
-
708
- this.order_review();
709
- };
710
-
711
- wc_stripe.CheckoutGateway.prototype.order_review = function () {
712
- var url = window.location.href;
713
- var matches = url.match(/order_review.+payment_method=([\w]+).+payment_nonce=(.+)/);
714
-
715
- if (matches && matches.length > 1) {
716
- var payment_method = matches[1],
717
- nonce = matches[2];
718
-
719
- if (this.gateway_id === payment_method) {
720
- this.payment_token_received = true;
721
- this.set_nonce(nonce);
722
- this.set_use_new_option(true);
723
- }
724
- }
725
- };
726
-
727
- wc_stripe.CheckoutGateway.prototype.update_shipping_address = function () {
728
- return wc_stripe.BaseGateway.prototype.update_shipping_address.apply(this, arguments).then(function (data) {
729
- // populate the checkout fields with the address
730
- this.populate_address_fields(data.address, this.get_shipping_prefix());
731
- this.fields.toFormFields({update_shipping_method: false});
732
- }.bind(this));
733
- }
734
-
735
- wc_stripe.CheckoutGateway.prototype.get_shipping_prefix = function () {
736
- if (this.needs_shipping() && $('[name="ship_to_different_address"]').length > 0 && $('[name="ship_to_different_address"]').is(':checked')) {
737
- return 'shipping';
738
- }
739
- return 'billing';
740
- }
741
-
742
- /**
743
- * Called on the WC updated_checkout event
744
- */
745
- wc_stripe.CheckoutGateway.prototype.updated_checkout = function () {
746
- };
747
-
748
- /**
749
- * Called on the WC update_checkout event
750
- */
751
- wc_stripe.CheckoutGateway.prototype.update_checkout = function () {
752
- };
753
- /**
754
- * Called on the WC checkout_error event
755
- */
756
-
757
-
758
- wc_stripe.CheckoutGateway.prototype.checkout_error = function () {
759
- if (this.has_checkout_error()) {
760
- this.payment_token_received = false;
761
- this.payment_response = null;
762
- this.show_payment_button();
763
- this.hide_place_order();
764
- }
765
- };
766
- /**
767
- *
768
- */
769
-
770
-
771
- wc_stripe.CheckoutGateway.prototype.is_valid_checkout = function () {
772
- if ($('[name="terms"]').length) {
773
- if (!$('[name="terms"]').is(':checked')) {
774
- return false;
775
- }
776
- }
777
-
778
- return true;
779
- };
780
- /**
781
- * Returns the selected payment gateway's id.
782
- *
783
- * @returns {String}
784
- */
785
-
786
-
787
- wc_stripe.CheckoutGateway.prototype.get_payment_method = function () {
788
- return $('[name="payment_method"]:checked').val();
789
- };
790
-
791
- wc_stripe.CheckoutGateway.prototype.set_use_new_option = function (bool) {
792
- $('#' + this.gateway_id + '_use_new').prop('checked', bool).trigger('change');
793
- };
794
- /**
795
- * Called on the WC checkout_place_order_{$gateway_id} event
796
- */
797
-
798
-
799
- wc_stripe.CheckoutGateway.prototype.checkout_place_order = function () {
800
- if (!this.is_valid_checkout()) {
801
- this.submit_error(this.params.messages.terms);
802
- return false;
803
- } else if (this.is_saved_method_selected()) {
804
- return true;
805
- }
806
-
807
- return this.payment_token_received;
808
- };
809
- /**
810
- * @param {[type]}
811
- * @return {[type]}
812
- */
813
-
814
-
815
- wc_stripe.CheckoutGateway.prototype.on_token_received = function (paymentMethod) {
816
- this.payment_token_received = true;
817
- this.set_nonce(paymentMethod.id);
818
- this.hide_payment_button();
819
- this.show_place_order();
820
- };
821
- /**
822
- * @return {[type]}
823
- */
824
-
825
-
826
- wc_stripe.CheckoutGateway.prototype.block = function () {
827
- if ($().block) {
828
- $('form.checkout').block({
829
- message: null,
830
- overlayCSS: {
831
- background: '#fff',
832
- opacity: 0.6
833
- }
834
- });
835
- }
836
-
837
- };
838
- /**
839
- * @return {[type]}
840
- */
841
-
842
-
843
- wc_stripe.CheckoutGateway.prototype.unblock = function () {
844
- if ($().block) {
845
- $('form.checkout').unblock();
846
- }
847
- };
848
-
849
- wc_stripe.CheckoutGateway.prototype.hide_place_order = function () {
850
- $('#place_order').addClass('wc-stripe-hide');
851
- };
852
- /**
853
- * @return {[type]}
854
- */
855
-
856
-
857
- wc_stripe.CheckoutGateway.prototype.show_place_order = function () {
858
- $('#place_order').removeClass('wc-stripe-hide');
859
- };
860
- /**
861
- * Method that should perform actions when the show new methods contain is made visible.
862
- * @param {[@event]}
863
- * @param {[String]}
864
- * @return {[type]}
865
- */
866
-
867
-
868
- wc_stripe.CheckoutGateway.prototype.on_show_new_methods = function () {
869
- if (this.payment_token_received) {
870
- this.show_place_order();
871
- this.hide_payment_button();
872
- } else {
873
- this.hide_place_order();
874
- this.show_payment_button();
875
- }
876
- };
877
- /**
878
- * Method that performs actions when the saved methods contains is visible.
879
- * @param {[type]}
880
- * @param {[type]}
881
- * @return {[type]}
882
- */
883
-
884
-
885
- wc_stripe.CheckoutGateway.prototype.on_show_saved_methods = function () {
886
- this.hide_payment_button();
887
- this.show_place_order();
888
- };
889
- /**
890
- * @return {[type]}
891
- */
892
-
893
-
894
- wc_stripe.CheckoutGateway.prototype.show_payment_button = function () {
895
- if (this.$button) {
896
- this.$button.show();
897
- }
898
- };
899
- /**
900
- * @return {[type]}
901
- */
902
-
903
-
904
- wc_stripe.CheckoutGateway.prototype.hide_payment_button = function () {
905
- if (this.$button) {
906
- this.$button.hide();
907
- }
908
- };
909
- /**
910
- * Wrapper for on_payment_method_selected that is safe to call since it won't trigger
911
- * any DOM events.
912
- * @return {[type]}
913
- */
914
-
915
-
916
- wc_stripe.CheckoutGateway.prototype.trigger_payment_method_selected = function () {
917
- this.on_payment_method_selected(null, $('[name="payment_method"]:checked').val());
918
- };
919
- /**
920
- * @param {[type]}
921
- * @param {[type]}
922
- * @return {[type]}
923
- */
924
-
925
-
926
- wc_stripe.CheckoutGateway.prototype.on_payment_method_selected = function (e, payment_method) {
927
- if (payment_method === this.gateway_id) {
928
- if (this.payment_token_received || this.is_saved_method_selected()) {
929
- this.hide_payment_button();
930
- this.show_place_order();
931
- } else {
932
- this.show_payment_button();
933
- this.hide_place_order();
934
- }
935
- } else {
936
- this.hide_payment_button();
937
-
938
- if (payment_method.indexOf('stripe_') < 0) {
939
- this.show_place_order();
940
- }
941
- }
942
- };
943
- /**
944
- * [Return true if the banner option has been enabled for the gateway.]
945
- * @return {[type]} [description]
946
- */
947
-
948
-
949
- wc_stripe.CheckoutGateway.prototype.banner_enabled = function () {
950
- return this.params.banner_enabled === '1';
951
- };
952
-
953
- wc_stripe.CheckoutGateway.prototype.checkout_fields_valid = function () {
954
- if (typeof wc_stripe_checkout_fields === 'undefined' || this.get_page() !== 'checkout') {
955
- return true;
956
- }
957
-
958
- var valid = true;
959
-
960
- function validateFields(prefix, fields) {
961
- for (var k in fields) {
962
- var field = fields[k];
963
-
964
- if (k.indexOf(prefix) > -1 && field.required) {
965
- if ($('#' + k).length) {
966
- var val = $('#' + k).val();
967
-
968
- if (typeof val === 'undefined' || val === null || val.length == 0) {
969
- valid = false;
970
- return;
971
- }
972
- }
973
- }
974
- }
975
- }
976
-
977
- validateFields('billing', wc_stripe_checkout_fields);
978
-
979
- if (this.needs_shipping() && $('#ship-to-different-address-checkbox').is(':checked')) {
980
- validateFields('shipping', wc_stripe_checkout_fields);
981
- }
982
-
983
- if (valid) {
984
- valid = this.is_valid_checkout();
985
- }
986
-
987
- return valid;
988
- };
989
- /************** Product Gateway ***************/
990
-
991
-
992
- wc_stripe.ProductGateway = function () {
993
- this.message_container = 'div.product'; // events
994
-
995
- $('form.cart').on('found_variation', this.found_variation.bind(this));
996
- $('form.cart').on('reset_data', this.reset_variation_data.bind(this));
997
- this.buttonWidth = $('form.cart div.quantity').outerWidth(true) + $('.single_add_to_cart_button').outerWidth();
998
- var marginLeft = $('.single_add_to_cart_button').css('marginLeft');
999
-
1000
- if (marginLeft) {
1001
- this.buttonWidth += parseInt(marginLeft.replace('px', ''));
1002
- }
1003
-
1004
- $(this.container).css('max-width', this.buttonWidth + 'px');
1005
- };
1006
- /**
1007
- * @return {[@int]}
1008
- */
1009
-
1010
-
1011
- wc_stripe.ProductGateway.prototype.get_quantity = function () {
1012
- return parseInt($('[name="quantity"]').val());
1013
- };
1014
- /**
1015
- * @param {[type]}
1016
- * @param {[type]}
1017
- */
1018
-
1019
-
1020
- wc_stripe.ProductGateway.prototype.set_rest_nonce = function (e, nonce) {
1021
- this.params.rest_nonce = nonce;
1022
- };
1023
- /**
1024
- * @param {[type]}
1025
- * @param {[type]}
1026
- * @return {[type]}
1027
- */
1028
-
1029
-
1030
- wc_stripe.ProductGateway.prototype.found_variation = function (e, variation) {
1031
- var data = this.get_gateway_data();
1032
- data.product.price = variation.display_price;
1033
- data.needs_shipping = !variation.is_virtual;
1034
- data.product.variation = variation;
1035
- this.set_gateway_data(data);
1036
- };
1037
- /**
1038
- * @return {[type]}
1039
- */
1040
-
1041
-
1042
- wc_stripe.ProductGateway.prototype.reset_variation_data = function () {
1043
- var data = this.get_product_data();
1044
- data.variation = false;
1045
- this.set_product_data(data);
1046
- this.disable_payment_button();
1047
- };
1048
- /**
1049
- * @return {[type]}
1050
- */
1051
-
1052
-
1053
- wc_stripe.ProductGateway.prototype.disable_payment_button = function () {
1054
- if (this.$button) {
1055
- this.get_button().prop('disabled', true).addClass('disabled');
1056
- }
1057
- };
1058
- /**
1059
- * @return {[type]}
1060
- */
1061
-
1062
-
1063
- wc_stripe.ProductGateway.prototype.enable_payment_button = function () {
1064
- if (this.$button) {
1065
- this.get_button().prop('disabled', false).removeClass('disabled');
1066
- }
1067
- };
1068
- /**
1069
- * @return {[type]}
1070
- */
1071
-
1072
-
1073
- wc_stripe.ProductGateway.prototype.get_button = function () {
1074
- return this.$button;
1075
- };
1076
- /**
1077
- * @return {Boolean}
1078
- */
1079
-
1080
-
1081
- wc_stripe.ProductGateway.prototype.is_variable_product = function () {
1082
- return $('[name="variation_id"]').length > 0;
1083
- };
1084
-
1085
- wc_stripe.ProductGateway.prototype.variable_product_selected = function () {
1086
- return this.get_product_data().variation !== false;
1087
- };
1088
- /**
1089
- * @return {[type]}
1090
- */
1091
-
1092
-
1093
- wc_stripe.ProductGateway.prototype.get_product_data = function () {
1094
- return this.get_gateway_data().product;
1095
- };
1096
- /**
1097
- * @return {[type]}
1098
- */
1099
-
1100
-
1101
- wc_stripe.ProductGateway.prototype.set_product_data = function (product) {
1102
- var data = this.get_gateway_data();
1103
- data.product = product;
1104
- this.set_gateway_data(data);
1105
- };
1106
- /**
1107
- * Add a product to the WC shopping cart
1108
- */
1109
-
1110
-
1111
- wc_stripe.ProductGateway.prototype.add_to_cart = function () {
1112
- return new Promise(function (resolve, reject) {
1113
- this.block();
1114
- $.ajax({
1115
- url: this.params.routes.add_to_cart,
1116
- method: 'POST',
1117
- dataType: 'json',
1118
- data: {
1119
- product_id: this.get_product_data().id,
1120
- variation_id: this.is_variable_product() ? $('[name="variation_id"]').val() : 0,
1121
- qty: $('[name="quantity"]').val(),
1122
- payment_method: this.gateway_id,
1123
- page_id: this.get_page()
1124
- },
1125
- beforeSend: this.ajax_before_send.bind(this)
1126
- }).done(function (response) {
1127
- this.unblock();
1128
-
1129
- if (response.code) {
1130
- this.submit_error(response.message);
1131
- reject(response);
1132
- } else {
1133
- this.set_total_price(response.data.total);
1134
- this.set_total_price_cents(response.data.totalCents);
1135
- this.set_display_items(response.data.displayItems);
1136
- resolve(response.data);
1137
- }
1138
- }.bind(this)).fail(function (xhr, textStatus, errorThrown) {
1139
- this.unblock();
1140
- this.submit_error(errorThrown);
1141
- }.bind(this));
1142
- }.bind(this));
1143
- };
1144
-
1145
- wc_stripe.ProductGateway.prototype.cart_calculation = function (variation_id) {
1146
- return new Promise(function (resolve, reject) {
1147
- $.ajax({
1148
- url: this.params.routes.cart_calculation,
1149
- method: 'POST',
1150
- dataType: 'json',
1151
- data: {
1152
- product_id: this.get_product_data().id,
1153
- variation_id: this.is_variable_product() && variation_id ? variation_id : 0,
1154
- qty: $('[name="quantity"]').val(),
1155
- payment_method: this.gateway_id
1156
- },
1157
- beforeSend: this.ajax_before_send.bind(this)
1158
- }).done(function (response) {
1159
- if (response.code) {
1160
- this.cart_calculation_error = true;
1161
- reject(response);
1162
- } else {
1163
- this.set_total_price(response.data.total);
1164
- this.set_total_price_cents(response.data.totalCents);
1165
- this.set_display_items(response.data.displayItems);
1166
- resolve(response.data);
1167
- }
1168
- }.bind(this)).fail(function () {
1169
- }.bind(this));
1170
- }.bind(this));
1171
- };
1172
- /************* Cart Gateway *************/
1173
-
1174
- /**
1175
- * @constructor
1176
- */
1177
-
1178
-
1179
- wc_stripe.CartGateway = function () {
1180
- this.message_container = 'div.woocommerce'; // cart events
1181
-
1182
- $(document.body).on('updated_wc_div', this.updated_html.bind(this));
1183
- $(document.body).on('updated_cart_totals', this.updated_html.bind(this));
1184
- $(document.body).on('wc_cart_emptied', this.cart_emptied.bind(this));
1185
- };
1186
- /**
1187
- * @param {[type]}
1188
- * @return {[type]}
1189
- */
1190
-
1191
-
1192
- wc_stripe.CartGateway.prototype.submit_error = function (message) {
1193
- this.submit_message(this.get_error_message(message));
1194
- };
1195
- /**
1196
- * @param {[@event]}
1197
- * @return {[null]}
1198
- */
1199
-
1200
-
1201
- wc_stripe.CartGateway.prototype.updated_html = function (e) {
1202
- };
1203
-
1204
- wc_stripe.CartGateway.prototype.cart_emptied = function (e) {
1205
- };
1206
-
1207
- wc_stripe.CartGateway.prototype.add_cart_totals_class = function () {
1208
- $('.cart_totals').addClass('stripe_cart_gateway_active');
1209
- };
1210
-
1211
- /************* Google Pay Mixins **************/
1212
-
1213
- wc_stripe.GooglePay = function () {
1214
- };
1215
-
1216
- var googlePayBaseRequest = {
1217
- apiVersion: 2,
1218
- apiVersionMinor: 0
1219
- };
1220
- var allowedCardNetworks = ["AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA"];
1221
- var allowedCardAuthMethods = ["PAN_ONLY"];
1222
- var baseCardPaymentMethod = {
1223
- type: 'CARD',
1224
- parameters: {
1225
- allowedAuthMethods: allowedCardAuthMethods,
1226
- allowedCardNetworks: allowedCardNetworks
1227
- }
1228
- };
1229
- /**
1230
- * Populate the WC checkout fields.
1231
- * @param {[type]}
1232
- * @return {[type]}
1233
- */
1234
-
1235
- wc_stripe.GooglePay.prototype.update_addresses = function (paymentData) {
1236
- this.populate_billing_fields(paymentData.paymentMethodData.info.billingAddress);
1237
-
1238
- if (paymentData.shippingAddress) {
1239
- this.populate_shipping_fields(paymentData.shippingAddress);
1240
- }
1241
-
1242
- if (paymentData.email) {
1243
- this.fields.set('email', paymentData.email, 'billing');
1244
- }
1245
- };
1246
- /**
1247
- * @param {[type]}
1248
- * @return {[type]}
1249
- */
1250
-
1251
-
1252
- wc_stripe.GooglePay.prototype.map_address = function (address) {
1253
- return {
1254
- city: address.locality,
1255
- postcode: address.postalCode,
1256
- state: address.administrativeArea,
1257
- country: address.countryCode
1258
- };
1259
- };
1260
- /**
1261
- * @param {[type]}
1262
- * @return {[type]}
1263
- */
1264
-
1265
-
1266
- wc_stripe.GooglePay.prototype.update_payment_data = function (data) {
1267
- return new Promise(function (resolve, reject) {
1268
- var shipping_method = data.shippingOptionData.id == 'default' ? null : data.shippingOptionData.id;
1269
- $.when($.ajax({
1270
- url: this.params.routes.payment_data,
1271
- dataType: 'json',
1272
- method: 'POST',
1273
- data: {
1274
- shipping_address: this.map_address(data.shippingAddress),
1275
- shipping_method: shipping_method,
1276
- page_id: this.get_page()
1277
- },
1278
- beforeSend: this.ajax_before_send.bind(this)
1279
- })).done(function (response) {
1280
- if (response.code) {
1281
- reject(response.data.data);
1282
- } else {
1283
- resolve(response.data);
1284
- }
1285
- }.bind(this)).fail(function () {
1286
- reject();
1287
- }.bind(this));
1288
- }.bind(this));
1289
- };
1290
- /**
1291
- * @param {[type]}
1292
- * @return {[type]}
1293
- */
1294
-
1295
-
1296
- wc_stripe.GooglePay.prototype.on_payment_data_changed = function (address) {
1297
- return new Promise(function (resolve) {
1298
- this.update_payment_data(address).then(function (response) {
1299
- resolve(response.paymentRequestUpdate);
1300
- this.set_selected_shipping_methods(response.shipping_methods);
1301
- this.payment_data_updated(response, address);
1302
- }.bind(this))['catch'](function (data) {
1303
- resolve(data);
1304
- }.bind(this));
1305
- }.bind(this));
1306
- };
1307
- /**
1308
- * Convenience method so that gateway can perform actions after the payment data
1309
- * has been updated.
1310
- * @param {[type]}
1311
- * @return {[type]}
1312
- */
1313
-
1314
-
1315
- wc_stripe.GooglePay.prototype.payment_data_updated = function (response) {
1316
- };
1317
- /**
1318
- * @return {[type]}
1319
- */
1320
-
1321
-
1322
- wc_stripe.GooglePay.prototype.get_merchant_info = function () {
1323
- var options = {
1324
- merchantId: this.params.merchant_id,
1325
- merchantName: this.params.merchant_name
1326
- };
1327
-
1328
- if (this.params.environment === 'TEST') {
1329
- delete options.merchantId;
1330
- }
1331
-
1332
- return options;
1333
- };
1334
- /**
1335
- * @return {[type]}
1336
- */
1337
-
1338
-
1339
- wc_stripe.GooglePay.prototype.get_payment_options = function () {
1340
- var options = {
1341
- environment: this.params.environment,
1342
- merchantInfo: this.get_merchant_info()
1343
- };
1344
-
1345
- if (this.needs_shipping()) {
1346
- options.paymentDataCallbacks = {
1347
- onPaymentDataChanged: this.on_payment_data_changed.bind(this),
1348
- onPaymentAuthorized: function (data) {
1349
- return new Promise(function (resolve, reject) {
1350
- resolve({
1351
- transactionState: "SUCCESS"
1352
- });
1353
- }.bind(this));
1354
- }.bind(this)
1355
- };
1356
- } else {
1357
- options.paymentDataCallbacks = {
1358
- onPaymentAuthorized: function onPaymentAuthorized(data) {
1359
- return new Promise(function (resolve, reject) {
1360
- resolve({
1361
- transactionState: "SUCCESS"
1362
- });
1363
- }.bind(this));
1364
- }
1365
- };
1366
- }
1367
-
1368
- return options;
1369
- };
1370
- /**
1371
- * @return {[type]}
1372
- */
1373
-
1374
-
1375
- wc_stripe.GooglePay.prototype.build_payment_request = function () {
1376
- var request = $.extend({}, googlePayBaseRequest, {
1377
- emailRequired: function () {
1378
- if ('checkout' === this.get_page()) {
1379
- return this.fields.required('billing_email') && this.fields.isEmpty('billing_email');
1380
- } else if ('order_pay' === this.get_page()) {
1381
- return false;
1382
- }
1383
-
1384
- return this.fields.required('billing_email');
1385
- }.bind(this)(),
1386
- merchantInfo: this.get_merchant_info(),
1387
- allowedPaymentMethods: [$.extend({
1388
- type: "CARD",
1389
- tokenizationSpecification: {
1390
- type: "PAYMENT_GATEWAY",
1391
- parameters: {
1392
- gateway: 'stripe',
1393
- "stripe:version": "2018-10-31",
1394
- "stripe:publishableKey": this.params.api_key
1395
- }
1396
- }
1397
- }, baseCardPaymentMethod)],
1398
- shippingAddressRequired: this.needs_shipping(),
1399
- transactionInfo: {
1400
- currencyCode: this.get_currency(),
1401
- totalPriceStatus: "ESTIMATED",
1402
- totalPrice: this.get_total_price().toString(),
1403
- displayItems: this.get_display_items(),
1404
- totalPriceLabel: this.params.total_price_label
1405
- }
1406
- });
1407
- request.allowedPaymentMethods[0].parameters['billingAddressRequired'] = true;
1408
- request.allowedPaymentMethods[0].parameters['billingAddressParameters'] = {
1409
- format: "FULL",
1410
- phoneNumberRequired: function () {
1411
- if ('checkout' === this.get_page()) {
1412
- return this.fields.required('billing_phone') && this.fields.isEmpty('billing_phone');
1413
- } else if ('order_pay' === this.get_page()) {
1414
- return false;
1415
- }
1416
-
1417
- return this.fields.required('billing_phone');
1418
- }.bind(this)()
1419
- };
1420
-
1421
- if (this.needs_shipping()) {
1422
- request['shippingAddressParameters'] = {};
1423
- request['shippingOptionRequired'] = true;
1424
- request['shippingOptionParameters'] = {
1425
- shippingOptions: this.get_shipping_options()
1426
- };
1427
- request['callbackIntents'] = ["SHIPPING_ADDRESS", "SHIPPING_OPTION", "PAYMENT_AUTHORIZATION"];
1428
- } else {
1429
- request['callbackIntents'] = ["PAYMENT_AUTHORIZATION"];
1430
- }
1431
-
1432
- return request;
1433
- };
1434
- /**
1435
- * @return {[type]}
1436
- */
1437
-
1438
-
1439
- wc_stripe.GooglePay.prototype.createPaymentsClient = function () {
1440
- this.paymentsClient = new google.payments.api.PaymentsClient(this.get_payment_options());
1441
- };
1442
- /**
1443
- * @return {Promise}
1444
- */
1445
-
1446
-
1447
- wc_stripe.GooglePay.prototype.isReadyToPay = function () {
1448
- return new Promise(function (resolve) {
1449
- var isReadyToPayRequest = $.extend({}, googlePayBaseRequest);
1450
- isReadyToPayRequest.allowedPaymentMethods = [baseCardPaymentMethod];
1451
- this.paymentsClient.isReadyToPay(isReadyToPayRequest).then(function () {
1452
- this.can_pay = true;
1453
- this.create_button();
1454
- resolve();
1455
- }.bind(this))["catch"](function (err) {
1456
- this.submit_error(err);
1457
- }.bind(this));
1458
- }.bind(this));
1459
- };
1460
-
1461
- wc_stripe.GooglePay.prototype.create_button = function () {
1462
- if (this.$button) {
1463
- this.$button.remove();
1464
- }
1465
-
1466
- this.$button = $(this.paymentsClient.createButton({
1467
- onClick: this.start.bind(this),
1468
- buttonColor: this.params.button_color,
1469
- buttonType: this.params.button_style
1470
- }));
1471
- this.$button.addClass('gpay-button-container');
1472
- };
1473
- /**
1474
- * @return {[type]}
1475
- */
1476
-
1477
-
1478
- wc_stripe.GooglePay.prototype.start = function () {
1479
- // always recreate the paymentClient to ensure latest data is used.
1480
- this.createPaymentsClient();
1481
- this.paymentsClient.loadPaymentData(this.build_payment_request()).then(function (paymentData) {
1482
- var data = JSON.parse(paymentData.paymentMethodData.tokenizationData.token);
1483
- this.update_addresses(paymentData);
1484
- this.on_token_received(data);
1485
- }.bind(this))["catch"](function (err) {
1486
- if (err.statusCode === "CANCELED") {
1487
- return;
1488
- }
1489
-
1490
- if (err.statusMessage && err.statusMessage.indexOf("paymentDataRequest.callbackIntent") > -1) {
1491
- this.submit_error_code("DEVELOPER_ERROR_WHITELIST");
1492
- } else {
1493
- this.submit_error(err.statusMessage);
1494
- }
1495
- }.bind(this));
1496
- };
1497
-
1498
- wc_stripe.ApplePay = function () {
1499
- };
1500
-
1501
- wc_stripe.ApplePay.prototype.initialize = function () {
1502
- var selector = '.apple-pay-button';
1503
-
1504
- if (['checkout', 'order_pay'].indexOf(this.get_page()) < 0) {
1505
- selector = this.container + ' .apple-pay-button';
1506
- }
1507
-
1508
- $(document.body).on('click', selector, this.start.bind(this));
1509
- this.createPaymentRequest();
1510
- this.canMakePayment();
1511
- };
1512
-
1513
- wc_stripe.ApplePay.prototype.create_button = function () {
1514
- if (this.$button) {
1515
- this.$button.remove();
1516
- }
1517
-
1518
- this.$button = $(this.params.button);
1519
- this.append_button();
1520
- };
1521
-
1522
- wc_stripe.ApplePay.prototype.canMakePayment = function () {
1523
- return new Promise(function (resolve) {
1524
- this.paymentRequest.canMakePayment().then(function (result) {
1525
- if (result && result.applePay) {
1526
- this.can_pay = true;
1527
- this.create_button();
1528
- $(this.container).show();
1529
- resolve(result);
1530
- }
1531
- }.bind(this));
1532
- }.bind(this));
1533
- };
1534
-
1535
- wc_stripe.ApplePay.prototype.start = function (e) {
1536
- e.preventDefault();
1537
- this.paymentRequest.update(this.get_payment_request_update({
1538
- total: {
1539
- pending: false
1540
- }
1541
- }));
1542
- this.paymentRequest.show();
1543
- };
1544
-
1545
- /*********** PaymentRequest *********/
1546
- wc_stripe.PaymentRequest = function () {
1547
- };
1548
-
1549
- wc_stripe.PaymentRequest.prototype.initialize = function () {
1550
- this.createPaymentRequest();
1551
- this.canMakePayment();
1552
- this.createPaymentRequestButton();
1553
- this.paymentRequestButton.on('click', this.button_click.bind(this));
1554
- };
1555
-
1556
- wc_stripe.PaymentRequest.prototype.button_click = function (event) {
1557
- };
1558
-
1559
- wc_stripe.PaymentRequest.prototype.createPaymentRequestButton = function () {
1560
- this.paymentRequestButton = this.elements.create("paymentRequestButton", {
1561
- paymentRequest: this.paymentRequest,
1562
- style: {
1563
- paymentRequestButton: {
1564
- type: this.params.button.type,
1565
- theme: this.params.button.theme,
1566
- height: this.params.button.height
1567
- }
1568
- }
1569
- });
1570
- };
1571
-
1572
- wc_stripe.PaymentRequest.prototype.canMakePayment = function () {
1573
- return new Promise(function (resolve) {
1574
- this.paymentRequest.canMakePayment().then(function (result) {
1575
- if (result && !result.applePay) {
1576
- this.can_pay = true;
1577
- this.create_button();
1578
- $(this.container).show();
1579
- resolve(result);
1580
- }
1581
- }.bind(this));
1582
- }.bind(this));
1583
- };
1584
-
1585
- wc_stripe.PaymentRequest.prototype.create_button = function () {
1586
- this.paymentRequestButton.mount('#wc-stripe-payment-request-container');
1587
- };
1588
-
1589
- wc_stripe.CheckoutFields = function (params, page) {
1590
- this.params = params;
1591
- this.page = page;
1592
- this.fields = new Map(Object.keys(this.params).map(function (k) {
1593
- return [k, this.params[k].value];
1594
- }.bind(this)));
1595
-
1596
- if ('checkout' === page) {
1597
- $('form.checkout').on('change', '.input-text, select', this.onChange.bind(this));
1598
- $('form.checkout').on('change', '[name="ship_to_different_address"]', this.on_ship_to_address_change.bind(this));
1599
- this.init_i18n();
1600
- }
1601
- };
1602
-
1603
- wc_stripe.CheckoutFields.prototype.init_i18n = function () {
1604
- if (typeof wc_address_i18n_params !== 'undefined') {
1605
- this.locales = $.parseJSON(wc_address_i18n_params.locale.replace(/&quot;/g, '"'));
1606
- } else {
1607
- this.locales = null;
1608
- }
1609
- };
1610
-
1611
- wc_stripe.CheckoutFields.prototype.onChange = function (e) {
1612
- try {
1613
- var name = e.currentTarget.name,
1614
- value = e.currentTarget.value;
1615
- this.fields.set(name, value);
1616
-
1617
- if (name === 'billing_country' || name === 'shipping_country') {
1618
- this.update_required_fields(value, name);
1619
- }
1620
- } catch (err) {
1621
- console.log(err);
1622
- }
1623
- };
1624
-
1625
- wc_stripe.CheckoutFields.prototype.update_required_fields = function (country, name) {
1626
- if (this.locales) {
1627
- var prefix = name.indexOf('billing_') > -1 ? 'billing_' : 'shipping_';
1628
- var locale = typeof this.locales[country] !== 'undefined' ? this.locales[country] : this.locales['default'];
1629
- var fields = $.extend(true, {}, this.locales['default'], locale);
1630
-
1631
- for (var k in fields) {
1632
- var k2 = prefix + k;
1633
-
1634
- if (this.params[k2]) {
1635
- this.params[k2] = $.extend(true, {}, this.params[k2], fields[k]);
1636
- }
1637
- }
1638
- }
1639
- };
1640
-
1641
- wc_stripe.CheckoutFields.prototype.on_ship_to_address_change = function (e) {
1642
- if ($(e.currentTarget).is(':checked')) {
1643
- this.update_required_fields($('shipping_country'), 'shipping_country');
1644
- }
1645
- };
1646
-
1647
- wc_stripe.CheckoutFields.prototype.requestFieldInWallet = function (key) {
1648
- if ('checkout' === this.page) {
1649
- return this.required(key) && this.isEmpty(key);
1650
- } else if ('order_pay' === this.page) {
1651
- return false;
1652
- }
1653
-
1654
- return this.required(key);
1655
- };
1656
-
1657
- wc_stripe.CheckoutFields.prototype.set = function (k, v, prefix) {
1658
- if (this[k] && typeof this[k] === 'function') {
1659
- this[k]().set.call(this, v, prefix);
1660
- } else {
1661
- this.fields.set(k, v);
1662
- }
1663
- };
1664
-
1665
- wc_stripe.CheckoutFields.prototype.get = function (k, prefix) {
1666
- if (this[k] && typeof this[k] === 'function') {
1667
- var value = this[k]().get.call(this, prefix);
1668
- } else {
1669
- var value = this.fields.get(k);
1670
-
1671
- if (typeof value === 'undefined' || value === null || value === '') {
1672
- if (typeof prefix !== 'undefined') {
1673
- value = prefix;
1674
- }
1675
- }
1676
- }
1677
-
1678
- return typeof value === 'undefined' ? '' : value;
1679
- };
1680
- /**
1681
- * Return true if the field is required
1682
- * @param k
1683
- * @returns boolean
1684
- */
1685
-
1686
-
1687
- wc_stripe.CheckoutFields.prototype.required = function (k) {
1688
- if (this.params[k]) {
1689
- if (typeof this.params[k].required !== 'undefined') {
1690
- return this.params[k].required;
1691
- }
1692
- }
1693
-
1694
- return false;
1695
- };
1696
-
1697
- wc_stripe.CheckoutFields.prototype.isEmpty = function (k) {
1698
- if (this.fields.has(k)) {
1699
- var value = this.fields.get(k);
1700
- return typeof value === 'undefined' || value === null || typeof value === 'string' && value.trim().length === 0;
1701
- }
1702
-
1703
- return true;
1704
- };
1705
-
1706
- wc_stripe.CheckoutFields.prototype.name = function () {
1707
- return {
1708
- set: function set(v, prefix) {
1709
- var name = v.split(" ");
1710
- this.fields.set(prefix + '_first_name', name[0]);
1711
- this.fields.set(prefix + '_last_name', name[1]);
1712
- },
1713
- get: function get(prefix) {
1714
- return this.fields.get(prefix + '_first_name') + ' ' + this.fields.get(prefix + '_last_name');
1715
- }
1716
- };
1717
- };
1718
-
1719
- wc_stripe.CheckoutFields.prototype.payerName = function () {
1720
- return wc_stripe.CheckoutFields.prototype.name.apply(this, arguments);
1721
- };
1722
-
1723
- wc_stripe.CheckoutFields.prototype.email = function () {
1724
- return {
1725
- set: function set(v, prefix) {
1726
- this.fields.set(prefix + '_email', v);
1727
- },
1728
- get: function get(prefix) {
1729
- return this.fields.get(prefix + '_email');
1730
- }
1731
- };
1732
- };
1733
-
1734
- wc_stripe.CheckoutFields.prototype.payerEmail = function () {
1735
- return wc_stripe.CheckoutFields.prototype.email.apply(this, arguments);
1736
- };
1737
-
1738
- wc_stripe.CheckoutFields.prototype.phone = function () {
1739
- return {
1740
- set: function set(v, prefix) {
1741
- this.fields.set(prefix + '_phone', v);
1742
- },
1743
- get: function get(prefix) {
1744
- return this.fields.get(prefix + '_phone');
1745
- }
1746
- };
1747
- };
1748
-
1749
- wc_stripe.CheckoutFields.prototype.payerPhone = function () {
1750
- return wc_stripe.CheckoutFields.prototype.phone.apply(this, arguments);
1751
- };
1752
-
1753
- wc_stripe.CheckoutFields.prototype.phoneNumber = function () {
1754
- return wc_stripe.CheckoutFields.prototype.phone.apply(this, arguments);
1755
- };
1756
-
1757
- wc_stripe.CheckoutFields.prototype.recipient = function () {
1758
- return {
1759
- set: function set(v, prefix) {
1760
- var name = v.split(" ");
1761
-
1762
- if (name.length > 0) {
1763
- this.fields.set(prefix + '_first_name', name[0]);
1764
- }
1765
-
1766
- if (name.length > 1) {
1767
- this.fields.set(prefix + '_last_name', name[1]);
1768
- }
1769
- },
1770
- get: function get(prefix) {
1771
- return this.fields.get(prefix + '_first_name') + ' ' + this.fields.get(prefix + '_last_name');
1772
- }
1773
- };
1774
- };
1775
-
1776
- wc_stripe.CheckoutFields.prototype.country = function () {
1777
- return {
1778
- set: function set(v, prefix) {
1779
- this.fields.set(prefix + '_country', v);
1780
- },
1781
- get: function get(prefix) {
1782
- return this.fields.get(prefix + '_country');
1783
- }
1784
- };
1785
- };
1786
-
1787
- wc_stripe.CheckoutFields.prototype.countryCode = function () {
1788
- return wc_stripe.CheckoutFields.prototype.country.apply(this, arguments);
1789
- };
1790
-
1791
- wc_stripe.CheckoutFields.prototype.address1 = function () {
1792
- return {
1793
- set: function set(v, prefix) {
1794
- this.fields.set(prefix + '_address_1', v);
1795
- },
1796
- get: function get(prefix) {
1797
- return this.fields.get(prefix + '_address_1');
1798
- }
1799
- };
1800
- };
1801
-
1802
- wc_stripe.CheckoutFields.prototype.address2 = function () {
1803
- return {
1804
- set: function set(v, prefix) {
1805
- this.fields.set(prefix + '_address_2', v);
1806
- },
1807
- get: function get(prefix) {
1808
- this.fields.get(prefix + '_address_2');
1809
- }
1810
- };
1811
- };
1812
-
1813
- wc_stripe.CheckoutFields.prototype.line1 = function () {
1814
- return wc_stripe.CheckoutFields.prototype.address1.apply(this, arguments);
1815
- };
1816
-
1817
- wc_stripe.CheckoutFields.prototype.line2 = function () {
1818
- return wc_stripe.CheckoutFields.prototype.address2.apply(this, arguments);
1819
- };
1820
-
1821
- wc_stripe.CheckoutFields.prototype.addressLine = function () {
1822
- return {
1823
- set: function set(v, prefix) {
1824
- if (v.length > 0) {
1825
- this.fields.set(prefix + '_address_1', v[0]);
1826
- }
1827
-
1828
- if (v.length > 1) {
1829
- this.fields.set(prefix + '_address_2', v[1]);
1830
- }
1831
- },
1832
- get: function get(prefix) {
1833
- return [this.fields.get(prefix + '_address_1'), this.fields.get(prefix + '_address_2')];
1834
- }
1835
- };
1836
- };
1837
-
1838
- wc_stripe.CheckoutFields.prototype.state = function () {
1839
- return {
1840
- set: function set(v, prefix) {
1841
- v = v.toUpperCase();
1842
- if (v.length > 2 && this.page === 'checkout') {
1843
- $('#' + prefix + '_state option').each(function () {
1844
- var $option = $(this);
1845
- var state = $option.text().toUpperCase();
1846
- if (v === state) {
1847
- v = $option.val();
1848
- }
1849
- });
1850
- }
1851
- this.fields.set(prefix + '_state', v);
1852
- },
1853
- get: function get(prefix) {
1854
- return this.fields.get(prefix + '_state');
1855
- }
1856
- };
1857
- };
1858
-
1859
- wc_stripe.CheckoutFields.prototype.region = function () {
1860
- return wc_stripe.CheckoutFields.prototype.state.apply(this, arguments);
1861
- };
1862
-
1863
- wc_stripe.CheckoutFields.prototype.administrativeArea = function () {
1864
- return wc_stripe.CheckoutFields.prototype.state.apply(this, arguments);
1865
- };
1866
-
1867
- wc_stripe.CheckoutFields.prototype.city = function () {
1868
- return {
1869
- set: function set(v, prefix) {
1870
- this.fields.set(prefix + '_city', v);
1871
- },
1872
- get: function get(prefix) {
1873
- this.fields.get(prefix + '_city');
1874
- }
1875
- };
1876
- };
1877
-
1878
- wc_stripe.CheckoutFields.prototype.locality = function () {
1879
- return wc_stripe.CheckoutFields.prototype.city.apply(this, arguments);
1880
- };
1881
-
1882
- wc_stripe.CheckoutFields.prototype.postcode = function () {
1883
- return {
1884
- set: function set(v, prefix) {
1885
- this.fields.set(prefix + '_postcode', v);
1886
- },
1887
- get: function get(prefix) {
1888
- this.fields.get(prefix + '_postcode');
1889
- }
1890
- };
1891
- };
1892
-
1893
- wc_stripe.CheckoutFields.prototype.postal_code = function () {
1894
- return wc_stripe.CheckoutFields.prototype.postcode.apply(this, arguments);
1895
- }
1896
-
1897
- wc_stripe.CheckoutFields.prototype.postalCode = function () {
1898
- return wc_stripe.CheckoutFields.prototype.postcode.apply(this, arguments);
1899
- };
1900
- /**
1901
- * Serialize the fields into an expected format
1902
- */
1903
-
1904
-
1905
- wc_stripe.CheckoutFields.prototype.toJson = function () {
1906
- var data = {};
1907
- this.fields.forEach(function (value, key) {
1908
- data[key] = value;
1909
- });
1910
- return data;
1911
- };
1912
-
1913
- wc_stripe.CheckoutFields.prototype.toFormFields = function (args) {
1914
- var changes = [];
1915
- this.fields.forEach(function (value, key) {
1916
- var name = '[name="' + key + '"]';
1917
-
1918
- if ($(name).length && value !== '') {
1919
- if ($(name).val() !== value && $(name).is('select')) {
1920
- changes.push(name);
1921
- }
1922
-
1923
- $(name).val(value);
1924
- }
1925
- });
1926
- if (changes.length > 0) {
1927
- $(changes.join(',')).trigger('change');
1928
- }
1929
- if (typeof args !== 'undefined') {
1930
- $(document.body).trigger('update_checkout', args);
1931
- }
1932
- };
1933
-
1934
- try {
1935
- stripe = Stripe(wc_stripe_params_v3.api_key, {
1936
- stripeAccount: wc_stripe_params_v3.account
1937
- });
1938
- } catch (error) {
1939
- window.alert(error);
1940
- console.log(error);
1941
- return;
1942
- }
1943
-
1944
- var checkoutFields = new wc_stripe.CheckoutFields(wc_stripe_checkout_fields, wc_stripe_params_v3.page);
1945
- })(window, jQuery);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ (function (window, $) {
2
+ window.wc_stripe = {};
3
+ var stripe = null;
4
+
5
+ if (typeof wc_stripe_checkout_fields === 'undefined') {
6
+ window.wc_stripe_checkout_fields = [];
7
+ }
8
+
9
+ wc_stripe.BaseGateway = function (params, container) {
10
+ this.params = params;
11
+ this.gateway_id = this.params.gateway_id;
12
+ this.container = typeof container === 'undefined' ? 'li.payment_method_'.concat(this.gateway_id) : container;
13
+
14
+ if (!$(this.container).length) {
15
+ this.container = '.payment_method_'.concat(this.gateway_id);
16
+ }
17
+
18
+ this.token_selector = this.params.token_selector;
19
+ this.saved_method_selector = this.params.saved_method_selector;
20
+ this.payment_token_received = false;
21
+ this.stripe = stripe;
22
+ this.elements = stripe.elements($.extend({}, {
23
+ locale: 'auto'
24
+ }, this.get_element_options()));
25
+ this.fields = checkoutFields;
26
+ this.initialize();
27
+ };
28
+
29
+ wc_stripe.BaseGateway.prototype.get_page = function () {
30
+ return wc_stripe_params_v3.page;
31
+ };
32
+
33
+ wc_stripe.BaseGateway.prototype.set_nonce = function (value) {
34
+ this.fields.set(this.gateway_id + '_token_key', value);
35
+ $(this.token_selector).val(value);
36
+ };
37
+ /**
38
+ * [get_element_options description]
39
+ * @return {[type]} [description]
40
+ */
41
+
42
+
43
+ wc_stripe.BaseGateway.prototype.get_element_options = function () {
44
+ return {};
45
+ };
46
+
47
+ wc_stripe.BaseGateway.prototype.initialize = function () {
48
+ };
49
+ /**
50
+ * @return {[type]}
51
+ */
52
+
53
+
54
+ wc_stripe.BaseGateway.prototype.create_button = function () {
55
+ };
56
+ /**
57
+ * @returns {Boolean}
58
+ */
59
+
60
+
61
+ wc_stripe.BaseGateway.prototype.is_gateway_selected = function () {
62
+ return $('[name="payment_method"]:checked').val() === this.gateway_id;
63
+ };
64
+ /**
65
+ * @returns {Boolean}
66
+ */
67
+
68
+
69
+ wc_stripe.BaseGateway.prototype.is_saved_method_selected = function () {
70
+ return this.is_gateway_selected() && $('[name="' + this.gateway_id + '_payment_type_key"]:checked').val() === 'saved';
71
+ };
72
+ /**
73
+ * @return {Boolean}
74
+ */
75
+
76
+
77
+ wc_stripe.BaseGateway.prototype.has_checkout_error = function () {
78
+ return $('#wc_stripe_checkout_error').length > 0 && this.is_gateway_selected();
79
+ };
80
+ /**
81
+ * @param {[type]}
82
+ * @return {[type]}
83
+ */
84
+
85
+
86
+ wc_stripe.BaseGateway.prototype.submit_error = function (message) {
87
+ message = this.get_error_message(message);
88
+
89
+ if (message.indexOf('</ul>') == -1) {
90
+ message = '<div class="woocommerce-error">' + message + '</div>';
91
+ }
92
+
93
+ this.submit_message(message);
94
+ };
95
+
96
+ wc_stripe.BaseGateway.prototype.submit_error_code = function (code) {
97
+ console.log(code);
98
+ };
99
+
100
+ wc_stripe.BaseGateway.prototype.get_error_message = function (message) {
101
+ if (typeof message == 'object' && message.code) {
102
+ if (wc_stripe_messages[message.code]) {
103
+ message = wc_stripe_messages[message.code];
104
+ } else {
105
+ message = message.message;
106
+ }
107
+ }
108
+
109
+ return message;
110
+ };
111
+ /**
112
+ * @param {[type]}
113
+ * @return {[type]}
114
+ */
115
+
116
+
117
+ wc_stripe.BaseGateway.prototype.submit_message = function (message) {
118
+ $('.woocommerce-error, .woocommerce-message, .woocommerce-info').remove();
119
+ var $container = $(this.message_container);
120
+
121
+ if ($container.closest('form').length) {
122
+ $container = $container.closest('form');
123
+ }
124
+
125
+ $container.prepend(message);
126
+ $container.removeClass('processing').unblock();
127
+ $container.find('.input-text, select, input:checkbox').blur();
128
+
129
+ if ($.scroll_to_notices) {
130
+ $.scroll_to_notices($container);
131
+ } else {
132
+ $('html, body').animate({
133
+ scrollTop: $container.offset().top - 100
134
+ }, 1000);
135
+ }
136
+ };
137
+
138
+ wc_stripe.BaseGateway.prototype.get_first_name = function (prefix) {
139
+ return $('#' + prefix + '_first_name').val();
140
+ };
141
+
142
+ wc_stripe.BaseGateway.prototype.get_last_name = function (prefix) {
143
+ return $('#' + prefix + '_last_name').val();
144
+ };
145
+
146
+ wc_stripe.BaseGateway.prototype.get_shipping_prefix = function () {
147
+ if (this.needs_shipping() && $('[name="ship_to_different_address"]').length > 0 && $('[name="ship_to_different_address"]').is(':checked')) {
148
+ return 'shipping';
149
+ }
150
+ return 'billing';
151
+ }
152
+
153
+ wc_stripe.BaseGateway.prototype.should_save_method = function () {
154
+ return $('#' + this.gateway_id + '_save_source_key').is(':checked');
155
+ };
156
+
157
+ wc_stripe.BaseGateway.prototype.is_add_payment_method_page = function () {
158
+ return this.get_page() === 'add_payment_method' || $(document.body).hasClass('woocommerce-add-payment-method');
159
+ };
160
+
161
+ wc_stripe.BaseGateway.prototype.is_change_payment_method = function () {
162
+ return this.get_page() === 'change_payment_method';
163
+ };
164
+
165
+ wc_stripe.BaseGateway.prototype.get_selected_payment_method = function () {
166
+ return $(this.saved_method_selector).val();
167
+ };
168
+
169
+ wc_stripe.BaseGateway.prototype.needs_shipping = function () {
170
+ return this.get_gateway_data().needs_shipping;
171
+ };
172
+
173
+ wc_stripe.BaseGateway.prototype.get_currency = function () {
174
+ return this.get_gateway_data().currency;
175
+ };
176
+
177
+ wc_stripe.BaseGateway.prototype.get_gateway_data = function () {
178
+ return $(this.container).find(".woocommerce_".concat(this.gateway_id, "_gateway_data")).data('gateway');
179
+ };
180
+
181
+ wc_stripe.BaseGateway.prototype.set_gateway_data = function (data) {
182
+ $(this.container).find(".woocommerce_".concat(this.gateway_id, "_gateway_data")).data('gateway', data);
183
+ };
184
+ /**
185
+ * [get_customer_name description]
186
+ * @return String
187
+ */
188
+
189
+
190
+ wc_stripe.BaseGateway.prototype.get_customer_name = function (prefix) {
191
+ return this.fields.get(prefix + '_first_name') + ' ' + this.fields.get(prefix + '_last_name');
192
+ };
193
+ /**
194
+ * [get_customer_email description]
195
+ * @return {String} [description]
196
+ */
197
+
198
+
199
+ wc_stripe.BaseGateway.prototype.get_customer_email = function () {
200
+ return this.fields.get('billing_email');
201
+ };
202
+ /**
203
+ * Returns a string representation of an address.
204
+ * @param {[type]}
205
+ * @return {[type]}
206
+ */
207
+
208
+
209
+ wc_stripe.BaseGateway.prototype.get_address_field_hash = function (prefix) {
210
+ var params = ['_first_name', '_last_name', '_address_1', '_address_2', '_postcode', '_city', '_state', '_country'];
211
+ var hash = '';
212
+
213
+ for (var i = 0; i < params.length; i++) {
214
+ hash += this.fields.get(prefix + params[i]) + '_';
215
+ }
216
+
217
+ return hash;
218
+ };
219
+ /**
220
+ * @return {[type]}
221
+ */
222
+
223
+
224
+ wc_stripe.BaseGateway.prototype.block = function () {
225
+ if ($().block) {
226
+ $.blockUI({
227
+ message: null,
228
+ overlayCSS: {
229
+ background: '#fff',
230
+ opacity: 0.6
231
+ }
232
+ });
233
+ }
234
+ ;
235
+ }
236
+ /**
237
+ * @return {[type]}
238
+ */
239
+
240
+
241
+ wc_stripe.BaseGateway.prototype.unblock = function () {
242
+ if ($().block) {
243
+ $.unblockUI();
244
+ }
245
+ };
246
+ /**
247
+ * @return {[type]}
248
+ */
249
+
250
+
251
+ wc_stripe.BaseGateway.prototype.get_form = function () {
252
+ return $(this.token_selector).closest('form');
253
+ };
254
+ /**
255
+ * @return {[type]}
256
+ */
257
+
258
+
259
+ wc_stripe.BaseGateway.prototype.get_total_price = function () {
260
+ return this.get_gateway_data().total;
261
+ };
262
+
263
+ wc_stripe.BaseGateway.prototype.get_total_price_cents = function () {
264
+ return this.get_gateway_data().total_cents;
265
+ };
266
+ /**
267
+ * @return {[type]}
268
+ */
269
+
270
+
271
+ wc_stripe.BaseGateway.prototype.set_total_price = function (total) {
272
+ var data = this.get_gateway_data();
273
+ data.total = total;
274
+ this.set_gateway_data(data);
275
+ };
276
+ /**
277
+ * @return {[type]}
278
+ */
279
+
280
+
281
+ wc_stripe.BaseGateway.prototype.set_total_price_cents = function (total) {
282
+ var data = this.get_gateway_data();
283
+ data.total_cents = total;
284
+ this.set_gateway_data(data);
285
+ };
286
+ /**
287
+ * [set_payment_method description]
288
+ * @param {[type]} payment_method [description]
289
+ */
290
+
291
+
292
+ wc_stripe.BaseGateway.prototype.set_payment_method = function (payment_method) {
293
+ $('[name="payment_method"][value="' + payment_method + '"]').prop("checked", true).trigger('click');
294
+ };
295
+ /**
296
+ * [set_shipping_methods description]
297
+ */
298
+
299
+
300
+ wc_stripe.BaseGateway.prototype.set_selected_shipping_methods = function (shipping_methods) {
301
+ this.fields.set('shipping_method', shipping_methods);
302
+
303
+ if (shipping_methods && $('[name^="shipping_method"]').length) {
304
+ for (var i in shipping_methods) {
305
+ var method = shipping_methods[i];
306
+ $('[name="shipping_method[' + i + ']"][value="' + method + '"]').prop("checked", true).trigger('change');
307
+ }
308
+ }
309
+ };
310
+ /**
311
+ * @param {[type]}
312
+ * @return {[type]}
313
+ */
314
+
315
+
316
+ wc_stripe.BaseGateway.prototype.on_token_received = function (paymentMethod) {
317
+ this.payment_token_received = true;
318
+ this.set_nonce(paymentMethod.id);
319
+ this.process_checkout();
320
+ };
321
+
322
+ wc_stripe.BaseGateway.prototype.createPaymentRequest = function () {
323
+ try {
324
+ this.payment_request_options = this.get_payment_request_options();
325
+ this.paymentRequest = stripe.paymentRequest(this.payment_request_options);
326
+ } catch (err) {
327
+ this.submit_error(err.message);
328
+ return;
329
+ }
330
+
331
+ if (this.payment_request_options.requestShipping) {
332
+ this.paymentRequest.on('shippingaddresschange', this.update_shipping_address.bind(this));
333
+ this.paymentRequest.on('shippingoptionchange', this.update_shipping_method.bind(this));
334
+ }
335
+
336
+ this.paymentRequest.on('paymentmethod', this.on_payment_method_received.bind(this));
337
+ };
338
+ /**
339
+ * @return {[Object]}
340
+ */
341
+
342
+
343
+ wc_stripe.BaseGateway.prototype.get_payment_request_options = function () {
344
+ var options = {
345
+ country: this.params.country_code,
346
+ currency: this.get_currency().toLowerCase(),
347
+ total: {
348
+ amount: this.get_total_price_cents(),
349
+ label: this.params.total_label,
350
+ pending: true
351
+ },
352
+ requestPayerName: true,
353
+ requestPayerEmail: this.fields.requestFieldInWallet('billing_email'),
354
+ requestPayerPhone: this.fields.requestFieldInWallet('billing_phone'),
355
+ requestShipping: (function () {
356
+ if (this.needs_shipping()) {
357
+ var prefix = this.get_shipping_prefix();
358
+ if ((this.is_current_page('checkout') && !this.is_valid_address(this.get_address_object(prefix), prefix, ['email', 'phone'])) || !this.is_current_page('checkout')) {
359
+ return true;
360
+ }
361
+ }
362
+ return false;
363
+ }.bind(this))()
364
+ };
365
+ var displayItems = this.get_display_items(),
366
+ shippingOptions = this.get_shipping_options();
367
+
368
+ if (displayItems) {
369
+ options.displayItems = displayItems;
370
+ }
371
+
372
+ if (options.requestShipping && shippingOptions) {
373
+ options.shippingOptions = shippingOptions;
374
+ }
375
+
376
+ return options;
377
+ };
378
+ /**
379
+ * @return {[Object]}
380
+ */
381
+
382
+
383
+ wc_stripe.BaseGateway.prototype.get_payment_request_update = function (data) {
384
+ var options = {
385
+ currency: this.get_currency().toLowerCase(),
386
+ total: {
387
+ amount: parseInt(this.get_total_price_cents()),
388
+ label: this.params.total_label,
389
+ pending: true
390
+ }
391
+ };
392
+ var displayItems = this.get_display_items(),
393
+ shippingOptions = this.get_shipping_options();
394
+
395
+ if (displayItems) {
396
+ options.displayItems = displayItems;
397
+ }
398
+
399
+ if (this.payment_request_options.requestShipping && shippingOptions) {
400
+ options.shippingOptions = shippingOptions;
401
+ }
402
+
403
+ if (data) {
404
+ options = $.extend(true, {}, options, data);
405
+ }
406
+
407
+ return options;
408
+ };
409
+ /**
410
+ * @return {[type]}
411
+ */
412
+
413
+
414
+ wc_stripe.BaseGateway.prototype.get_display_items = function () {
415
+ return this.get_gateway_data().items;
416
+ };
417
+ /**
418
+ * @return {[type]}
419
+ */
420
+
421
+
422
+ wc_stripe.BaseGateway.prototype.set_display_items = function (items) {
423
+ var data = this.get_gateway_data();
424
+ data.items = items;
425
+ this.set_gateway_data(data);
426
+ };
427
+ /**
428
+ * Return an array of shipping options for display in the Google payment sheet
429
+ * @return {[type]}
430
+ */
431
+
432
+
433
+ wc_stripe.BaseGateway.prototype.get_shipping_options = function () {
434
+ return this.get_gateway_data().shipping_options;
435
+ };
436
+ /**
437
+ * Update the shipping options.
438
+ * @param {[type]}
439
+ */
440
+
441
+
442
+ wc_stripe.BaseGateway.prototype.set_shipping_options = function (items) {
443
+ var data = this.get_gateway_data();
444
+ data.shipping_options = items;
445
+ this.set_gateway_data(data);
446
+ };
447
+ /**
448
+ * Maps an address from the Browser address format to WC format.
449
+ * @param {[type]}
450
+ * @return {[type]}
451
+ */
452
+
453
+
454
+ wc_stripe.BaseGateway.prototype.map_address = function (address) {
455
+ return {
456
+ city: address.city,
457
+ postcode: address.postalCode,
458
+ state: address.region,
459
+ country: address.country
460
+ };
461
+ };
462
+ /**
463
+ * @param {[type]}
464
+ * @return {[type]}
465
+ */
466
+
467
+
468
+ wc_stripe.BaseGateway.prototype.on_payment_method_received = function (paymentResponse) {
469
+ try {
470
+ this.payment_response = paymentResponse;
471
+ this.populate_checkout_fields(paymentResponse);
472
+ paymentResponse.complete("success");
473
+ this.on_token_received(paymentResponse.paymentMethod);
474
+ } catch (err) {
475
+ window.alert(err);
476
+ }
477
+ };
478
+ /**
479
+ * @return {[type]}
480
+ */
481
+
482
+
483
+ wc_stripe.BaseGateway.prototype.populate_checkout_fields = function (data) {
484
+ this.set_nonce(data.paymentMethod.id);
485
+ this.update_addresses(data);
486
+ };
487
+ /**
488
+ * @param {[type]}
489
+ * @return {[type]}
490
+ */
491
+
492
+
493
+ wc_stripe.BaseGateway.prototype.update_addresses = function (data) {
494
+ if (data.payerName) {
495
+ this.fields.set('name', data.payerName, 'billing');
496
+ }
497
+
498
+ if (data.payerEmail) {
499
+ this.fields.set('email', data.payerEmail, 'billing');
500
+ }
501
+
502
+ if (data.payerPhone) {
503
+ this.fields.set('phone', data.payerPhone, 'billing');
504
+ }
505
+
506
+ if (data.shippingAddress) {
507
+ this.populate_shipping_fields(data.shippingAddress);
508
+ }
509
+
510
+ if (data.paymentMethod.billing_details.address) {
511
+ this.populate_billing_fields(data.paymentMethod.billing_details.address);
512
+ }
513
+ };
514
+
515
+ wc_stripe.BaseGateway.prototype.populate_address_fields = function (address, prefix) {
516
+ for (var k in address) {
517
+ if (null !== address[k]) {
518
+ this.fields.set(k, address[k], prefix);
519
+ }
520
+ }
521
+ }
522
+
523
+ wc_stripe.BaseGateway.prototype.populate_billing_fields = function (address) {
524
+ this.populate_address_fields(address, 'billing');
525
+ }
526
+
527
+ wc_stripe.BaseGateway.prototype.populate_shipping_fields = function (address) {
528
+ this.populate_address_fields(address, 'shipping');
529
+ }
530
+
531
+ wc_stripe.BaseGateway.prototype.get_address_fields = function () {
532
+ return ['first_name', 'last_name', 'country', 'address_1', 'address_2', 'city', 'state', 'postcode', 'phone', 'email'];
533
+ }
534
+
535
+ wc_stripe.BaseGateway.prototype.get_address_object = function (prefix) {
536
+ var address = {};
537
+ this.get_address_fields().forEach(function (k) {
538
+ address[k] = this.fields.get(k, prefix);
539
+ }.bind(this));
540
+ return address;
541
+ }
542
+
543
+ wc_stripe.BaseGateway.prototype.is_current_page = function (page) {
544
+ return this.get_page() === page;
545
+ }
546
+
547
+ wc_stripe.BaseGateway.prototype.is_valid_address = function (address, prefix, exclude) {
548
+ if ($.isEmptyObject(address)) {
549
+ return false;
550
+ }
551
+
552
+ var mappings = this.get_address_fields();
553
+ if (typeof exclude !== 'undefined') {
554
+ exclude.forEach(function (k) {
555
+ if (mappings.indexOf(k) > -1) {
556
+ mappings.splice(mappings.indexOf(k), 1);
557
+ }
558
+ });
559
+ }
560
+ for (var i = 0; i < mappings.length; i++) {
561
+ var k = mappings[i];
562
+ var required = this.fields.required(prefix + '_' + k);
563
+ if (required) {
564
+ if (!address[k] || typeof address[k] === 'undefined' || !this.fields.isValid(k, address[k], address)) {
565
+ return false;
566
+ }
567
+ }
568
+ }
569
+ return true;
570
+ }
571
+
572
+ wc_stripe.BaseGateway.prototype.ajax_before_send = function (xhr) {
573
+ if (this.params.user_id > 0) {
574
+ xhr.setRequestHeader('X-WP-Nonce', this.params.rest_nonce);
575
+ }
576
+ };
577
+ /**
578
+ * @return {[type]}
579
+ */
580
+
581
+
582
+ wc_stripe.BaseGateway.prototype.process_checkout = function () {
583
+ return new Promise(function () {
584
+ this.block();
585
+ $.ajax({
586
+ url: this.params.routes.checkout,
587
+ method: 'POST',
588
+ dataType: 'json',
589
+ data: $.extend({}, this.serialize_fields(), {
590
+ payment_method: this.gateway_id,
591
+ page_id: this.get_page()
592
+ }),
593
+ beforeSend: this.ajax_before_send.bind(this)
594
+ }).done(function (result) {
595
+ if (result.reload) {
596
+ window.location.reload();
597
+ return;
598
+ }
599
+
600
+ if (result.result === 'success') {
601
+ window.location = result.redirect;
602
+ } else {
603
+ if (result.messages) {
604
+ this.submit_error(result.messages);
605
+ }
606
+
607
+ this.unblock();
608
+ }
609
+ }.bind(this)).fail(function (xhr, textStatus, errorThrown) {
610
+ this.unblock();
611
+ this.submit_error(errorThrown);
612
+ }.bind(this));
613
+ }.bind(this));
614
+ };
615
+ /**
616
+ * @return {[type]}
617
+ */
618
+
619
+
620
+ wc_stripe.BaseGateway.prototype.serialize_form = function ($form) {
621
+ var formData = $form.find('input').filter(function (i, e) {
622
+ if ($(e).is('[name^="add-to-cart"]')) {
623
+ return false;
624
+ }
625
+
626
+ return true;
627
+ }.bind(this)).serializeArray(),
628
+ data = {};
629
+
630
+ for (var i in formData) {
631
+ var obj = formData[i];
632
+ data[obj.name] = obj.value;
633
+ }
634
+
635
+ data.payment_method = this.gateway_id;
636
+ return data;
637
+ };
638
+
639
+ wc_stripe.BaseGateway.prototype.serialize_fields = function () {
640
+ return $.extend({}, this.fields.toJson(), $(document.body).triggerHandler('wc_stripe_process_checkout_data', [this, this.fields]));
641
+ };
642
+ /**
643
+ * @param {[type]}
644
+ * @return {[type]}
645
+ */
646
+
647
+
648
+ wc_stripe.BaseGateway.prototype.map_shipping_methods = function (shippingData) {
649
+ var methods = {};
650
+
651
+ if (shippingData !== "default") {
652
+ var matches = shippingData.match(/^([\w+]):(.+)$/);
653
+
654
+ if (matches.length > 1) {
655
+ methods[matches[1]] = matches[2];
656
+ }
657
+ }
658
+
659
+ return methods;
660
+ };
661
+ /**
662
+ * [maybe_set_ship_to_different description]
663
+ * @return {[type]} [description]
664
+ */
665
+
666
+
667
+ wc_stripe.BaseGateway.prototype.maybe_set_ship_to_different = function () {
668
+ // if shipping and billing address are different,
669
+ // set the ship to different address option.
670
+ if ($('[name="ship_to_different_address"]').length) {
671
+ $('[name="ship_to_different_address"]').prop('checked', this.get_address_field_hash("billing") !== this.get_address_field_hash("shipping")).trigger('change');
672
+ }
673
+ };
674
+
675
+ wc_stripe.BaseGateway.prototype.update_shipping_address = function (ev) {
676
+ return new Promise(function (resolve, reject) {
677
+ $.ajax({
678
+ url: this.params.routes.shipping_address,
679
+ method: 'POST',
680
+ dataType: 'json',
681
+ data: {
682
+ address: this.map_address(ev.shippingAddress),
683
+ payment_method: this.gateway_id,
684
+ page_id: this.get_page()
685
+ },
686
+ beforeSend: this.ajax_before_send.bind(this)
687
+ }).done(function (response) {
688
+ if (response.code) {
689
+ ev.updateWith(response.data.newData);
690
+ reject(response.data);
691
+ } else {
692
+ ev.updateWith(response.data.newData);
693
+ this.fields.set('shipping_method', response.data.shipping_method);
694
+ resolve(response.data);
695
+ }
696
+ }.bind(this)).fail(function () {
697
+ }.bind(this));
698
+ }.bind(this));
699
+ };
700
+ /**
701
+ * @return {[@event]}
702
+ */
703
+
704
+
705
+ wc_stripe.BaseGateway.prototype.update_shipping_method = function (ev) {
706
+ return new Promise(function (resolve, reject) {
707
+ $.ajax({
708
+ url: this.params.routes.shipping_method,
709
+ method: 'POST',
710
+ dataType: 'json',
711
+ data: {
712
+ shipping_method: ev.shippingOption.id,
713
+ payment_method: this.gateway_id,
714
+ page_id: this.get_page()
715
+ },
716
+ beforeSend: this.ajax_before_send.bind(this)
717
+ }).done(function (response) {
718
+ if (response.code) {
719
+ ev.updateWith(response.data.newData);
720
+ reject(response.data);
721
+ } else {
722
+ this.set_selected_shipping_methods(response.data.shipping_methods);
723
+ ev.updateWith(response.data.newData);
724
+ resolve(response.data);
725
+ }
726
+ }.bind(this)).fail(function (xhr, textStatus, errorThrown) {
727
+ this.submit_error(errorThrown);
728
+ }.bind(this));
729
+ }.bind(this));
730
+ };
731
+ /********** Checkout Gateway ********/
732
+
733
+ /**
734
+ * @constructor
735
+ */
736
+
737
+
738
+ wc_stripe.CheckoutGateway = function () {
739
+ this.message_container = 'li.payment_method_' + this.gateway_id;
740
+ this.banner_container = 'li.banner_payment_method_' + this.gateway_id;
741
+ $(document.body).on('update_checkout', this.update_checkout.bind(this));
742
+ $(document.body).on('updated_checkout', this.updated_checkout.bind(this));
743
+ $(document.body).on('cfw_updated_checkout', this.updated_checkout.bind(this));
744
+ $(document.body).on('checkout_error', this.checkout_error.bind(this));
745
+ $(this.token_selector).closest('form').on('checkout_place_order_' + this.gateway_id, this.checkout_place_order.bind(this)); // events for showing gateway payment buttons
746
+
747
+ $(document.body).on('wc_stripe_new_method_' + this.gateway_id, this.on_show_new_methods.bind(this));
748
+ $(document.body).on('wc_stripe_saved_method_' + this.gateway_id, this.on_show_saved_methods.bind(this));
749
+ $(document.body).on('wc_stripe_payment_method_selected', this.on_payment_method_selected.bind(this));
750
+
751
+ if (this.banner_enabled()) {
752
+ if ($('.woocommerce-billing-fields').length) {
753
+ $('.wc-stripe-banner-checkout').css('max-width', $('.woocommerce-billing-fields').outerWidth(true));
754
+ }
755
+ }
756
+
757
+ this.order_review();
758
+ };
759
+
760
+ wc_stripe.CheckoutGateway.prototype.order_review = function () {
761
+ var url = window.location.href;
762
+ var matches = url.match(/order_review.+payment_method=([\w]+).+payment_nonce=(.+)/);
763
+
764
+ if (matches && matches.length > 1) {
765
+ var payment_method = matches[1],
766
+ nonce = matches[2];
767
+
768
+ if (this.gateway_id === payment_method) {
769
+ this.payment_token_received = true;
770
+ this.set_nonce(nonce);
771
+ this.set_use_new_option(true);
772
+ }
773
+ }
774
+ };
775
+
776
+ wc_stripe.CheckoutGateway.prototype.update_shipping_address = function () {
777
+ return wc_stripe.BaseGateway.prototype.update_shipping_address.apply(this, arguments).then(function (data) {
778
+ // populate the checkout fields with the address
779
+ this.populate_address_fields(data.address, this.get_shipping_prefix());
780
+ this.fields.toFormFields({update_shipping_method: false});
781
+ }.bind(this));
782
+ }
783
+
784
+ /**
785
+ * Called on the WC updated_checkout event
786
+ */
787
+ wc_stripe.CheckoutGateway.prototype.updated_checkout = function () {
788
+ };
789
+
790
+ /**
791
+ * Called on the WC update_checkout event
792
+ */
793
+ wc_stripe.CheckoutGateway.prototype.update_checkout = function () {
794
+ };
795
+ /**
796
+ * Called on the WC checkout_error event
797
+ */
798
+
799
+
800
+ wc_stripe.CheckoutGateway.prototype.checkout_error = function () {
801
+ if (this.has_checkout_error()) {
802
+ this.payment_token_received = false;
803
+ this.payment_response = null;
804
+ this.show_payment_button();
805
+ this.hide_place_order();
806
+ }
807
+ };
808
+ /**
809
+ *
810
+ */
811
+
812
+
813
+ wc_stripe.CheckoutGateway.prototype.is_valid_checkout = function () {
814
+ if ($('[name="terms"]').length) {
815
+ if (!$('[name="terms"]').is(':checked')) {
816
+ return false;
817
+ }
818
+ }
819
+
820
+ return true;
821
+ };
822
+ /**
823
+ * Returns the selected payment gateway's id.
824
+ *
825
+ * @returns {String}
826
+ */
827
+
828
+
829
+ wc_stripe.CheckoutGateway.prototype.get_payment_method = function () {
830
+ return $('[name="payment_method"]:checked').val();
831
+ };
832
+
833
+ wc_stripe.CheckoutGateway.prototype.set_use_new_option = function (bool) {
834
+ $('#' + this.gateway_id + '_use_new').prop('checked', bool).trigger('change');
835
+ };
836
+ /**
837
+ * Called on the WC checkout_place_order_{$gateway_id} event
838
+ */
839
+
840
+
841
+ wc_stripe.CheckoutGateway.prototype.checkout_place_order = function () {
842
+ if (!this.is_valid_checkout()) {
843
+ this.submit_error(this.params.messages.terms);
844
+ return false;
845
+ } else if (this.is_saved_method_selected()) {
846
+ return true;
847
+ }
848
+
849
+ return this.payment_token_received;
850
+ };
851
+ /**
852
+ * @param {[type]}
853
+ * @return {[type]}
854
+ */
855
+
856
+
857
+ wc_stripe.CheckoutGateway.prototype.on_token_received = function (paymentMethod) {
858
+ this.payment_token_received = true;
859
+ this.set_nonce(paymentMethod.id);
860
+ this.hide_payment_button();
861
+ this.show_place_order();
862
+ };
863
+ /**
864
+ * @return {[type]}
865
+ */
866
+
867
+
868
+ wc_stripe.CheckoutGateway.prototype.block = function () {
869
+ if ($().block) {
870
+ $('form.checkout').block({
871
+ message: null,
872
+ overlayCSS: {
873
+ background: '#fff',
874
+ opacity: 0.6
875
+ }
876
+ });
877
+ }
878
+
879
+ };
880
+ /**
881
+ * @return {[type]}
882
+ */
883
+
884
+
885
+ wc_stripe.CheckoutGateway.prototype.unblock = function () {
886
+ if ($().block) {
887
+ $('form.checkout').unblock();
888
+ }
889
+ };
890
+
891
+ wc_stripe.CheckoutGateway.prototype.hide_place_order = function () {
892
+ $('#place_order').addClass('wc-stripe-hide');
893
+ };
894
+ /**
895
+ * @return {[type]}
896
+ */
897
+
898
+
899
+ wc_stripe.CheckoutGateway.prototype.show_place_order = function () {
900
+ $('#place_order').removeClass('wc-stripe-hide');
901
+ };
902
+ /**
903
+ * Method that should perform actions when the show new methods contain is made visible.
904
+ * @param {[@event]}
905
+ * @param {[String]}
906
+ * @return {[type]}
907
+ */
908
+
909
+
910
+ wc_stripe.CheckoutGateway.prototype.on_show_new_methods = function () {
911
+ if (this.payment_token_received) {
912
+ this.show_place_order();
913
+ this.hide_payment_button();
914
+ } else {
915
+ this.hide_place_order();
916
+ this.show_payment_button();
917
+ }
918
+ };
919
+ /**
920
+ * Method that performs actions when the saved methods contains is visible.
921
+ * @param {[type]}
922
+ * @param {[type]}
923
+ * @return {[type]}
924
+ */
925
+
926
+
927
+ wc_stripe.CheckoutGateway.prototype.on_show_saved_methods = function () {
928
+ this.hide_payment_button();
929
+ this.show_place_order();
930
+ };
931
+ /**
932
+ * @return {[type]}
933
+ */
934
+
935
+
936
+ wc_stripe.CheckoutGateway.prototype.show_payment_button = function () {
937
+ if (this.$button) {
938
+ this.$button.show();
939
+ }
940
+ };
941
+ /**
942
+ * @return {[type]}
943
+ */
944
+
945
+
946
+ wc_stripe.CheckoutGateway.prototype.hide_payment_button = function () {
947
+ if (this.$button) {
948
+ this.$button.hide();
949
+ }
950
+ };
951
+ /**
952
+ * Wrapper for on_payment_method_selected that is safe to call since it won't trigger
953
+ * any DOM events.
954
+ * @return {[type]}
955
+ */
956
+
957
+
958
+ wc_stripe.CheckoutGateway.prototype.trigger_payment_method_selected = function () {
959
+ this.on_payment_method_selected(null, $('[name="payment_method"]:checked').val());
960
+ };
961
+ /**
962
+ * @param {[type]}
963
+ * @param {[type]}
964
+ * @return {[type]}
965
+ */
966
+
967
+
968
+ wc_stripe.CheckoutGateway.prototype.on_payment_method_selected = function (e, payment_method) {
969
+ if (payment_method === this.gateway_id) {
970
+ if (this.payment_token_received || this.is_saved_method_selected()) {
971
+ this.hide_payment_button();
972
+ this.show_place_order();
973
+ } else {
974
+ this.show_payment_button();
975
+ this.hide_place_order();
976
+ }
977
+ } else {
978
+ this.hide_payment_button();
979
+
980
+ if (payment_method.indexOf('stripe_') < 0) {
981
+ this.show_place_order();
982
+ }
983
+ }
984
+ };
985
+ /**
986
+ * [Return true if the banner option has been enabled for the gateway.]
987
+ * @return {[type]} [description]
988
+ */
989
+
990
+
991
+ wc_stripe.CheckoutGateway.prototype.banner_enabled = function () {
992
+ return this.params.banner_enabled === '1';
993
+ };
994
+
995
+ wc_stripe.CheckoutGateway.prototype.checkout_fields_valid = function () {
996
+ if (['checkout', 'order_pay'].indexOf(this.get_page()) < 0) {
997
+ return true;
998
+ }
999
+
1000
+ var valid = true;
1001
+
1002
+ if (!(valid = this.fields.validateFields('billing'))) {
1003
+ this.submit_error(this.params.messages.required_field);
1004
+ } else if (this.needs_shipping() && $('#ship-to-different-address-checkbox').is(':checked')) {
1005
+ if (!(valid = this.fields.validateFields('shipping'))) {
1006
+ this.submit_error(this.params.messages.required_field);
1007
+ }
1008
+ } else if (!(valid = this.is_valid_checkout())) {
1009
+ this.submit_error(this.params.messages.terms);
1010
+ }
1011
+
1012
+ return valid;
1013
+ };
1014
+ /************** Product Gateway ***************/
1015
+
1016
+
1017
+ wc_stripe.ProductGateway = function () {
1018
+ this.message_container = 'div.product'; // events
1019
+
1020
+ $('form.cart').on('found_variation', this.found_variation.bind(this));
1021
+ $('form.cart').on('reset_data', this.reset_variation_data.bind(this));
1022
+ this.buttonWidth = $('form.cart div.quantity').outerWidth(true) + $('.single_add_to_cart_button').outerWidth();
1023
+ var marginLeft = $('.single_add_to_cart_button').css('marginLeft');
1024
+
1025
+ if (marginLeft) {
1026
+ this.buttonWidth += parseInt(marginLeft.replace('px', ''));
1027
+ }
1028
+
1029
+ $(this.container).css('max-width', this.buttonWidth + 'px');
1030
+ };
1031
+ /**
1032
+ * @return {[@int]}
1033
+ */
1034
+
1035
+
1036
+ wc_stripe.ProductGateway.prototype.get_quantity = function () {
1037
+ return parseInt($('[name="quantity"]').val());
1038
+ };
1039
+ /**
1040
+ * @param {[type]}
1041
+ * @param {[type]}
1042
+ */
1043
+
1044
+
1045
+ wc_stripe.ProductGateway.prototype.set_rest_nonce = function (e, nonce) {
1046
+ this.params.rest_nonce = nonce;
1047
+ };
1048
+ /**
1049
+ * @param {[type]}
1050
+ * @param {[type]}
1051
+ * @return {[type]}
1052
+ */
1053
+
1054
+
1055
+ wc_stripe.ProductGateway.prototype.found_variation = function (e, variation) {
1056
+ var data = this.get_gateway_data();
1057
+ data.product.price = variation.display_price;
1058
+ data.needs_shipping = !variation.is_virtual;
1059
+ data.product.variation = variation;
1060
+ this.set_gateway_data(data);
1061
+ };
1062
+ /**
1063
+ * @return {[type]}
1064
+ */
1065
+
1066
+
1067
+ wc_stripe.ProductGateway.prototype.reset_variation_data = function () {
1068
+ var data = this.get_product_data();
1069
+ data.variation = false;
1070
+ this.set_product_data(data);
1071
+ this.disable_payment_button();
1072
+ };
1073
+ /**
1074
+ * @return {[type]}
1075
+ */
1076
+
1077
+
1078
+ wc_stripe.ProductGateway.prototype.disable_payment_button = function () {
1079
+ if (this.$button) {
1080
+ this.get_button().prop('disabled', true).addClass('disabled');
1081
+ }
1082
+ };
1083
+ /**
1084
+ * @return {[type]}
1085
+ */
1086
+
1087
+
1088
+ wc_stripe.ProductGateway.prototype.enable_payment_button = function () {
1089
+ if (this.$button) {
1090
+ this.get_button().prop('disabled', false).removeClass('disabled');
1091
+ }
1092
+ };
1093
+ /**
1094
+ * @return {[type]}
1095
+ */
1096
+
1097
+
1098
+ wc_stripe.ProductGateway.prototype.get_button = function () {
1099
+ return this.$button;
1100
+ };
1101
+ /**
1102
+ * @return {Boolean}
1103
+ */
1104
+
1105
+
1106
+ wc_stripe.ProductGateway.prototype.is_variable_product = function () {
1107
+ return $('[name="variation_id"]').length > 0;
1108
+ };
1109
+
1110
+ wc_stripe.ProductGateway.prototype.variable_product_selected = function () {
1111
+ return this.get_product_data().variation !== false;
1112
+ };
1113
+ /**
1114
+ * @return {[type]}
1115
+ */
1116
+
1117
+
1118
+ wc_stripe.ProductGateway.prototype.get_product_data = function () {
1119
+ return this.get_gateway_data().product;
1120
+ };
1121
+ /**
1122
+ * @return {[type]}
1123
+ */
1124
+
1125
+
1126
+ wc_stripe.ProductGateway.prototype.set_product_data = function (product) {
1127
+ var data = this.get_gateway_data();
1128
+ data.product = product;
1129
+ this.set_gateway_data(data);
1130
+ };
1131
+ /**
1132
+ * Add a product to the WC shopping cart
1133
+ */
1134
+
1135
+
1136
+ wc_stripe.ProductGateway.prototype.add_to_cart = function () {
1137
+ return new Promise(function (resolve, reject) {
1138
+ this.block();
1139
+ $.ajax({
1140
+ url: this.params.routes.add_to_cart,
1141
+ method: 'POST',
1142
+ dataType: 'json',
1143
+ data: {
1144
+ product_id: this.get_product_data().id,
1145
+ variation_id: this.is_variable_product() ? $('[name="variation_id"]').val() : 0,
1146
+ qty: $('[name="quantity"]').val(),
1147
+ payment_method: this.gateway_id,
1148
+ page_id: this.get_page()
1149
+ },
1150
+ beforeSend: this.ajax_before_send.bind(this)
1151
+ }).done(function (response) {
1152
+ this.unblock();
1153
+
1154
+ if (response.code) {
1155
+ this.submit_error(response.message);
1156
+ reject(response);
1157
+ } else {
1158
+ this.set_total_price(response.data.total);
1159
+ this.set_total_price_cents(response.data.totalCents);
1160
+ this.set_display_items(response.data.displayItems);
1161
+ resolve(response.data);
1162
+ }
1163
+ }.bind(this)).fail(function (xhr, textStatus, errorThrown) {
1164
+ this.unblock();
1165
+ this.submit_error(errorThrown);
1166
+ }.bind(this));
1167
+ }.bind(this));
1168
+ };
1169
+
1170
+ wc_stripe.ProductGateway.prototype.cart_calculation = function (variation_id) {
1171
+ return new Promise(function (resolve, reject) {
1172
+ $.ajax({
1173
+ url: this.params.routes.cart_calculation,
1174
+ method: 'POST',
1175
+ dataType: 'json',
1176
+ data: {
1177
+ product_id: this.get_product_data().id,
1178
+ variation_id: this.is_variable_product() && variation_id ? variation_id : 0,
1179
+ qty: $('[name="quantity"]').val(),
1180
+ payment_method: this.gateway_id
1181
+ },
1182
+ beforeSend: this.ajax_before_send.bind(this)
1183
+ }).done(function (response) {
1184
+ if (response.code) {
1185
+ this.cart_calculation_error = true;
1186
+ reject(response);
1187
+ } else {
1188
+ this.set_total_price(response.data.total);
1189
+ this.set_total_price_cents(response.data.totalCents);
1190
+ this.set_display_items(response.data.displayItems);
1191
+ resolve(response.data);
1192
+ }
1193
+ }.bind(this)).fail(function () {
1194
+ }.bind(this));
1195
+ }.bind(this));
1196
+ };
1197
+ /************* Cart Gateway *************/
1198
+
1199
+ /**
1200
+ * @constructor
1201
+ */
1202
+
1203
+
1204
+ wc_stripe.CartGateway = function () {
1205
+ this.message_container = 'div.woocommerce'; // cart events
1206
+
1207
+ $(document.body).on('updated_wc_div', this.updated_html.bind(this));
1208
+ $(document.body).on('updated_cart_totals', this.updated_html.bind(this));
1209
+ $(document.body).on('wc_cart_emptied', this.cart_emptied.bind(this));
1210
+ };
1211
+ /**
1212
+ * @param {[type]}
1213
+ * @return {[type]}
1214
+ */
1215
+
1216
+
1217
+ wc_stripe.CartGateway.prototype.submit_error = function (message) {
1218
+ this.submit_message(this.get_error_message(message));
1219
+ };
1220
+ /**
1221
+ * @param {[@event]}
1222
+ * @return {[null]}
1223
+ */
1224
+
1225
+
1226
+ wc_stripe.CartGateway.prototype.updated_html = function (e) {
1227
+ };
1228
+
1229
+ wc_stripe.CartGateway.prototype.cart_emptied = function (e) {
1230
+ };
1231
+
1232
+ wc_stripe.CartGateway.prototype.add_cart_totals_class = function () {
1233
+ $('.cart_totals').addClass('stripe_cart_gateway_active');
1234
+ };
1235
+
1236
+ /************* Google Pay Mixins **************/
1237
+
1238
+ wc_stripe.GooglePay = function () {
1239
+ };
1240
+
1241
+ var googlePayBaseRequest = {
1242
+ apiVersion: 2,
1243
+ apiVersionMinor: 0
1244
+ };
1245
+ var allowedCardNetworks = ["AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA"];
1246
+ var allowedCardAuthMethods = ["PAN_ONLY"];
1247
+ var baseCardPaymentMethod = {
1248
+ type: 'CARD',
1249
+ parameters: {
1250
+ allowedAuthMethods: allowedCardAuthMethods,
1251
+ allowedCardNetworks: allowedCardNetworks
1252
+ }
1253
+ };
1254
+ /**
1255
+ * Populate the WC checkout fields.
1256
+ * @param {[type]}
1257
+ * @return {[type]}
1258
+ */
1259
+
1260
+ wc_stripe.GooglePay.prototype.update_addresses = function (paymentData) {
1261
+ this.populate_billing_fields(paymentData.paymentMethodData.info.billingAddress);
1262
+
1263
+ if (paymentData.shippingAddress) {
1264
+ this.populate_shipping_fields(paymentData.shippingAddress);
1265
+ }
1266
+
1267
+ if (paymentData.email) {
1268
+ this.fields.set('email', paymentData.email, 'billing');
1269
+ }
1270
+ };
1271
+
1272
+ wc_stripe.GooglePay.prototype.map_address = function (address) {
1273
+ return {
1274
+ city: address.locality,
1275
+ postcode: address.postalCode,
1276
+ state: address.administrativeArea,
1277
+ country: address.countryCode
1278
+ };
1279
+ };
1280
+
1281
+ wc_stripe.GooglePay.prototype.update_payment_data = function (data) {
1282
+ return new Promise(function (resolve, reject) {
1283
+ var shipping_method = data.shippingOptionData.id == 'default' ? null : data.shippingOptionData.id;
1284
+ $.when($.ajax({
1285
+ url: this.params.routes.payment_data,
1286
+ dataType: 'json',
1287
+ method: 'POST',
1288
+ data: {
1289
+ shipping_address: this.map_address(data.shippingAddress),
1290
+ shipping_method: shipping_method,
1291
+ page_id: this.get_page()
1292
+ },
1293
+ beforeSend: this.ajax_before_send.bind(this)
1294
+ })).done(function (response) {
1295
+ if (response.code) {
1296
+ reject(response.data.data);
1297
+ } else {
1298
+ resolve(response.data);
1299
+ }
1300
+ }.bind(this)).fail(function () {
1301
+ reject();
1302
+ }.bind(this));
1303
+ }.bind(this));
1304
+ };
1305
+
1306
+ wc_stripe.GooglePay.prototype.on_payment_data_changed = function (address) {
1307
+ return new Promise(function (resolve) {
1308
+ this.update_payment_data(address).then(function (response) {
1309
+ resolve(response.paymentRequestUpdate);
1310
+ this.set_selected_shipping_methods(response.shipping_methods);
1311
+ this.payment_data_updated(response, address);
1312
+ }.bind(this))['catch'](function (data) {
1313
+ resolve(data);
1314
+ }.bind(this));
1315
+ }.bind(this));
1316
+ };
1317
+
1318
+ wc_stripe.GooglePay.prototype.payment_data_updated = function (response) {
1319
+ };
1320
+
1321
+ wc_stripe.GooglePay.prototype.get_merchant_info = function () {
1322
+ var options = {
1323
+ merchantId: this.params.merchant_id,
1324
+ merchantName: this.params.merchant_name
1325
+ };
1326
+
1327
+ if (this.params.environment === 'TEST') {
1328
+ delete options.merchantId;
1329
+ }
1330
+
1331
+ return options;
1332
+ };
1333
+
1334
+ wc_stripe.GooglePay.prototype.get_payment_options = function () {
1335
+ var options = {
1336
+ environment: this.params.environment,
1337
+ merchantInfo: this.get_merchant_info(),
1338
+ paymentDataCallbacks: {
1339
+ onPaymentAuthorized: function onPaymentAuthorized() {
1340
+ return new Promise(function (resolve) {
1341
+ resolve({
1342
+ transactionState: "SUCCESS"
1343
+ });
1344
+ }.bind(this));
1345
+ }
1346
+ }
1347
+ };
1348
+
1349
+ if (this.needs_shipping()) {
1350
+ var prefix = this.get_shipping_prefix();
1351
+ if ((this.is_current_page('checkout') && !this.is_valid_address(this.get_address_object(prefix), prefix, ['email', 'phone'])) || !this.is_current_page('checkout')) {
1352
+ options.paymentDataCallbacks.onPaymentDataChanged = this.on_payment_data_changed.bind(this);
1353
+ }
1354
+ }
1355
+
1356
+ return options;
1357
+ };
1358
+
1359
+ wc_stripe.GooglePay.prototype.build_payment_request = function () {
1360
+ var request = $.extend({}, googlePayBaseRequest, {
1361
+ emailRequired: this.fields.requestFieldInWallet('billing_email'),
1362
+ merchantInfo: this.get_merchant_info(),
1363
+ allowedPaymentMethods: [$.extend({
1364
+ type: "CARD",
1365
+ tokenizationSpecification: {
1366
+ type: "PAYMENT_GATEWAY",
1367
+ parameters: {
1368
+ gateway: 'stripe',
1369
+ "stripe:version": "2018-10-31",
1370
+ "stripe:publishableKey": this.params.api_key
1371
+ }
1372
+ }
1373
+ }, baseCardPaymentMethod)],
1374
+ shippingAddressRequired: (function () {
1375
+ if (this.needs_shipping()) {
1376
+ var prefix = this.get_shipping_prefix();
1377
+ if ((this.is_current_page('checkout') && !this.is_valid_address(this.get_address_object(prefix), prefix, ['email', 'phone'])) || !this.is_current_page('checkout')) {
1378
+ return true;
1379
+ }
1380
+ }
1381
+ return false;
1382
+ }.bind(this))(),
1383
+ transactionInfo: {
1384
+ currencyCode: this.get_currency(),
1385
+ totalPriceStatus: "ESTIMATED",
1386
+ totalPrice: this.get_total_price().toString(),
1387
+ displayItems: this.get_display_items(),
1388
+ totalPriceLabel: this.params.total_price_label
1389
+ }
1390
+ });
1391
+ request.allowedPaymentMethods[0].parameters['billingAddressRequired'] = true;
1392
+ request.allowedPaymentMethods[0].parameters['billingAddressParameters'] = {
1393
+ format: "FULL",
1394
+ phoneNumberRequired: this.fields.requestFieldInWallet('billing_phone')
1395
+ };
1396
+
1397
+ if (request.shippingAddressRequired) {
1398
+ request.shippingAddressParameters = {};
1399
+ request.shippingOptionRequired = true;
1400
+ request.shippingOptionParameters = {
1401
+ shippingOptions: this.get_shipping_options()
1402
+ };
1403
+ request.callbackIntents = ["SHIPPING_ADDRESS", "SHIPPING_OPTION", "PAYMENT_AUTHORIZATION"];
1404
+ } else {
1405
+ request.callbackIntents = ["PAYMENT_AUTHORIZATION"];
1406
+ }
1407
+ this.payment_request_options = request;
1408
+ return request;
1409
+ };
1410
+ /**
1411
+ * @return {[type]}
1412
+ */
1413
+
1414
+
1415
+ wc_stripe.GooglePay.prototype.createPaymentsClient = function () {
1416
+ this.paymentsClient = new google.payments.api.PaymentsClient(this.get_payment_options());
1417
+ };
1418
+ /**
1419
+ * @return {Promise}
1420
+ */
1421
+
1422
+
1423
+ wc_stripe.GooglePay.prototype.isReadyToPay = function () {
1424
+ return new Promise(function (resolve) {
1425
+ var isReadyToPayRequest = $.extend({}, googlePayBaseRequest);
1426
+ isReadyToPayRequest.allowedPaymentMethods = [baseCardPaymentMethod];
1427
+ this.paymentsClient.isReadyToPay(isReadyToPayRequest).then(function () {
1428
+ this.can_pay = true;
1429
+ this.create_button();
1430
+ resolve();
1431
+ }.bind(this))["catch"](function (err) {
1432
+ this.submit_error(err);
1433
+ }.bind(this));
1434
+ }.bind(this));
1435
+ };
1436
+
1437
+ wc_stripe.GooglePay.prototype.create_button = function () {
1438
+ if (this.$button) {
1439
+ this.$button.remove();
1440
+ }
1441
+
1442
+ this.$button = $(this.paymentsClient.createButton({
1443
+ onClick: this.start.bind(this),
1444
+ buttonColor: this.params.button_color,
1445
+ buttonType: this.params.button_style
1446
+ }));
1447
+ this.$button.addClass('gpay-button-container');
1448
+ };
1449
+ /**
1450
+ * @return {[type]}
1451
+ */
1452
+
1453
+
1454
+ wc_stripe.GooglePay.prototype.start = function () {
1455
+ // always recreate the paymentClient to ensure latest data is used.
1456
+ this.createPaymentsClient();
1457
+ this.paymentsClient.loadPaymentData(this.build_payment_request()).then(function (paymentData) {
1458
+ var data = JSON.parse(paymentData.paymentMethodData.tokenizationData.token);
1459
+ this.update_addresses(paymentData);
1460
+ this.on_token_received(data);
1461
+ }.bind(this))["catch"](function (err) {
1462
+ if (err.statusCode === "CANCELED") {
1463
+ return;
1464
+ }
1465
+
1466
+ if (err.statusMessage && err.statusMessage.indexOf("paymentDataRequest.callbackIntent") > -1) {
1467
+ this.submit_error_code("DEVELOPER_ERROR_WHITELIST");
1468
+ } else {
1469
+ this.submit_error(err.message);
1470
+ }
1471
+ }.bind(this));
1472
+ };
1473
+
1474
+ wc_stripe.ApplePay = function () {
1475
+ };
1476
+
1477
+ wc_stripe.ApplePay.prototype.initialize = function () {
1478
+ var selector = '.apple-pay-button';
1479
+
1480
+ if (['checkout', 'order_pay'].indexOf(this.get_page()) < 0) {
1481
+ selector = this.container + ' .apple-pay-button';
1482
+ }
1483
+
1484
+ $(document.body).on('click', selector, this.start.bind(this));
1485
+ this.createPaymentRequest();
1486
+ this.canMakePayment();
1487
+ };
1488
+
1489
+ wc_stripe.ApplePay.prototype.create_button = function () {
1490
+ if (this.$button) {
1491
+ this.$button.remove();
1492
+ }
1493
+
1494
+ this.$button = $(this.params.button);
1495
+ this.append_button();
1496
+ };
1497
+
1498
+ wc_stripe.ApplePay.prototype.canMakePayment = function () {
1499
+ return new Promise(function (resolve) {
1500
+ this.paymentRequest.canMakePayment().then(function (result) {
1501
+ if (result && result.applePay) {
1502
+ this.can_pay = true;
1503
+ this.create_button();
1504
+ $(this.container).show();
1505
+ resolve(result);
1506
+ }
1507
+ }.bind(this));
1508
+ }.bind(this));
1509
+ };
1510
+
1511
+ wc_stripe.ApplePay.prototype.start = function (e) {
1512
+ e.preventDefault();
1513
+ this.paymentRequest.update(this.get_payment_request_update({
1514
+ total: {
1515
+ pending: false
1516
+ }
1517
+ }));
1518
+ this.paymentRequest.show();
1519
+ };
1520
+
1521
+ /*********** PaymentRequest *********/
1522
+ wc_stripe.PaymentRequest = function () {
1523
+ };
1524
+
1525
+ wc_stripe.PaymentRequest.prototype.initialize = function () {
1526
+ this.createPaymentRequest();
1527
+ this.createPaymentRequestButton();
1528
+ this.canMakePayment();
1529
+ this.paymentRequestButton.on('click', this.button_click.bind(this));
1530
+ };
1531
+
1532
+ wc_stripe.PaymentRequest.prototype.button_click = function (event) {
1533
+ };
1534
+
1535
+ wc_stripe.PaymentRequest.prototype.createPaymentRequestButton = function () {
1536
+ if (this.paymentRequestButton) {
1537
+ this.paymentRequestButton.destroy();
1538
+ }
1539
+ this.paymentRequestButton = this.elements.create("paymentRequestButton", {
1540
+ paymentRequest: this.paymentRequest,
1541
+ style: {
1542
+ paymentRequestButton: {
1543
+ type: this.params.button.type,
1544
+ theme: this.params.button.theme,
1545
+ height: this.params.button.height
1546
+ }
1547
+ }
1548
+ });
1549
+ };
1550
+
1551
+ wc_stripe.PaymentRequest.prototype.canMakePayment = function () {
1552
+ return new Promise(function (resolve) {
1553
+ this.paymentRequest.canMakePayment().then(function (result) {
1554
+ if (result && !result.applePay) {
1555
+ this.can_pay = true;
1556
+ this.create_button();
1557
+ $(this.container).show();
1558
+ resolve(result);
1559
+ }
1560
+ }.bind(this));
1561
+ }.bind(this));
1562
+ };
1563
+
1564
+ wc_stripe.PaymentRequest.prototype.create_button = function () {
1565
+ this.paymentRequestButton.mount('#wc-stripe-payment-request-container');
1566
+ };
1567
+
1568
+ wc_stripe.CheckoutFields = function (params, page) {
1569
+ this.params = params;
1570
+ this.page = page;
1571
+ this.fields = new Map(Object.keys(this.params).map(function (k) {
1572
+ if (this.params[k].value === null) {
1573
+ this.params[k].value = "";
1574
+ }
1575
+ return [k, this.params[k].value];
1576
+ }.bind(this)));
1577
+
1578
+ if ('checkout' === page) {
1579
+ $('form.checkout').on('change', '.input-text, select', this.onChange.bind(this));
1580
+ $('form.checkout').on('change', '[name="ship_to_different_address"]', this.on_ship_to_address_change.bind(this));
1581
+ this.init_i18n();
1582
+ }
1583
+ };
1584
+
1585
+ wc_stripe.CheckoutFields.prototype.init_i18n = function () {
1586
+ if (typeof wc_address_i18n_params !== 'undefined') {
1587
+ this.locales = $.parseJSON(wc_address_i18n_params.locale.replace(/&quot;/g, '"'));
1588
+ } else {
1589
+ this.locales = null;
1590
+ }
1591
+ };
1592
+
1593
+ wc_stripe.CheckoutFields.prototype.onChange = function (e) {
1594
+ try {
1595
+ var name = e.currentTarget.name,
1596
+ value = e.currentTarget.value;
1597
+ this.fields.set(name, value);
1598
+
1599
+ if (name === 'billing_country' || name === 'shipping_country') {
1600
+ this.update_required_fields(value, name);
1601
+ }
1602
+ } catch (err) {
1603
+ console.log(err);
1604
+ }
1605
+ };
1606
+
1607
+ wc_stripe.CheckoutFields.prototype.update_required_fields = function (country, name) {
1608
+ if (this.locales) {
1609
+ var prefix = name.indexOf('billing_') > -1 ? 'billing_' : 'shipping_';
1610
+ var locale = typeof this.locales[country] !== 'undefined' ? this.locales[country] : this.locales['default'];
1611
+ var fields = $.extend(true, {}, this.locales['default'], locale);
1612
+
1613
+ for (var k in fields) {
1614
+ var k2 = prefix + k;
1615
+
1616
+ if (this.params[k2]) {
1617
+ this.params[k2] = $.extend(true, {}, this.params[k2], fields[k]);
1618
+ }
1619
+ }
1620
+ }
1621
+ };
1622
+
1623
+ wc_stripe.CheckoutFields.prototype.on_ship_to_address_change = function (e) {
1624
+ if ($(e.currentTarget).is(':checked')) {
1625
+ this.update_required_fields($('shipping_country'), 'shipping_country');
1626
+ }
1627
+ };
1628
+
1629
+ wc_stripe.CheckoutFields.prototype.requestFieldInWallet = function (key) {
1630
+ if ('checkout' === this.page) {
1631
+ return this.required(key) && this.isEmpty(key);
1632
+ } else if ('order_pay' === this.page) {
1633
+ return false;
1634
+ }
1635
+
1636
+ return this.required(key);
1637
+ };
1638
+
1639
+ wc_stripe.CheckoutFields.prototype.set = function (k, v, prefix) {
1640
+ if (this[k] && typeof this[k] === 'function') {
1641
+ this[k]().set.call(this, v, prefix);
1642
+ } else {
1643
+ this.fields.set(k, v);
1644
+ }
1645
+ };
1646
+
1647
+ wc_stripe.CheckoutFields.prototype.get = function (k, prefix) {
1648
+ if (this[k] && typeof this[k] === 'function') {
1649
+ var value = this[k]().get.call(this, prefix);
1650
+ } else {
1651
+ var value = this.fields.get(k);
1652
+
1653
+ if (typeof value === 'undefined' || value === null || value === '') {
1654
+ if (typeof prefix !== 'undefined') {
1655
+ value = prefix;
1656
+ }
1657
+ }
1658
+ }
1659
+
1660
+ return typeof value === 'undefined' ? '' : value;
1661
+ };
1662
+ /**
1663
+ * Return true if the field is required
1664
+ * @param k
1665
+ * @returns boolean
1666
+ */
1667
+
1668
+
1669
+ wc_stripe.CheckoutFields.prototype.required = function (k) {
1670
+ if (this.params[k]) {
1671
+ if (typeof this.params[k].required !== 'undefined') {
1672
+ return this.params[k].required;
1673
+ }
1674
+ }
1675
+
1676
+ return false;
1677
+ };
1678
+
1679
+ wc_stripe.CheckoutFields.prototype.isEmpty = function (k) {
1680
+ if (this.fields.has(k)) {
1681
+ var value = this.fields.get(k);
1682
+ return typeof value === 'undefined' || value === null || typeof value === 'string' && value.trim().length === 0;
1683
+ }
1684
+
1685
+ return true;
1686
+ };
1687
+
1688
+ wc_stripe.CheckoutFields.prototype.isValid = function (k) {
1689
+ if (this[k] && typeof this[k] === 'function') {
1690
+ return this[k]().isValid.apply(this, Array.prototype.slice.call(arguments, 1));
1691
+ }
1692
+ }
1693
+
1694
+ wc_stripe.CheckoutFields.prototype.first_name = function () {
1695
+ return {
1696
+ set: function (v, prefix) {
1697
+ this.fields.set(prefix + '_first_name', v);
1698
+ },
1699
+ get: function (prefix) {
1700
+ return this.fields.get(prefix + '_first_name');
1701
+ },
1702
+ isValid: function (v) {
1703
+ return typeof v === 'string' && v.length > 0;
1704
+ }
1705
+ }
1706
+ }
1707
+
1708
+ wc_stripe.CheckoutFields.prototype.last_name = function () {
1709
+ return {
1710
+ set: function (v, prefix) {
1711
+ this.fields.set(prefix + '_last_name', v);
1712
+ },
1713
+ get: function (prefix) {
1714
+ return this.fields.get(prefix + '_last_name');
1715
+ },
1716
+ isValid: function (v) {
1717
+ return typeof v === 'string' && v.length > 0;
1718
+ }
1719
+ }
1720
+ }
1721
+
1722
+ wc_stripe.CheckoutFields.prototype.address_1 = function () {
1723
+ return {
1724
+ set: function set(v, prefix) {
1725
+ this.fields.set(prefix + '_address_1', v);
1726
+ },
1727
+ get: function get(prefix) {
1728
+ return this.fields.get(prefix + '_address_1');
1729
+ },
1730
+ isValid: function (v) {
1731
+ return typeof v === 'string' && v.length > 0;
1732
+ }
1733
+ };
1734
+ };
1735
+
1736
+ wc_stripe.CheckoutFields.prototype.address_2 = function () {
1737
+ return {
1738
+ set: function set(v, prefix) {
1739
+ this.fields.set(prefix + '_address_2', v);
1740
+ },
1741
+ get: function get(prefix) {
1742
+ return this.fields.get(prefix + '_address_2');
1743
+ },
1744
+ isValid: function (v) {
1745
+ return typeof v === 'string' && v.length > 0;
1746
+ }
1747
+ };
1748
+ };
1749
+
1750
+ wc_stripe.CheckoutFields.prototype.name = function () {
1751
+ return {
1752
+ set: function set(v, prefix) {
1753
+ var name = v.split(" ");
1754
+ if (name.length > 0) {
1755
+ this.fields.set(prefix + '_first_name', name[0]);
1756
+ }
1757
+ if (name.length > 1) {
1758
+ this.fields.set(prefix + '_last_name', name[1]);
1759
+ }
1760
+ },
1761
+ get: function get(prefix) {
1762
+ return this.fields.get(prefix + '_first_name') + ' ' + this.fields.get(prefix + '_last_name');
1763
+ }
1764
+ };
1765
+ };
1766
+
1767
+ wc_stripe.CheckoutFields.prototype.email = function () {
1768
+ return {
1769
+ set: function set(v, prefix) {
1770
+ this.fields.set(prefix + '_email', v);
1771
+ },
1772
+ get: function get(prefix) {
1773
+ return this.fields.get(prefix + '_email');
1774
+ },
1775
+ isValid: function (v) {
1776
+ return typeof v === 'string' && v.length > 0;
1777
+ }
1778
+ };
1779
+ };
1780
+
1781
+ wc_stripe.CheckoutFields.prototype.phone = function () {
1782
+ return {
1783
+ set: function set(v, prefix) {
1784
+ this.fields.set(prefix + '_phone', v);
1785
+ },
1786
+ get: function get(prefix) {
1787
+ return this.fields.get(prefix + '_phone');
1788
+ },
1789
+ isValid: function (v) {
1790
+ return typeof v === 'string' && v.length > 0;
1791
+ }
1792
+ };
1793
+ };
1794
+
1795
+ wc_stripe.CheckoutFields.prototype.country = function () {
1796
+ return {
1797
+ set: function set(v, prefix) {
1798
+ this.fields.set(prefix + '_country', v);
1799
+ },
1800
+ get: function get(prefix) {
1801
+ return this.fields.get(prefix + '_country');
1802
+ },
1803
+ isValid: function (v) {
1804
+ return typeof v === 'string' && v.length === 2;
1805
+ }
1806
+ };
1807
+ };
1808
+
1809
+ wc_stripe.CheckoutFields.prototype.state = function () {
1810
+ return {
1811
+ set: function set(v, prefix) {
1812
+ v = v.toUpperCase();
1813
+ if (v.length > 2 && this.page === 'checkout') {
1814
+ $('#' + prefix + '_state option').each(function () {
1815
+ var $option = $(this);
1816
+ var state = $option.text().toUpperCase();
1817
+ if (v === state) {
1818
+ v = $option.val();
1819
+ }
1820
+ });
1821
+ }
1822
+ this.fields.set(prefix + '_state', v);
1823
+ },
1824
+ get: function get(prefix) {
1825
+ return this.fields.get(prefix + '_state');
1826
+ },
1827
+ isValid: function (v) {
1828
+ return typeof v === 'string' && v.length > 0;
1829
+ }
1830
+ };
1831
+ };
1832
+
1833
+ wc_stripe.CheckoutFields.prototype.city = function () {
1834
+ return {
1835
+ set: function set(v, prefix) {
1836
+ this.fields.set(prefix + '_city', v);
1837
+ },
1838
+ get: function get(prefix) {
1839
+ return this.fields.get(prefix + '_city');
1840
+ },
1841
+ isValid: function (v) {
1842
+ return typeof v === 'string' && v.length > 0;
1843
+ }
1844
+ };
1845
+ };
1846
+
1847
+ wc_stripe.CheckoutFields.prototype.postcode = function () {
1848
+ return {
1849
+ set: function set(v, prefix) {
1850
+ this.fields.set(prefix + '_postcode', v);
1851
+ },
1852
+ get: function get(prefix) {
1853
+ return this.fields.get(prefix + '_postcode');
1854
+ },
1855
+ isValid: function (v) {
1856
+ return typeof v === 'string' && v.length > 0;
1857
+ }
1858
+ };
1859
+ };
1860
+
1861
+ wc_stripe.CheckoutFields.prototype.recipient = function () {
1862
+ return wc_stripe.CheckoutFields.prototype.name.apply(this, arguments);
1863
+ }
1864
+
1865
+ wc_stripe.CheckoutFields.prototype.payerName = function () {
1866
+ return wc_stripe.CheckoutFields.prototype.name.apply(this, arguments);
1867
+ };
1868
+
1869
+ wc_stripe.CheckoutFields.prototype.payerEmail = function () {
1870
+ return wc_stripe.CheckoutFields.prototype.email.apply(this, arguments);
1871
+ };
1872
+
1873
+ wc_stripe.CheckoutFields.prototype.payerPhone = function () {
1874
+ return wc_stripe.CheckoutFields.prototype.phone.apply(this, arguments);
1875
+ };
1876
+
1877
+ wc_stripe.CheckoutFields.prototype.phoneNumber = function () {
1878
+ return wc_stripe.CheckoutFields.prototype.phone.apply(this, arguments);
1879
+ };
1880
+
1881
+ wc_stripe.CheckoutFields.prototype.countryCode = function () {
1882
+ return wc_stripe.CheckoutFields.prototype.country.apply(this, arguments);
1883
+ };
1884
+
1885
+ wc_stripe.CheckoutFields.prototype.address1 = function () {
1886
+ return wc_stripe.CheckoutFields.prototype.address_1.apply(this, arguments);
1887
+ };
1888
+
1889
+ wc_stripe.CheckoutFields.prototype.address2 = function () {
1890
+ return wc_stripe.CheckoutFields.prototype.address_2.apply(this, arguments);
1891
+ };
1892
+
1893
+ wc_stripe.CheckoutFields.prototype.line1 = function () {
1894
+ return wc_stripe.CheckoutFields.prototype.address_1.apply(this, arguments);
1895
+ };
1896
+
1897
+ wc_stripe.CheckoutFields.prototype.line2 = function () {
1898
+ return wc_stripe.CheckoutFields.prototype.address_2.apply(this, arguments);
1899
+ };
1900
+
1901
+ wc_stripe.CheckoutFields.prototype.addressLine = function () {
1902
+ return {
1903
+ set: function set(v, prefix) {
1904
+ if (v.length > 0) {
1905
+ this.fields.set(prefix + '_address_1', v[0]);
1906
+ }
1907
+
1908
+ if (v.length > 1) {
1909
+ this.fields.set(prefix + '_address_2', v[1]);
1910
+ }
1911
+ },
1912
+ get: function get(prefix) {
1913
+ return [this.fields.get(prefix + '_address_1'), this.fields.get(prefix + '_address_2')];
1914
+ },
1915
+ isValid: function (v) {
1916
+ if (v.length > 0) {
1917
+ return typeof v[0] === 'string' && v[0].length > 0;
1918
+ }
1919
+ return false;
1920
+ }
1921
+ };
1922
+ };
1923
+
1924
+ wc_stripe.CheckoutFields.prototype.region = function () {
1925
+ return wc_stripe.CheckoutFields.prototype.state.apply(this, arguments);
1926
+ };
1927
+
1928
+ wc_stripe.CheckoutFields.prototype.administrativeArea = function () {
1929
+ return wc_stripe.CheckoutFields.prototype.state.apply(this, arguments);
1930
+ };
1931
+
1932
+ wc_stripe.CheckoutFields.prototype.locality = function () {
1933
+ return wc_stripe.CheckoutFields.prototype.city.apply(this, arguments);
1934
+ };
1935
+
1936
+ wc_stripe.CheckoutFields.prototype.postal_code = function () {
1937
+ return wc_stripe.CheckoutFields.prototype.postcode.apply(this, arguments);
1938
+ }
1939
+
1940
+ wc_stripe.CheckoutFields.prototype.postalCode = function () {
1941
+ return wc_stripe.CheckoutFields.prototype.postcode.apply(this, arguments);
1942
+ };
1943
+ /**
1944
+ * Serialize the fields into an expected format
1945
+ */
1946
+
1947
+
1948
+ wc_stripe.CheckoutFields.prototype.toJson = function () {
1949
+ var data = {};
1950
+ this.fields.forEach(function (value, key) {
1951
+ data[key] = value;
1952
+ });
1953
+ return data;
1954
+ };
1955
+
1956
+ wc_stripe.CheckoutFields.prototype.toFormFields = function (args) {
1957
+ var changes = [];
1958
+ this.fields.forEach(function (value, key) {
1959
+ var name = '[name="' + key + '"]';
1960
+
1961
+ if ($(name).length && value !== '') {
1962
+ if ($(name).val() !== value && $(name).is('select')) {
1963
+ changes.push(name);
1964
+ }
1965
+
1966
+ $(name).val(value);
1967
+ }
1968
+ });
1969
+ if (changes.length > 0) {
1970
+ $(changes.join(',')).trigger('change');
1971
+ }
1972
+ if (typeof args !== 'undefined') {
1973
+ $(document.body).trigger('update_checkout', args);
1974
+ }
1975
+ };
1976
+
1977
+ wc_stripe.CheckoutFields.prototype.validateFields = function (prefix) {
1978
+ for (var k in this.params) {
1979
+ var field = this.params[k];
1980
+ if (k.indexOf(prefix) > -1 && field.required) {
1981
+ if ($('#' + k).length) {
1982
+ var val = $('#' + k).val();
1983
+ if (typeof val === 'undefined' || val === null || val.length === 0) {
1984
+ return false;
1985
+ }
1986
+ }
1987
+ }
1988
+ }
1989
+ return true;
1990
+ }
1991
+
1992
+ try {
1993
+ stripe = Stripe(wc_stripe_params_v3.api_key, {
1994
+ stripeAccount: wc_stripe_params_v3.account
1995
+ });
1996
+ } catch (error) {
1997
+ window.alert(error);
1998
+ console.log(error);
1999
+ return;
2000
+ }
2001
+
2002
+ var checkoutFields = new wc_stripe.CheckoutFields(wc_stripe_checkout_fields, wc_stripe_params_v3.page);
2003
+ })(window, jQuery);
assets/js/frontend/wc-stripe.min.js CHANGED
@@ -1,5 +1,5 @@
1
- (function(a,b){a.wc_stripe={};var c=null;"undefined"==typeof wc_stripe_checkout_fields&&(a.wc_stripe_checkout_fields=[]),wc_stripe.BaseGateway=function(a,d){this.params=a,this.gateway_id=this.params.gateway_id,this.container="undefined"==typeof d?"li.payment_method_".concat(this.gateway_id):d,b(this.container).length||(this.container=".payment_method_".concat(this.gateway_id)),this.token_selector=this.params.token_selector,this.saved_method_selector=this.params.saved_method_selector,this.payment_token_received=!1,this.stripe=c,this.elements=c.elements(b.extend({},{locale:"auto"},this.get_element_options())),this.fields=f,this.initialize()},wc_stripe.BaseGateway.prototype.get_page=function(){return wc_stripe_params_v3.page},wc_stripe.BaseGateway.prototype.set_nonce=function(a){this.fields.set(this.gateway_id+"_token_key",a),b(this.token_selector).val(a)},wc_stripe.BaseGateway.prototype.get_element_options=function(){return{}},wc_stripe.BaseGateway.prototype.initialize=function(){},wc_stripe.BaseGateway.prototype.create_button=function(){},wc_stripe.BaseGateway.prototype.is_gateway_selected=function(){return b("[name=\"payment_method\"]:checked").val()===this.gateway_id},wc_stripe.BaseGateway.prototype.is_saved_method_selected=function(){return this.is_gateway_selected()&&"saved"===b("[name=\""+this.gateway_id+"_payment_type_key\"]:checked").val()},wc_stripe.BaseGateway.prototype.has_checkout_error=function(){return 0<b("#wc_stripe_checkout_error").length&&this.is_gateway_selected()},wc_stripe.BaseGateway.prototype.submit_error=function(a){a=this.get_error_message(a),-1==a.indexOf("</ul>")&&(a="<div class=\"woocommerce-error\">"+a+"</div>"),this.submit_message(a)},wc_stripe.BaseGateway.prototype.submit_error_code=function(a){console.log(a)},wc_stripe.BaseGateway.prototype.get_error_message=function(a){return"object"==typeof a&&a.code&&(wc_stripe_messages[a.code]?a=wc_stripe_messages[a.code]:a=a.message),a},wc_stripe.BaseGateway.prototype.submit_message=function(a){b(".woocommerce-error, .woocommerce-message, .woocommerce-info").remove();var c=b(this.message_container);c.closest("form").length&&(c=c.closest("form")),c.prepend(a),c.removeClass("processing").unblock(),c.find(".input-text, select, input:checkbox").blur(),b.scroll_to_notices?b.scroll_to_notices(c):b("html, body").animate({scrollTop:c.offset().top-100},1e3)},wc_stripe.BaseGateway.prototype.get_first_name=function(a){return b("#"+a+"_first_name").val()},wc_stripe.BaseGateway.prototype.get_last_name=function(a){return b("#"+a+"_last_name").val()},wc_stripe.BaseGateway.prototype.should_save_method=function(){return b("#"+this.gateway_id+"_save_source_key").is(":checked")},wc_stripe.BaseGateway.prototype.is_add_payment_method_page=function(){return"add_payment_method"===this.get_page()||b(document.body).hasClass("woocommerce-add-payment-method")},wc_stripe.BaseGateway.prototype.is_change_payment_method=function(){return"change_payment_method"===this.get_page()},wc_stripe.BaseGateway.prototype.get_selected_payment_method=function(){return b(this.saved_method_selector).val()},wc_stripe.BaseGateway.prototype.needs_shipping=function(){return this.get_gateway_data().needs_shipping},wc_stripe.BaseGateway.prototype.get_currency=function(){return this.get_gateway_data().currency},wc_stripe.BaseGateway.prototype.get_gateway_data=function(){return b(this.container).find(".woocommerce_".concat(this.gateway_id,"_gateway_data")).data("gateway")},wc_stripe.BaseGateway.prototype.set_gateway_data=function(a){b(this.container).find(".woocommerce_".concat(this.gateway_id,"_gateway_data")).data("gateway",a)},wc_stripe.BaseGateway.prototype.get_customer_name=function(a){return this.fields.get(a+"_first_name")+" "+this.fields.get(a+"_last_name")},wc_stripe.BaseGateway.prototype.get_customer_email=function(){return this.fields.get("billing_email")},wc_stripe.BaseGateway.prototype.get_address_field_hash=function(a){for(var b=["_first_name","_last_name","_address_1","_address_2","_postcode","_city","_state","_country"],c="",d=0;d<b.length;d++)c+=this.fields.get(a+b[d])+"_";return c},wc_stripe.BaseGateway.prototype.block=function(){b().block&&b.blockUI({message:null,overlayCSS:{background:"#fff",opacity:.6}})},wc_stripe.BaseGateway.prototype.unblock=function(){b().block&&b.unblockUI()},wc_stripe.BaseGateway.prototype.get_form=function(){return b(this.token_selector).closest("form")},wc_stripe.BaseGateway.prototype.get_total_price=function(){return this.get_gateway_data().total},wc_stripe.BaseGateway.prototype.get_total_price_cents=function(){return this.get_gateway_data().total_cents},wc_stripe.BaseGateway.prototype.set_total_price=function(a){var b=this.get_gateway_data();b.total=a,this.set_gateway_data(b)},wc_stripe.BaseGateway.prototype.set_total_price_cents=function(a){var b=this.get_gateway_data();b.total_cents=a,this.set_gateway_data(b)},wc_stripe.BaseGateway.prototype.set_payment_method=function(a){b("[name=\"payment_method\"][value=\""+a+"\"]").prop("checked",!0).trigger("click")},wc_stripe.BaseGateway.prototype.set_selected_shipping_methods=function(a){if(this.fields.set("shipping_method",a),a&&b("[name^=\"shipping_method\"]").length)for(var c in a){var d=a[c];b("[name=\"shipping_method["+c+"]\"][value=\""+d+"\"]").prop("checked",!0).trigger("change")}},wc_stripe.BaseGateway.prototype.on_token_received=function(a){this.payment_token_received=!0,this.set_nonce(a.id),this.process_checkout()},wc_stripe.BaseGateway.prototype.createPaymentRequest=function(){try{this.paymentRequest=c.paymentRequest(this.get_payment_request_options())}catch(a){return void this.submit_error(a.message)}this.needs_shipping()&&(this.paymentRequest.on("shippingaddresschange",this.update_shipping_address.bind(this)),this.paymentRequest.on("shippingoptionchange",this.update_shipping_method.bind(this))),this.paymentRequest.on("paymentmethod",this.on_payment_method_received.bind(this))},wc_stripe.BaseGateway.prototype.get_payment_request_options=function(){var a={country:this.params.country_code,currency:this.get_currency().toLowerCase(),total:{amount:this.get_total_price_cents(),label:this.params.total_label,pending:!0},requestPayerName:!0,requestPayerEmail:this.fields.requestFieldInWallet("billing_email"),requestPayerPhone:this.fields.requestFieldInWallet("billing_phone"),requestShipping:this.needs_shipping()},b=this.get_display_items(),c=this.get_shipping_options();return b&&(a.displayItems=b),this.needs_shipping()&&c&&(a.shippingOptions=c),a},wc_stripe.BaseGateway.prototype.get_payment_request_update=function(a){var c={currency:this.get_currency().toLowerCase(),total:{amount:parseInt(this.get_total_price_cents()),label:this.params.total_label,pending:!0}},d=this.get_display_items(),e=this.get_shipping_options();return d&&(c.displayItems=d),this.needs_shipping()&&e&&(c.shippingOptions=e),a&&(c=b.extend(!0,{},c,a)),c},wc_stripe.BaseGateway.prototype.get_display_items=function(){return this.get_gateway_data().items},wc_stripe.BaseGateway.prototype.set_display_items=function(a){var b=this.get_gateway_data();b.items=a,this.set_gateway_data(b)},wc_stripe.BaseGateway.prototype.get_shipping_options=function(){return this.get_gateway_data().shipping_options},wc_stripe.BaseGateway.prototype.set_shipping_options=function(a){var b=this.get_gateway_data();b.shipping_options=a,this.set_gateway_data(b)},wc_stripe.BaseGateway.prototype.map_address=function(a){return{city:a.city,postcode:a.postalCode,state:a.region,country:a.country}},wc_stripe.BaseGateway.prototype.on_payment_method_received=function(b){try{this.payment_response=b,this.populate_checkout_fields(b),b.complete("success"),this.on_token_received(b.paymentMethod)}catch(b){a.alert(b)}},wc_stripe.BaseGateway.prototype.populate_checkout_fields=function(a){this.set_nonce(a.paymentMethod.id),this.update_addresses(a)},wc_stripe.BaseGateway.prototype.update_addresses=function(a){a.payerName&&this.fields.set("name",a.payerName,"billing"),a.payerEmail&&this.fields.set("email",a.payerEmail,"billing"),a.payerPhone&&this.fields.set("phone",a.payerPhone,"billing"),a.shippingAddress&&this.populate_shipping_fields(a.shippingAddress),a.paymentMethod.billing_details.address&&this.populate_billing_fields(a.paymentMethod.billing_details.address)},wc_stripe.BaseGateway.prototype.populate_address_fields=function(a,b){for(var c in a)this.fields.set(c,a[c],b)},wc_stripe.BaseGateway.prototype.populate_billing_fields=function(a){this.populate_address_fields(a,"billing")},wc_stripe.BaseGateway.prototype.populate_shipping_fields=function(a){this.populate_address_fields(a,"shipping")},wc_stripe.BaseGateway.prototype.address_mappings=function(){return new wc_stripe.CheckoutFields},wc_stripe.BaseGateway.prototype.ajax_before_send=function(a){0<this.params.user_id&&a.setRequestHeader("X-WP-Nonce",this.params.rest_nonce)},wc_stripe.BaseGateway.prototype.process_checkout=function(){return new Promise(function(){this.block(),b.ajax({url:this.params.routes.checkout,method:"POST",dataType:"json",data:b.extend({},this.serialize_fields(),{payment_method:this.gateway_id,page_id:this.get_page()}),beforeSend:this.ajax_before_send.bind(this)}).done(function(b){return b.reload?void a.location.reload():void("success"===b.result?a.location=b.redirect:(b.messages&&this.submit_error(b.messages),this.unblock()))}.bind(this)).fail(function(a,b,c){this.unblock(),this.submit_error(c)}.bind(this))}.bind(this))},wc_stripe.BaseGateway.prototype.serialize_form=function(a){var c=a.find("input").filter(function(a,c){return!b(c).is("[name^=\"add-to-cart\"]")}.bind(this)).serializeArray(),d={};for(var e in c){var f=c[e];d[f.name]=f.value}return d.payment_method=this.gateway_id,d},wc_stripe.BaseGateway.prototype.serialize_fields=function(){return b.extend({},this.fields.toJson(),b(document.body).triggerHandler("wc_stripe_process_checkout_data",[this,this.fields]))},wc_stripe.BaseGateway.prototype.map_shipping_methods=function(a){var b={};if("default"!==a){var c=a.match(/^([\w+]):(.+)$/);1<c.length&&(b[c[1]]=c[2])}return b},wc_stripe.BaseGateway.prototype.maybe_set_ship_to_different=function(){b("[name=\"ship_to_different_address\"]").length&&b("[name=\"ship_to_different_address\"]").prop("checked",this.get_address_field_hash("billing")!==this.get_address_field_hash("shipping")).trigger("change")},wc_stripe.BaseGateway.prototype.update_shipping_address=function(a){return new Promise(function(c,d){b.ajax({url:this.params.routes.shipping_address,method:"POST",dataType:"json",data:{address:this.map_address(a.shippingAddress),payment_method:this.gateway_id,page_id:this.get_page()},beforeSend:this.ajax_before_send.bind(this)}).done(function(b){b.code?(a.updateWith(b.data.newData),d(b.data)):(a.updateWith(b.data.newData),this.fields.set("shipping_method",data.shipping_method),c(b.data))}.bind(this)).fail(function(){}.bind(this))}.bind(this))},wc_stripe.BaseGateway.prototype.update_shipping_method=function(a){return new Promise(function(c,d){b.ajax({url:this.params.routes.shipping_method,method:"POST",dataType:"json",data:{shipping_method:a.shippingOption.id,payment_method:this.gateway_id,page_id:this.get_page()},beforeSend:this.ajax_before_send.bind(this)}).done(function(b){b.code?(a.updateWith(b.data.newData),d(b.data)):(this.set_selected_shipping_methods(b.data.shipping_methods),a.updateWith(b.data.newData),c(b.data))}.bind(this)).fail(function(a,b,c){this.submit_error(c)}.bind(this))}.bind(this))},wc_stripe.CheckoutGateway=function(){// events for showing gateway payment buttons
2
  this.message_container="li.payment_method_"+this.gateway_id,this.banner_container="li.banner_payment_method_"+this.gateway_id,b(document.body).on("update_checkout",this.update_checkout.bind(this)),b(document.body).on("updated_checkout",this.updated_checkout.bind(this)),b(document.body).on("cfw_updated_checkout",this.updated_checkout.bind(this)),b(document.body).on("checkout_error",this.checkout_error.bind(this)),b(this.token_selector).closest("form").on("checkout_place_order_"+this.gateway_id,this.checkout_place_order.bind(this)),b(document.body).on("wc_stripe_new_method_"+this.gateway_id,this.on_show_new_methods.bind(this)),b(document.body).on("wc_stripe_saved_method_"+this.gateway_id,this.on_show_saved_methods.bind(this)),b(document.body).on("wc_stripe_payment_method_selected",this.on_payment_method_selected.bind(this)),this.banner_enabled()&&b(".woocommerce-billing-fields").length&&b(".wc-stripe-banner-checkout").css("max-width",b(".woocommerce-billing-fields").outerWidth(!0)),this.order_review()},wc_stripe.CheckoutGateway.prototype.order_review=function(){var b=a.location.href,c=b.match(/order_review.+payment_method=([\w]+).+payment_nonce=(.+)/);if(c&&1<c.length){var d=c[1],e=c[2];this.gateway_id===d&&(this.payment_token_received=!0,this.set_nonce(e),this.set_use_new_option(!0))}},wc_stripe.CheckoutGateway.prototype.update_shipping_address=function(){return wc_stripe.BaseGateway.prototype.update_shipping_address.apply(this,arguments).then(function(a){// populate the checkout fields with the address
3
- this.populate_address_fields(a.address,this.get_shipping_prefix()),this.fields.toFormFields({update_shipping_method:!1})}.bind(this))},wc_stripe.CheckoutGateway.prototype.get_shipping_prefix=function(){return this.needs_shipping()&&0<b("[name=\"ship_to_different_address\"]").length&&b("[name=\"ship_to_different_address\"]").is(":checked")?"shipping":"billing"},wc_stripe.CheckoutGateway.prototype.updated_checkout=function(){},wc_stripe.CheckoutGateway.prototype.update_checkout=function(){},wc_stripe.CheckoutGateway.prototype.checkout_error=function(){this.has_checkout_error()&&(this.payment_token_received=!1,this.payment_response=null,this.show_payment_button(),this.hide_place_order())},wc_stripe.CheckoutGateway.prototype.is_valid_checkout=function(){return!b("[name=\"terms\"]").length||b("[name=\"terms\"]").is(":checked")},wc_stripe.CheckoutGateway.prototype.get_payment_method=function(){return b("[name=\"payment_method\"]:checked").val()},wc_stripe.CheckoutGateway.prototype.set_use_new_option=function(a){b("#"+this.gateway_id+"_use_new").prop("checked",a).trigger("change")},wc_stripe.CheckoutGateway.prototype.checkout_place_order=function(){return this.is_valid_checkout()?!!this.is_saved_method_selected()||this.payment_token_received:(this.submit_error(this.params.messages.terms),!1)},wc_stripe.CheckoutGateway.prototype.on_token_received=function(a){this.payment_token_received=!0,this.set_nonce(a.id),this.hide_payment_button(),this.show_place_order()},wc_stripe.CheckoutGateway.prototype.block=function(){b().block&&b("form.checkout").block({message:null,overlayCSS:{background:"#fff",opacity:.6}})},wc_stripe.CheckoutGateway.prototype.unblock=function(){b().block&&b("form.checkout").unblock()},wc_stripe.CheckoutGateway.prototype.hide_place_order=function(){b("#place_order").addClass("wc-stripe-hide")},wc_stripe.CheckoutGateway.prototype.show_place_order=function(){b("#place_order").removeClass("wc-stripe-hide")},wc_stripe.CheckoutGateway.prototype.on_show_new_methods=function(){this.payment_token_received?(this.show_place_order(),this.hide_payment_button()):(this.hide_place_order(),this.show_payment_button())},wc_stripe.CheckoutGateway.prototype.on_show_saved_methods=function(){this.hide_payment_button(),this.show_place_order()},wc_stripe.CheckoutGateway.prototype.show_payment_button=function(){this.$button&&this.$button.show()},wc_stripe.CheckoutGateway.prototype.hide_payment_button=function(){this.$button&&this.$button.hide()},wc_stripe.CheckoutGateway.prototype.trigger_payment_method_selected=function(){this.on_payment_method_selected(null,b("[name=\"payment_method\"]:checked").val())},wc_stripe.CheckoutGateway.prototype.on_payment_method_selected=function(a,b){b===this.gateway_id?this.payment_token_received||this.is_saved_method_selected()?(this.hide_payment_button(),this.show_place_order()):(this.show_payment_button(),this.hide_place_order()):(this.hide_payment_button(),0>b.indexOf("stripe_")&&this.show_place_order())},wc_stripe.CheckoutGateway.prototype.banner_enabled=function(){return"1"===this.params.banner_enabled},wc_stripe.CheckoutGateway.prototype.checkout_fields_valid=function(){function a(a,d){for(var e in d){var f=d[e];if(-1<e.indexOf(a)&&f.required&&b("#"+e).length){var g=b("#"+e).val();if("undefined"==typeof g||null===g||0==g.length)return void(c=!1)}}}if("undefined"==typeof wc_stripe_checkout_fields||"checkout"!==this.get_page())return!0;var c=!0;return a("billing",wc_stripe_checkout_fields),this.needs_shipping()&&b("#ship-to-different-address-checkbox").is(":checked")&&a("shipping",wc_stripe_checkout_fields),c&&(c=this.is_valid_checkout()),c},wc_stripe.ProductGateway=function(){this.message_container="div.product",b("form.cart").on("found_variation",this.found_variation.bind(this)),b("form.cart").on("reset_data",this.reset_variation_data.bind(this)),this.buttonWidth=b("form.cart div.quantity").outerWidth(!0)+b(".single_add_to_cart_button").outerWidth();var a=b(".single_add_to_cart_button").css("marginLeft");a&&(this.buttonWidth+=parseInt(a.replace("px",""))),b(this.container).css("max-width",this.buttonWidth+"px")},wc_stripe.ProductGateway.prototype.get_quantity=function(){return parseInt(b("[name=\"quantity\"]").val())},wc_stripe.ProductGateway.prototype.set_rest_nonce=function(a,b){this.params.rest_nonce=b},wc_stripe.ProductGateway.prototype.found_variation=function(a,b){var c=this.get_gateway_data();c.product.price=b.display_price,c.needs_shipping=!b.is_virtual,c.product.variation=b,this.set_gateway_data(c)},wc_stripe.ProductGateway.prototype.reset_variation_data=function(){var a=this.get_product_data();a.variation=!1,this.set_product_data(a),this.disable_payment_button()},wc_stripe.ProductGateway.prototype.disable_payment_button=function(){this.$button&&this.get_button().prop("disabled",!0).addClass("disabled")},wc_stripe.ProductGateway.prototype.enable_payment_button=function(){this.$button&&this.get_button().prop("disabled",!1).removeClass("disabled")},wc_stripe.ProductGateway.prototype.get_button=function(){return this.$button},wc_stripe.ProductGateway.prototype.is_variable_product=function(){return 0<b("[name=\"variation_id\"]").length},wc_stripe.ProductGateway.prototype.variable_product_selected=function(){return!1!==this.get_product_data().variation},wc_stripe.ProductGateway.prototype.get_product_data=function(){return this.get_gateway_data().product},wc_stripe.ProductGateway.prototype.set_product_data=function(a){var b=this.get_gateway_data();b.product=a,this.set_gateway_data(b)},wc_stripe.ProductGateway.prototype.add_to_cart=function(){return new Promise(function(a,c){this.block(),b.ajax({url:this.params.routes.add_to_cart,method:"POST",dataType:"json",data:{product_id:this.get_product_data().id,variation_id:this.is_variable_product()?b("[name=\"variation_id\"]").val():0,qty:b("[name=\"quantity\"]").val(),payment_method:this.gateway_id,page_id:this.get_page()},beforeSend:this.ajax_before_send.bind(this)}).done(function(b){this.unblock(),b.code?(this.submit_error(b.message),c(b)):(this.set_total_price(b.data.total),this.set_total_price_cents(b.data.totalCents),this.set_display_items(b.data.displayItems),a(b.data))}.bind(this)).fail(function(a,b,c){this.unblock(),this.submit_error(c)}.bind(this))}.bind(this))},wc_stripe.ProductGateway.prototype.cart_calculation=function(a){return new Promise(function(c,d){b.ajax({url:this.params.routes.cart_calculation,method:"POST",dataType:"json",data:{product_id:this.get_product_data().id,variation_id:this.is_variable_product()&&a?a:0,qty:b("[name=\"quantity\"]").val(),payment_method:this.gateway_id},beforeSend:this.ajax_before_send.bind(this)}).done(function(a){a.code?(this.cart_calculation_error=!0,d(a)):(this.set_total_price(a.data.total),this.set_total_price_cents(a.data.totalCents),this.set_display_items(a.data.displayItems),c(a.data))}.bind(this)).fail(function(){}.bind(this))}.bind(this))},wc_stripe.CartGateway=function(){// cart events
4
- this.message_container="div.woocommerce",b(document.body).on("updated_wc_div",this.updated_html.bind(this)),b(document.body).on("updated_cart_totals",this.updated_html.bind(this)),b(document.body).on("wc_cart_emptied",this.cart_emptied.bind(this))},wc_stripe.CartGateway.prototype.submit_error=function(a){this.submit_message(this.get_error_message(a))},wc_stripe.CartGateway.prototype.updated_html=function(){},wc_stripe.CartGateway.prototype.cart_emptied=function(){},wc_stripe.CartGateway.prototype.add_cart_totals_class=function(){b(".cart_totals").addClass("stripe_cart_gateway_active")},wc_stripe.GooglePay=function(){};var d={apiVersion:2,apiVersionMinor:0},e={type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY"],allowedCardNetworks:["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"]}};wc_stripe.GooglePay.prototype.update_addresses=function(a){this.populate_billing_fields(a.paymentMethodData.info.billingAddress),a.shippingAddress&&this.populate_shipping_fields(a.shippingAddress),a.email&&this.fields.set("email",a.email,"billing")},wc_stripe.GooglePay.prototype.map_address=function(a){return{city:a.locality,postcode:a.postalCode,state:a.administrativeArea,country:a.countryCode}},wc_stripe.GooglePay.prototype.update_payment_data=function(a){return new Promise(function(c,d){var e="default"==a.shippingOptionData.id?null:a.shippingOptionData.id;b.when(b.ajax({url:this.params.routes.payment_data,dataType:"json",method:"POST",data:{shipping_address:this.map_address(a.shippingAddress),shipping_method:e,page_id:this.get_page()},beforeSend:this.ajax_before_send.bind(this)})).done(function(a){a.code?d(a.data.data):c(a.data)}.bind(this)).fail(function(){d()}.bind(this))}.bind(this))},wc_stripe.GooglePay.prototype.on_payment_data_changed=function(a){return new Promise(function(b){this.update_payment_data(a).then(function(c){b(c.paymentRequestUpdate),this.set_selected_shipping_methods(c.shipping_methods),this.payment_data_updated(c,a)}.bind(this))["catch"](function(a){b(a)}.bind(this))}.bind(this))},wc_stripe.GooglePay.prototype.payment_data_updated=function(){},wc_stripe.GooglePay.prototype.get_merchant_info=function(){var a={merchantId:this.params.merchant_id,merchantName:this.params.merchant_name};return"TEST"===this.params.environment&&delete a.merchantId,a},wc_stripe.GooglePay.prototype.get_payment_options=function(){var a={environment:this.params.environment,merchantInfo:this.get_merchant_info()};return a.paymentDataCallbacks=this.needs_shipping()?{onPaymentDataChanged:this.on_payment_data_changed.bind(this),onPaymentAuthorized:function(){return new Promise(function(a){a({transactionState:"SUCCESS"})}.bind(this))}.bind(this)}:{onPaymentAuthorized:function(){return new Promise(function(a){a({transactionState:"SUCCESS"})}.bind(this))}},a},wc_stripe.GooglePay.prototype.build_payment_request=function(){var a=b.extend({},d,{emailRequired:function(){return"checkout"===this.get_page()?this.fields.required("billing_email")&&this.fields.isEmpty("billing_email"):"order_pay"!==this.get_page()&&this.fields.required("billing_email")}.bind(this)(),merchantInfo:this.get_merchant_info(),allowedPaymentMethods:[b.extend({type:"CARD",tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:"stripe","stripe:version":"2018-10-31","stripe:publishableKey":this.params.api_key}}},e)],shippingAddressRequired:this.needs_shipping(),transactionInfo:{currencyCode:this.get_currency(),totalPriceStatus:"ESTIMATED",totalPrice:this.get_total_price().toString(),displayItems:this.get_display_items(),totalPriceLabel:this.params.total_price_label}});return a.allowedPaymentMethods[0].parameters.billingAddressRequired=!0,a.allowedPaymentMethods[0].parameters.billingAddressParameters={format:"FULL",phoneNumberRequired:function(){return"checkout"===this.get_page()?this.fields.required("billing_phone")&&this.fields.isEmpty("billing_phone"):"order_pay"!==this.get_page()&&this.fields.required("billing_phone")}.bind(this)()},this.needs_shipping()?(a.shippingAddressParameters={},a.shippingOptionRequired=!0,a.shippingOptionParameters={shippingOptions:this.get_shipping_options()},a.callbackIntents=["SHIPPING_ADDRESS","SHIPPING_OPTION","PAYMENT_AUTHORIZATION"]):a.callbackIntents=["PAYMENT_AUTHORIZATION"],a},wc_stripe.GooglePay.prototype.createPaymentsClient=function(){this.paymentsClient=new google.payments.api.PaymentsClient(this.get_payment_options())},wc_stripe.GooglePay.prototype.isReadyToPay=function(){return new Promise(function(a){var c=b.extend({},d);c.allowedPaymentMethods=[e],this.paymentsClient.isReadyToPay(c).then(function(){this.can_pay=!0,this.create_button(),a()}.bind(this))["catch"](function(a){this.submit_error(a)}.bind(this))}.bind(this))},wc_stripe.GooglePay.prototype.create_button=function(){this.$button&&this.$button.remove(),this.$button=b(this.paymentsClient.createButton({onClick:this.start.bind(this),buttonColor:this.params.button_color,buttonType:this.params.button_style})),this.$button.addClass("gpay-button-container")},wc_stripe.GooglePay.prototype.start=function(){// always recreate the paymentClient to ensure latest data is used.
5
- this.createPaymentsClient(),this.paymentsClient.loadPaymentData(this.build_payment_request()).then(function(a){var b=JSON.parse(a.paymentMethodData.tokenizationData.token);this.update_addresses(a),this.on_token_received(b)}.bind(this))["catch"](function(a){"CANCELED"===a.statusCode||(a.statusMessage&&-1<a.statusMessage.indexOf("paymentDataRequest.callbackIntent")?this.submit_error_code("DEVELOPER_ERROR_WHITELIST"):this.submit_error(a.statusMessage))}.bind(this))},wc_stripe.ApplePay=function(){},wc_stripe.ApplePay.prototype.initialize=function(){var a=".apple-pay-button";0>["checkout","order_pay"].indexOf(this.get_page())&&(a=this.container+" .apple-pay-button"),b(document.body).on("click",a,this.start.bind(this)),this.createPaymentRequest(),this.canMakePayment()},wc_stripe.ApplePay.prototype.create_button=function(){this.$button&&this.$button.remove(),this.$button=b(this.params.button),this.append_button()},wc_stripe.ApplePay.prototype.canMakePayment=function(){return new Promise(function(a){this.paymentRequest.canMakePayment().then(function(c){c&&c.applePay&&(this.can_pay=!0,this.create_button(),b(this.container).show(),a(c))}.bind(this))}.bind(this))},wc_stripe.ApplePay.prototype.start=function(a){a.preventDefault(),this.paymentRequest.update(this.get_payment_request_update({total:{pending:!1}})),this.paymentRequest.show()},wc_stripe.PaymentRequest=function(){},wc_stripe.PaymentRequest.prototype.initialize=function(){this.createPaymentRequest(),this.canMakePayment(),this.createPaymentRequestButton(),this.paymentRequestButton.on("click",this.button_click.bind(this))},wc_stripe.PaymentRequest.prototype.button_click=function(){},wc_stripe.PaymentRequest.prototype.createPaymentRequestButton=function(){this.paymentRequestButton=this.elements.create("paymentRequestButton",{paymentRequest:this.paymentRequest,style:{paymentRequestButton:{type:this.params.button.type,theme:this.params.button.theme,height:this.params.button.height}}})},wc_stripe.PaymentRequest.prototype.canMakePayment=function(){return new Promise(function(a){this.paymentRequest.canMakePayment().then(function(c){c&&!c.applePay&&(this.can_pay=!0,this.create_button(),b(this.container).show(),a(c))}.bind(this))}.bind(this))},wc_stripe.PaymentRequest.prototype.create_button=function(){this.paymentRequestButton.mount("#wc-stripe-payment-request-container")},wc_stripe.CheckoutFields=function(a,c){this.params=a,this.page=c,this.fields=new Map(Object.keys(this.params).map(function(a){return[a,this.params[a].value]}.bind(this))),"checkout"===c&&(b("form.checkout").on("change",".input-text, select",this.onChange.bind(this)),b("form.checkout").on("change","[name=\"ship_to_different_address\"]",this.on_ship_to_address_change.bind(this)),this.init_i18n())},wc_stripe.CheckoutFields.prototype.init_i18n=function(){this.locales="undefined"==typeof wc_address_i18n_params?null:b.parseJSON(wc_address_i18n_params.locale.replace(/&quot;/g,"\""))},wc_stripe.CheckoutFields.prototype.onChange=function(a){try{var b=a.currentTarget.name,c=a.currentTarget.value;this.fields.set(b,c),("billing_country"===b||"shipping_country"===b)&&this.update_required_fields(c,b)}catch(a){console.log(a)}},wc_stripe.CheckoutFields.prototype.update_required_fields=function(a,c){if(this.locales){var d=-1<c.indexOf("billing_")?"billing_":"shipping_",e="undefined"==typeof this.locales[a]?this.locales["default"]:this.locales[a],f=b.extend(!0,{},this.locales["default"],e);for(var g in f){var h=d+g;this.params[h]&&(this.params[h]=b.extend(!0,{},this.params[h],f[g]))}}},wc_stripe.CheckoutFields.prototype.on_ship_to_address_change=function(a){b(a.currentTarget).is(":checked")&&this.update_required_fields(b("shipping_country"),"shipping_country")},wc_stripe.CheckoutFields.prototype.requestFieldInWallet=function(a){if("checkout"===this.page)return this.required(a)&&this.isEmpty(a);return"order_pay"!==this.page&&this.required(a)},wc_stripe.CheckoutFields.prototype.set=function(a,b,c){this[a]&&"function"==typeof this[a]?this[a]().set.call(this,b,c):this.fields.set(a,b)},wc_stripe.CheckoutFields.prototype.get=function(a,b){if(this[a]&&"function"==typeof this[a])var c=this[a]().get.call(this,b);else{var c=this.fields.get(a);("undefined"==typeof c||null===c||""===c)&&"undefined"!=typeof b&&(c=b)}return"undefined"==typeof c?"":c},wc_stripe.CheckoutFields.prototype.required=function(a){return!!(this.params[a]&&"undefined"!=typeof this.params[a].required)&&this.params[a].required},wc_stripe.CheckoutFields.prototype.isEmpty=function(a){if(this.fields.has(a)){var b=this.fields.get(a);return"undefined"==typeof b||null===b||"string"==typeof b&&0===b.trim().length}return!0},wc_stripe.CheckoutFields.prototype.name=function(){return{set:function(a,b){var c=a.split(" ");this.fields.set(b+"_first_name",c[0]),this.fields.set(b+"_last_name",c[1])},get:function(a){return this.fields.get(a+"_first_name")+" "+this.fields.get(a+"_last_name")}}},wc_stripe.CheckoutFields.prototype.payerName=function(){return wc_stripe.CheckoutFields.prototype.name.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.email=function(){return{set:function(a,b){this.fields.set(b+"_email",a)},get:function(a){return this.fields.get(a+"_email")}}},wc_stripe.CheckoutFields.prototype.payerEmail=function(){return wc_stripe.CheckoutFields.prototype.email.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.phone=function(){return{set:function(a,b){this.fields.set(b+"_phone",a)},get:function(a){return this.fields.get(a+"_phone")}}},wc_stripe.CheckoutFields.prototype.payerPhone=function(){return wc_stripe.CheckoutFields.prototype.phone.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.phoneNumber=function(){return wc_stripe.CheckoutFields.prototype.phone.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.recipient=function(){return{set:function(a,b){var c=a.split(" ");0<c.length&&this.fields.set(b+"_first_name",c[0]),1<c.length&&this.fields.set(b+"_last_name",c[1])},get:function(a){return this.fields.get(a+"_first_name")+" "+this.fields.get(a+"_last_name")}}},wc_stripe.CheckoutFields.prototype.country=function(){return{set:function(a,b){this.fields.set(b+"_country",a)},get:function(a){return this.fields.get(a+"_country")}}},wc_stripe.CheckoutFields.prototype.countryCode=function(){return wc_stripe.CheckoutFields.prototype.country.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.address1=function(){return{set:function(a,b){this.fields.set(b+"_address_1",a)},get:function(a){return this.fields.get(a+"_address_1")}}},wc_stripe.CheckoutFields.prototype.address2=function(){return{set:function(a,b){this.fields.set(b+"_address_2",a)},get:function(a){this.fields.get(a+"_address_2")}}},wc_stripe.CheckoutFields.prototype.line1=function(){return wc_stripe.CheckoutFields.prototype.address1.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.line2=function(){return wc_stripe.CheckoutFields.prototype.address2.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.addressLine=function(){return{set:function(a,b){0<a.length&&this.fields.set(b+"_address_1",a[0]),1<a.length&&this.fields.set(b+"_address_2",a[1])},get:function(a){return[this.fields.get(a+"_address_1"),this.fields.get(a+"_address_2")]}}},wc_stripe.CheckoutFields.prototype.state=function(){return{set:function(a,c){a=a.toUpperCase(),2<a.length&&"checkout"===this.page&&b("#"+c+"_state option").each(function(){var c=b(this),d=c.text().toUpperCase();a===d&&(a=c.val())}),this.fields.set(c+"_state",a)},get:function(a){return this.fields.get(a+"_state")}}},wc_stripe.CheckoutFields.prototype.region=function(){return wc_stripe.CheckoutFields.prototype.state.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.administrativeArea=function(){return wc_stripe.CheckoutFields.prototype.state.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.city=function(){return{set:function(a,b){this.fields.set(b+"_city",a)},get:function(a){this.fields.get(a+"_city")}}},wc_stripe.CheckoutFields.prototype.locality=function(){return wc_stripe.CheckoutFields.prototype.city.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.postcode=function(){return{set:function(a,b){this.fields.set(b+"_postcode",a)},get:function(a){this.fields.get(a+"_postcode")}}},wc_stripe.CheckoutFields.prototype.postal_code=function(){return wc_stripe.CheckoutFields.prototype.postcode.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.postalCode=function(){return wc_stripe.CheckoutFields.prototype.postcode.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.toJson=function(){var a={};return this.fields.forEach(function(b,c){a[c]=b}),a},wc_stripe.CheckoutFields.prototype.toFormFields=function(a){var c=[];this.fields.forEach(function(a,d){var e="[name=\""+d+"\"]";b(e).length&&""!==a&&(b(e).val()!==a&&b(e).is("select")&&c.push(e),b(e).val(a))}),0<c.length&&b(c.join(",")).trigger("change"),"undefined"!=typeof a&&b(document.body).trigger("update_checkout",a)};try{c=Stripe(wc_stripe_params_v3.api_key,{stripeAccount:wc_stripe_params_v3.account})}catch(b){return a.alert(b),void console.log(b)}var f=new wc_stripe.CheckoutFields(wc_stripe_checkout_fields,wc_stripe_params_v3.page)})(window,jQuery);
1
+ (function(a,b){a.wc_stripe={};var c=null;"undefined"==typeof wc_stripe_checkout_fields&&(a.wc_stripe_checkout_fields=[]),wc_stripe.BaseGateway=function(a,d){this.params=a,this.gateway_id=this.params.gateway_id,this.container="undefined"==typeof d?"li.payment_method_".concat(this.gateway_id):d,b(this.container).length||(this.container=".payment_method_".concat(this.gateway_id)),this.token_selector=this.params.token_selector,this.saved_method_selector=this.params.saved_method_selector,this.payment_token_received=!1,this.stripe=c,this.elements=c.elements(b.extend({},{locale:"auto"},this.get_element_options())),this.fields=f,this.initialize()},wc_stripe.BaseGateway.prototype.get_page=function(){return wc_stripe_params_v3.page},wc_stripe.BaseGateway.prototype.set_nonce=function(a){this.fields.set(this.gateway_id+"_token_key",a),b(this.token_selector).val(a)},wc_stripe.BaseGateway.prototype.get_element_options=function(){return{}},wc_stripe.BaseGateway.prototype.initialize=function(){},wc_stripe.BaseGateway.prototype.create_button=function(){},wc_stripe.BaseGateway.prototype.is_gateway_selected=function(){return b("[name=\"payment_method\"]:checked").val()===this.gateway_id},wc_stripe.BaseGateway.prototype.is_saved_method_selected=function(){return this.is_gateway_selected()&&"saved"===b("[name=\""+this.gateway_id+"_payment_type_key\"]:checked").val()},wc_stripe.BaseGateway.prototype.has_checkout_error=function(){return 0<b("#wc_stripe_checkout_error").length&&this.is_gateway_selected()},wc_stripe.BaseGateway.prototype.submit_error=function(a){a=this.get_error_message(a),-1==a.indexOf("</ul>")&&(a="<div class=\"woocommerce-error\">"+a+"</div>"),this.submit_message(a)},wc_stripe.BaseGateway.prototype.submit_error_code=function(a){console.log(a)},wc_stripe.BaseGateway.prototype.get_error_message=function(a){return"object"==typeof a&&a.code&&(wc_stripe_messages[a.code]?a=wc_stripe_messages[a.code]:a=a.message),a},wc_stripe.BaseGateway.prototype.submit_message=function(a){b(".woocommerce-error, .woocommerce-message, .woocommerce-info").remove();var c=b(this.message_container);c.closest("form").length&&(c=c.closest("form")),c.prepend(a),c.removeClass("processing").unblock(),c.find(".input-text, select, input:checkbox").blur(),b.scroll_to_notices?b.scroll_to_notices(c):b("html, body").animate({scrollTop:c.offset().top-100},1e3)},wc_stripe.BaseGateway.prototype.get_first_name=function(a){return b("#"+a+"_first_name").val()},wc_stripe.BaseGateway.prototype.get_last_name=function(a){return b("#"+a+"_last_name").val()},wc_stripe.BaseGateway.prototype.get_shipping_prefix=function(){return this.needs_shipping()&&0<b("[name=\"ship_to_different_address\"]").length&&b("[name=\"ship_to_different_address\"]").is(":checked")?"shipping":"billing"},wc_stripe.BaseGateway.prototype.should_save_method=function(){return b("#"+this.gateway_id+"_save_source_key").is(":checked")},wc_stripe.BaseGateway.prototype.is_add_payment_method_page=function(){return"add_payment_method"===this.get_page()||b(document.body).hasClass("woocommerce-add-payment-method")},wc_stripe.BaseGateway.prototype.is_change_payment_method=function(){return"change_payment_method"===this.get_page()},wc_stripe.BaseGateway.prototype.get_selected_payment_method=function(){return b(this.saved_method_selector).val()},wc_stripe.BaseGateway.prototype.needs_shipping=function(){return this.get_gateway_data().needs_shipping},wc_stripe.BaseGateway.prototype.get_currency=function(){return this.get_gateway_data().currency},wc_stripe.BaseGateway.prototype.get_gateway_data=function(){return b(this.container).find(".woocommerce_".concat(this.gateway_id,"_gateway_data")).data("gateway")},wc_stripe.BaseGateway.prototype.set_gateway_data=function(a){b(this.container).find(".woocommerce_".concat(this.gateway_id,"_gateway_data")).data("gateway",a)},wc_stripe.BaseGateway.prototype.get_customer_name=function(a){return this.fields.get(a+"_first_name")+" "+this.fields.get(a+"_last_name")},wc_stripe.BaseGateway.prototype.get_customer_email=function(){return this.fields.get("billing_email")},wc_stripe.BaseGateway.prototype.get_address_field_hash=function(a){for(var b=["_first_name","_last_name","_address_1","_address_2","_postcode","_city","_state","_country"],c="",d=0;d<b.length;d++)c+=this.fields.get(a+b[d])+"_";return c},wc_stripe.BaseGateway.prototype.block=function(){b().block&&b.blockUI({message:null,overlayCSS:{background:"#fff",opacity:.6}})},wc_stripe.BaseGateway.prototype.unblock=function(){b().block&&b.unblockUI()},wc_stripe.BaseGateway.prototype.get_form=function(){return b(this.token_selector).closest("form")},wc_stripe.BaseGateway.prototype.get_total_price=function(){return this.get_gateway_data().total},wc_stripe.BaseGateway.prototype.get_total_price_cents=function(){return this.get_gateway_data().total_cents},wc_stripe.BaseGateway.prototype.set_total_price=function(a){var b=this.get_gateway_data();b.total=a,this.set_gateway_data(b)},wc_stripe.BaseGateway.prototype.set_total_price_cents=function(a){var b=this.get_gateway_data();b.total_cents=a,this.set_gateway_data(b)},wc_stripe.BaseGateway.prototype.set_payment_method=function(a){b("[name=\"payment_method\"][value=\""+a+"\"]").prop("checked",!0).trigger("click")},wc_stripe.BaseGateway.prototype.set_selected_shipping_methods=function(a){if(this.fields.set("shipping_method",a),a&&b("[name^=\"shipping_method\"]").length)for(var c in a){var d=a[c];b("[name=\"shipping_method["+c+"]\"][value=\""+d+"\"]").prop("checked",!0).trigger("change")}},wc_stripe.BaseGateway.prototype.on_token_received=function(a){this.payment_token_received=!0,this.set_nonce(a.id),this.process_checkout()},wc_stripe.BaseGateway.prototype.createPaymentRequest=function(){try{this.payment_request_options=this.get_payment_request_options(),this.paymentRequest=c.paymentRequest(this.payment_request_options)}catch(a){return void this.submit_error(a.message)}this.payment_request_options.requestShipping&&(this.paymentRequest.on("shippingaddresschange",this.update_shipping_address.bind(this)),this.paymentRequest.on("shippingoptionchange",this.update_shipping_method.bind(this))),this.paymentRequest.on("paymentmethod",this.on_payment_method_received.bind(this))},wc_stripe.BaseGateway.prototype.get_payment_request_options=function(){var a={country:this.params.country_code,currency:this.get_currency().toLowerCase(),total:{amount:this.get_total_price_cents(),label:this.params.total_label,pending:!0},requestPayerName:!0,requestPayerEmail:this.fields.requestFieldInWallet("billing_email"),requestPayerPhone:this.fields.requestFieldInWallet("billing_phone"),requestShipping:function(){if(this.needs_shipping()){var a=this.get_shipping_prefix();if(this.is_current_page("checkout")&&!this.is_valid_address(this.get_address_object(a),a,["email","phone"])||!this.is_current_page("checkout"))return!0}return!1}.bind(this)()},b=this.get_display_items(),c=this.get_shipping_options();return b&&(a.displayItems=b),a.requestShipping&&c&&(a.shippingOptions=c),a},wc_stripe.BaseGateway.prototype.get_payment_request_update=function(a){var c={currency:this.get_currency().toLowerCase(),total:{amount:parseInt(this.get_total_price_cents()),label:this.params.total_label,pending:!0}},d=this.get_display_items(),e=this.get_shipping_options();return d&&(c.displayItems=d),this.payment_request_options.requestShipping&&e&&(c.shippingOptions=e),a&&(c=b.extend(!0,{},c,a)),c},wc_stripe.BaseGateway.prototype.get_display_items=function(){return this.get_gateway_data().items},wc_stripe.BaseGateway.prototype.set_display_items=function(a){var b=this.get_gateway_data();b.items=a,this.set_gateway_data(b)},wc_stripe.BaseGateway.prototype.get_shipping_options=function(){return this.get_gateway_data().shipping_options},wc_stripe.BaseGateway.prototype.set_shipping_options=function(a){var b=this.get_gateway_data();b.shipping_options=a,this.set_gateway_data(b)},wc_stripe.BaseGateway.prototype.map_address=function(a){return{city:a.city,postcode:a.postalCode,state:a.region,country:a.country}},wc_stripe.BaseGateway.prototype.on_payment_method_received=function(b){try{this.payment_response=b,this.populate_checkout_fields(b),b.complete("success"),this.on_token_received(b.paymentMethod)}catch(b){a.alert(b)}},wc_stripe.BaseGateway.prototype.populate_checkout_fields=function(a){this.set_nonce(a.paymentMethod.id),this.update_addresses(a)},wc_stripe.BaseGateway.prototype.update_addresses=function(a){a.payerName&&this.fields.set("name",a.payerName,"billing"),a.payerEmail&&this.fields.set("email",a.payerEmail,"billing"),a.payerPhone&&this.fields.set("phone",a.payerPhone,"billing"),a.shippingAddress&&this.populate_shipping_fields(a.shippingAddress),a.paymentMethod.billing_details.address&&this.populate_billing_fields(a.paymentMethod.billing_details.address)},wc_stripe.BaseGateway.prototype.populate_address_fields=function(a,b){for(var c in a)null!==a[c]&&this.fields.set(c,a[c],b)},wc_stripe.BaseGateway.prototype.populate_billing_fields=function(a){this.populate_address_fields(a,"billing")},wc_stripe.BaseGateway.prototype.populate_shipping_fields=function(a){this.populate_address_fields(a,"shipping")},wc_stripe.BaseGateway.prototype.get_address_fields=function(){return["first_name","last_name","country","address_1","address_2","city","state","postcode","phone","email"]},wc_stripe.BaseGateway.prototype.get_address_object=function(a){var b={};return this.get_address_fields().forEach(function(c){b[c]=this.fields.get(c,a)}.bind(this)),b},wc_stripe.BaseGateway.prototype.is_current_page=function(a){return this.get_page()===a},wc_stripe.BaseGateway.prototype.is_valid_address=function(a,c,d){if(b.isEmptyObject(a))return!1;var e=this.get_address_fields();"undefined"!=typeof d&&d.forEach(function(a){-1<e.indexOf(a)&&e.splice(e.indexOf(a),1)});for(var f=0;f<e.length;f++){var g=e[f],h=this.fields.required(c+"_"+g);if(h&&(!a[g]||"undefined"==typeof a[g]||!this.fields.isValid(g,a[g],a)))return!1}return!0},wc_stripe.BaseGateway.prototype.ajax_before_send=function(a){0<this.params.user_id&&a.setRequestHeader("X-WP-Nonce",this.params.rest_nonce)},wc_stripe.BaseGateway.prototype.process_checkout=function(){return new Promise(function(){this.block(),b.ajax({url:this.params.routes.checkout,method:"POST",dataType:"json",data:b.extend({},this.serialize_fields(),{payment_method:this.gateway_id,page_id:this.get_page()}),beforeSend:this.ajax_before_send.bind(this)}).done(function(b){return b.reload?void a.location.reload():void("success"===b.result?a.location=b.redirect:(b.messages&&this.submit_error(b.messages),this.unblock()))}.bind(this)).fail(function(a,b,c){this.unblock(),this.submit_error(c)}.bind(this))}.bind(this))},wc_stripe.BaseGateway.prototype.serialize_form=function(a){var c=a.find("input").filter(function(a,c){return!b(c).is("[name^=\"add-to-cart\"]")}.bind(this)).serializeArray(),d={};for(var e in c){var f=c[e];d[f.name]=f.value}return d.payment_method=this.gateway_id,d},wc_stripe.BaseGateway.prototype.serialize_fields=function(){return b.extend({},this.fields.toJson(),b(document.body).triggerHandler("wc_stripe_process_checkout_data",[this,this.fields]))},wc_stripe.BaseGateway.prototype.map_shipping_methods=function(a){var b={};if("default"!==a){var c=a.match(/^([\w+]):(.+)$/);1<c.length&&(b[c[1]]=c[2])}return b},wc_stripe.BaseGateway.prototype.maybe_set_ship_to_different=function(){b("[name=\"ship_to_different_address\"]").length&&b("[name=\"ship_to_different_address\"]").prop("checked",this.get_address_field_hash("billing")!==this.get_address_field_hash("shipping")).trigger("change")},wc_stripe.BaseGateway.prototype.update_shipping_address=function(a){return new Promise(function(c,d){b.ajax({url:this.params.routes.shipping_address,method:"POST",dataType:"json",data:{address:this.map_address(a.shippingAddress),payment_method:this.gateway_id,page_id:this.get_page()},beforeSend:this.ajax_before_send.bind(this)}).done(function(b){b.code?(a.updateWith(b.data.newData),d(b.data)):(a.updateWith(b.data.newData),this.fields.set("shipping_method",b.data.shipping_method),c(b.data))}.bind(this)).fail(function(){}.bind(this))}.bind(this))},wc_stripe.BaseGateway.prototype.update_shipping_method=function(a){return new Promise(function(c,d){b.ajax({url:this.params.routes.shipping_method,method:"POST",dataType:"json",data:{shipping_method:a.shippingOption.id,payment_method:this.gateway_id,page_id:this.get_page()},beforeSend:this.ajax_before_send.bind(this)}).done(function(b){b.code?(a.updateWith(b.data.newData),d(b.data)):(this.set_selected_shipping_methods(b.data.shipping_methods),a.updateWith(b.data.newData),c(b.data))}.bind(this)).fail(function(a,b,c){this.submit_error(c)}.bind(this))}.bind(this))},wc_stripe.CheckoutGateway=function(){// events for showing gateway payment buttons
2
  this.message_container="li.payment_method_"+this.gateway_id,this.banner_container="li.banner_payment_method_"+this.gateway_id,b(document.body).on("update_checkout",this.update_checkout.bind(this)),b(document.body).on("updated_checkout",this.updated_checkout.bind(this)),b(document.body).on("cfw_updated_checkout",this.updated_checkout.bind(this)),b(document.body).on("checkout_error",this.checkout_error.bind(this)),b(this.token_selector).closest("form").on("checkout_place_order_"+this.gateway_id,this.checkout_place_order.bind(this)),b(document.body).on("wc_stripe_new_method_"+this.gateway_id,this.on_show_new_methods.bind(this)),b(document.body).on("wc_stripe_saved_method_"+this.gateway_id,this.on_show_saved_methods.bind(this)),b(document.body).on("wc_stripe_payment_method_selected",this.on_payment_method_selected.bind(this)),this.banner_enabled()&&b(".woocommerce-billing-fields").length&&b(".wc-stripe-banner-checkout").css("max-width",b(".woocommerce-billing-fields").outerWidth(!0)),this.order_review()},wc_stripe.CheckoutGateway.prototype.order_review=function(){var b=a.location.href,c=b.match(/order_review.+payment_method=([\w]+).+payment_nonce=(.+)/);if(c&&1<c.length){var d=c[1],e=c[2];this.gateway_id===d&&(this.payment_token_received=!0,this.set_nonce(e),this.set_use_new_option(!0))}},wc_stripe.CheckoutGateway.prototype.update_shipping_address=function(){return wc_stripe.BaseGateway.prototype.update_shipping_address.apply(this,arguments).then(function(a){// populate the checkout fields with the address
3
+ this.populate_address_fields(a.address,this.get_shipping_prefix()),this.fields.toFormFields({update_shipping_method:!1})}.bind(this))},wc_stripe.CheckoutGateway.prototype.updated_checkout=function(){},wc_stripe.CheckoutGateway.prototype.update_checkout=function(){},wc_stripe.CheckoutGateway.prototype.checkout_error=function(){this.has_checkout_error()&&(this.payment_token_received=!1,this.payment_response=null,this.show_payment_button(),this.hide_place_order())},wc_stripe.CheckoutGateway.prototype.is_valid_checkout=function(){return!b("[name=\"terms\"]").length||b("[name=\"terms\"]").is(":checked")},wc_stripe.CheckoutGateway.prototype.get_payment_method=function(){return b("[name=\"payment_method\"]:checked").val()},wc_stripe.CheckoutGateway.prototype.set_use_new_option=function(a){b("#"+this.gateway_id+"_use_new").prop("checked",a).trigger("change")},wc_stripe.CheckoutGateway.prototype.checkout_place_order=function(){return this.is_valid_checkout()?!!this.is_saved_method_selected()||this.payment_token_received:(this.submit_error(this.params.messages.terms),!1)},wc_stripe.CheckoutGateway.prototype.on_token_received=function(a){this.payment_token_received=!0,this.set_nonce(a.id),this.hide_payment_button(),this.show_place_order()},wc_stripe.CheckoutGateway.prototype.block=function(){b().block&&b("form.checkout").block({message:null,overlayCSS:{background:"#fff",opacity:.6}})},wc_stripe.CheckoutGateway.prototype.unblock=function(){b().block&&b("form.checkout").unblock()},wc_stripe.CheckoutGateway.prototype.hide_place_order=function(){b("#place_order").addClass("wc-stripe-hide")},wc_stripe.CheckoutGateway.prototype.show_place_order=function(){b("#place_order").removeClass("wc-stripe-hide")},wc_stripe.CheckoutGateway.prototype.on_show_new_methods=function(){this.payment_token_received?(this.show_place_order(),this.hide_payment_button()):(this.hide_place_order(),this.show_payment_button())},wc_stripe.CheckoutGateway.prototype.on_show_saved_methods=function(){this.hide_payment_button(),this.show_place_order()},wc_stripe.CheckoutGateway.prototype.show_payment_button=function(){this.$button&&this.$button.show()},wc_stripe.CheckoutGateway.prototype.hide_payment_button=function(){this.$button&&this.$button.hide()},wc_stripe.CheckoutGateway.prototype.trigger_payment_method_selected=function(){this.on_payment_method_selected(null,b("[name=\"payment_method\"]:checked").val())},wc_stripe.CheckoutGateway.prototype.on_payment_method_selected=function(a,b){b===this.gateway_id?this.payment_token_received||this.is_saved_method_selected()?(this.hide_payment_button(),this.show_place_order()):(this.show_payment_button(),this.hide_place_order()):(this.hide_payment_button(),0>b.indexOf("stripe_")&&this.show_place_order())},wc_stripe.CheckoutGateway.prototype.banner_enabled=function(){return"1"===this.params.banner_enabled},wc_stripe.CheckoutGateway.prototype.checkout_fields_valid=function(){if(0>["checkout","order_pay"].indexOf(this.get_page()))return!0;var a=!0;return(a=this.fields.validateFields("billing"))?this.needs_shipping()&&b("#ship-to-different-address-checkbox").is(":checked")?!(a=this.fields.validateFields("shipping"))&&this.submit_error(this.params.messages.required_field):!(a=this.is_valid_checkout())&&this.submit_error(this.params.messages.terms):this.submit_error(this.params.messages.required_field),a},wc_stripe.ProductGateway=function(){this.message_container="div.product",b("form.cart").on("found_variation",this.found_variation.bind(this)),b("form.cart").on("reset_data",this.reset_variation_data.bind(this)),this.buttonWidth=b("form.cart div.quantity").outerWidth(!0)+b(".single_add_to_cart_button").outerWidth();var a=b(".single_add_to_cart_button").css("marginLeft");a&&(this.buttonWidth+=parseInt(a.replace("px",""))),b(this.container).css("max-width",this.buttonWidth+"px")},wc_stripe.ProductGateway.prototype.get_quantity=function(){return parseInt(b("[name=\"quantity\"]").val())},wc_stripe.ProductGateway.prototype.set_rest_nonce=function(a,b){this.params.rest_nonce=b},wc_stripe.ProductGateway.prototype.found_variation=function(a,b){var c=this.get_gateway_data();c.product.price=b.display_price,c.needs_shipping=!b.is_virtual,c.product.variation=b,this.set_gateway_data(c)},wc_stripe.ProductGateway.prototype.reset_variation_data=function(){var a=this.get_product_data();a.variation=!1,this.set_product_data(a),this.disable_payment_button()},wc_stripe.ProductGateway.prototype.disable_payment_button=function(){this.$button&&this.get_button().prop("disabled",!0).addClass("disabled")},wc_stripe.ProductGateway.prototype.enable_payment_button=function(){this.$button&&this.get_button().prop("disabled",!1).removeClass("disabled")},wc_stripe.ProductGateway.prototype.get_button=function(){return this.$button},wc_stripe.ProductGateway.prototype.is_variable_product=function(){return 0<b("[name=\"variation_id\"]").length},wc_stripe.ProductGateway.prototype.variable_product_selected=function(){return!1!==this.get_product_data().variation},wc_stripe.ProductGateway.prototype.get_product_data=function(){return this.get_gateway_data().product},wc_stripe.ProductGateway.prototype.set_product_data=function(a){var b=this.get_gateway_data();b.product=a,this.set_gateway_data(b)},wc_stripe.ProductGateway.prototype.add_to_cart=function(){return new Promise(function(a,c){this.block(),b.ajax({url:this.params.routes.add_to_cart,method:"POST",dataType:"json",data:{product_id:this.get_product_data().id,variation_id:this.is_variable_product()?b("[name=\"variation_id\"]").val():0,qty:b("[name=\"quantity\"]").val(),payment_method:this.gateway_id,page_id:this.get_page()},beforeSend:this.ajax_before_send.bind(this)}).done(function(b){this.unblock(),b.code?(this.submit_error(b.message),c(b)):(this.set_total_price(b.data.total),this.set_total_price_cents(b.data.totalCents),this.set_display_items(b.data.displayItems),a(b.data))}.bind(this)).fail(function(a,b,c){this.unblock(),this.submit_error(c)}.bind(this))}.bind(this))},wc_stripe.ProductGateway.prototype.cart_calculation=function(a){return new Promise(function(c,d){b.ajax({url:this.params.routes.cart_calculation,method:"POST",dataType:"json",data:{product_id:this.get_product_data().id,variation_id:this.is_variable_product()&&a?a:0,qty:b("[name=\"quantity\"]").val(),payment_method:this.gateway_id},beforeSend:this.ajax_before_send.bind(this)}).done(function(a){a.code?(this.cart_calculation_error=!0,d(a)):(this.set_total_price(a.data.total),this.set_total_price_cents(a.data.totalCents),this.set_display_items(a.data.displayItems),c(a.data))}.bind(this)).fail(function(){}.bind(this))}.bind(this))},wc_stripe.CartGateway=function(){// cart events
4
+ this.message_container="div.woocommerce",b(document.body).on("updated_wc_div",this.updated_html.bind(this)),b(document.body).on("updated_cart_totals",this.updated_html.bind(this)),b(document.body).on("wc_cart_emptied",this.cart_emptied.bind(this))},wc_stripe.CartGateway.prototype.submit_error=function(a){this.submit_message(this.get_error_message(a))},wc_stripe.CartGateway.prototype.updated_html=function(){},wc_stripe.CartGateway.prototype.cart_emptied=function(){},wc_stripe.CartGateway.prototype.add_cart_totals_class=function(){b(".cart_totals").addClass("stripe_cart_gateway_active")},wc_stripe.GooglePay=function(){};var d={apiVersion:2,apiVersionMinor:0},e={type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY"],allowedCardNetworks:["AMEX","DISCOVER","INTERAC","JCB","MASTERCARD","VISA"]}};wc_stripe.GooglePay.prototype.update_addresses=function(a){this.populate_billing_fields(a.paymentMethodData.info.billingAddress),a.shippingAddress&&this.populate_shipping_fields(a.shippingAddress),a.email&&this.fields.set("email",a.email,"billing")},wc_stripe.GooglePay.prototype.map_address=function(a){return{city:a.locality,postcode:a.postalCode,state:a.administrativeArea,country:a.countryCode}},wc_stripe.GooglePay.prototype.update_payment_data=function(a){return new Promise(function(c,d){var e="default"==a.shippingOptionData.id?null:a.shippingOptionData.id;b.when(b.ajax({url:this.params.routes.payment_data,dataType:"json",method:"POST",data:{shipping_address:this.map_address(a.shippingAddress),shipping_method:e,page_id:this.get_page()},beforeSend:this.ajax_before_send.bind(this)})).done(function(a){a.code?d(a.data.data):c(a.data)}.bind(this)).fail(function(){d()}.bind(this))}.bind(this))},wc_stripe.GooglePay.prototype.on_payment_data_changed=function(a){return new Promise(function(b){this.update_payment_data(a).then(function(c){b(c.paymentRequestUpdate),this.set_selected_shipping_methods(c.shipping_methods),this.payment_data_updated(c,a)}.bind(this))["catch"](function(a){b(a)}.bind(this))}.bind(this))},wc_stripe.GooglePay.prototype.payment_data_updated=function(){},wc_stripe.GooglePay.prototype.get_merchant_info=function(){var a={merchantId:this.params.merchant_id,merchantName:this.params.merchant_name};return"TEST"===this.params.environment&&delete a.merchantId,a},wc_stripe.GooglePay.prototype.get_payment_options=function(){var a={environment:this.params.environment,merchantInfo:this.get_merchant_info(),paymentDataCallbacks:{onPaymentAuthorized:function(){return new Promise(function(a){a({transactionState:"SUCCESS"})}.bind(this))}}};if(this.needs_shipping()){var b=this.get_shipping_prefix();(!this.is_current_page("checkout")||this.is_valid_address(this.get_address_object(b),b,["email","phone"]))&&this.is_current_page("checkout")||(a.paymentDataCallbacks.onPaymentDataChanged=this.on_payment_data_changed.bind(this))}return a},wc_stripe.GooglePay.prototype.build_payment_request=function(){var a=b.extend({},d,{emailRequired:this.fields.requestFieldInWallet("billing_email"),merchantInfo:this.get_merchant_info(),allowedPaymentMethods:[b.extend({type:"CARD",tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:"stripe","stripe:version":"2018-10-31","stripe:publishableKey":this.params.api_key}}},e)],shippingAddressRequired:function(){if(this.needs_shipping()){var a=this.get_shipping_prefix();if(this.is_current_page("checkout")&&!this.is_valid_address(this.get_address_object(a),a,["email","phone"])||!this.is_current_page("checkout"))return!0}return!1}.bind(this)(),transactionInfo:{currencyCode:this.get_currency(),totalPriceStatus:"ESTIMATED",totalPrice:this.get_total_price().toString(),displayItems:this.get_display_items(),totalPriceLabel:this.params.total_price_label}});return a.allowedPaymentMethods[0].parameters.billingAddressRequired=!0,a.allowedPaymentMethods[0].parameters.billingAddressParameters={format:"FULL",phoneNumberRequired:this.fields.requestFieldInWallet("billing_phone")},a.shippingAddressRequired?(a.shippingAddressParameters={},a.shippingOptionRequired=!0,a.shippingOptionParameters={shippingOptions:this.get_shipping_options()},a.callbackIntents=["SHIPPING_ADDRESS","SHIPPING_OPTION","PAYMENT_AUTHORIZATION"]):a.callbackIntents=["PAYMENT_AUTHORIZATION"],this.payment_request_options=a,a},wc_stripe.GooglePay.prototype.createPaymentsClient=function(){this.paymentsClient=new google.payments.api.PaymentsClient(this.get_payment_options())},wc_stripe.GooglePay.prototype.isReadyToPay=function(){return new Promise(function(a){var c=b.extend({},d);c.allowedPaymentMethods=[e],this.paymentsClient.isReadyToPay(c).then(function(){this.can_pay=!0,this.create_button(),a()}.bind(this))["catch"](function(a){this.submit_error(a)}.bind(this))}.bind(this))},wc_stripe.GooglePay.prototype.create_button=function(){this.$button&&this.$button.remove(),this.$button=b(this.paymentsClient.createButton({onClick:this.start.bind(this),buttonColor:this.params.button_color,buttonType:this.params.button_style})),this.$button.addClass("gpay-button-container")},wc_stripe.GooglePay.prototype.start=function(){// always recreate the paymentClient to ensure latest data is used.
5
+ this.createPaymentsClient(),this.paymentsClient.loadPaymentData(this.build_payment_request()).then(function(a){var b=JSON.parse(a.paymentMethodData.tokenizationData.token);this.update_addresses(a),this.on_token_received(b)}.bind(this))["catch"](function(a){"CANCELED"===a.statusCode||(a.statusMessage&&-1<a.statusMessage.indexOf("paymentDataRequest.callbackIntent")?this.submit_error_code("DEVELOPER_ERROR_WHITELIST"):this.submit_error(a.message))}.bind(this))},wc_stripe.ApplePay=function(){},wc_stripe.ApplePay.prototype.initialize=function(){var a=".apple-pay-button";0>["checkout","order_pay"].indexOf(this.get_page())&&(a=this.container+" .apple-pay-button"),b(document.body).on("click",a,this.start.bind(this)),this.createPaymentRequest(),this.canMakePayment()},wc_stripe.ApplePay.prototype.create_button=function(){this.$button&&this.$button.remove(),this.$button=b(this.params.button),this.append_button()},wc_stripe.ApplePay.prototype.canMakePayment=function(){return new Promise(function(a){this.paymentRequest.canMakePayment().then(function(c){c&&c.applePay&&(this.can_pay=!0,this.create_button(),b(this.container).show(),a(c))}.bind(this))}.bind(this))},wc_stripe.ApplePay.prototype.start=function(a){a.preventDefault(),this.paymentRequest.update(this.get_payment_request_update({total:{pending:!1}})),this.paymentRequest.show()},wc_stripe.PaymentRequest=function(){},wc_stripe.PaymentRequest.prototype.initialize=function(){this.createPaymentRequest(),this.createPaymentRequestButton(),this.canMakePayment(),this.paymentRequestButton.on("click",this.button_click.bind(this))},wc_stripe.PaymentRequest.prototype.button_click=function(){},wc_stripe.PaymentRequest.prototype.createPaymentRequestButton=function(){this.paymentRequestButton&&this.paymentRequestButton.destroy(),this.paymentRequestButton=this.elements.create("paymentRequestButton",{paymentRequest:this.paymentRequest,style:{paymentRequestButton:{type:this.params.button.type,theme:this.params.button.theme,height:this.params.button.height}}})},wc_stripe.PaymentRequest.prototype.canMakePayment=function(){return new Promise(function(a){this.paymentRequest.canMakePayment().then(function(c){c&&!c.applePay&&(this.can_pay=!0,this.create_button(),b(this.container).show(),a(c))}.bind(this))}.bind(this))},wc_stripe.PaymentRequest.prototype.create_button=function(){this.paymentRequestButton.mount("#wc-stripe-payment-request-container")},wc_stripe.CheckoutFields=function(a,c){this.params=a,this.page=c,this.fields=new Map(Object.keys(this.params).map(function(a){return null===this.params[a].value&&(this.params[a].value=""),[a,this.params[a].value]}.bind(this))),"checkout"===c&&(b("form.checkout").on("change",".input-text, select",this.onChange.bind(this)),b("form.checkout").on("change","[name=\"ship_to_different_address\"]",this.on_ship_to_address_change.bind(this)),this.init_i18n())},wc_stripe.CheckoutFields.prototype.init_i18n=function(){this.locales="undefined"==typeof wc_address_i18n_params?null:b.parseJSON(wc_address_i18n_params.locale.replace(/&quot;/g,"\""))},wc_stripe.CheckoutFields.prototype.onChange=function(a){try{var b=a.currentTarget.name,c=a.currentTarget.value;this.fields.set(b,c),("billing_country"===b||"shipping_country"===b)&&this.update_required_fields(c,b)}catch(a){console.log(a)}},wc_stripe.CheckoutFields.prototype.update_required_fields=function(a,c){if(this.locales){var d=-1<c.indexOf("billing_")?"billing_":"shipping_",e="undefined"==typeof this.locales[a]?this.locales["default"]:this.locales[a],f=b.extend(!0,{},this.locales["default"],e);for(var g in f){var h=d+g;this.params[h]&&(this.params[h]=b.extend(!0,{},this.params[h],f[g]))}}},wc_stripe.CheckoutFields.prototype.on_ship_to_address_change=function(a){b(a.currentTarget).is(":checked")&&this.update_required_fields(b("shipping_country"),"shipping_country")},wc_stripe.CheckoutFields.prototype.requestFieldInWallet=function(a){if("checkout"===this.page)return this.required(a)&&this.isEmpty(a);return"order_pay"!==this.page&&this.required(a)},wc_stripe.CheckoutFields.prototype.set=function(a,b,c){this[a]&&"function"==typeof this[a]?this[a]().set.call(this,b,c):this.fields.set(a,b)},wc_stripe.CheckoutFields.prototype.get=function(a,b){if(this[a]&&"function"==typeof this[a])var c=this[a]().get.call(this,b);else{var c=this.fields.get(a);("undefined"==typeof c||null===c||""===c)&&"undefined"!=typeof b&&(c=b)}return"undefined"==typeof c?"":c},wc_stripe.CheckoutFields.prototype.required=function(a){return!!(this.params[a]&&"undefined"!=typeof this.params[a].required)&&this.params[a].required},wc_stripe.CheckoutFields.prototype.isEmpty=function(a){if(this.fields.has(a)){var b=this.fields.get(a);return"undefined"==typeof b||null===b||"string"==typeof b&&0===b.trim().length}return!0},wc_stripe.CheckoutFields.prototype.isValid=function(a){if(this[a]&&"function"==typeof this[a])return this[a]().isValid.apply(this,Array.prototype.slice.call(arguments,1))},wc_stripe.CheckoutFields.prototype.first_name=function(){return{set:function set(a,b){this.fields.set(b+"_first_name",a)},get:function get(a){return this.fields.get(a+"_first_name")},isValid:function isValid(a){return"string"==typeof a&&0<a.length}}},wc_stripe.CheckoutFields.prototype.last_name=function(){return{set:function set(a,b){this.fields.set(b+"_last_name",a)},get:function get(a){return this.fields.get(a+"_last_name")},isValid:function isValid(a){return"string"==typeof a&&0<a.length}}},wc_stripe.CheckoutFields.prototype.address_1=function(){return{set:function(a,b){this.fields.set(b+"_address_1",a)},get:function(a){return this.fields.get(a+"_address_1")},isValid:function isValid(a){return"string"==typeof a&&0<a.length}}},wc_stripe.CheckoutFields.prototype.address_2=function(){return{set:function(a,b){this.fields.set(b+"_address_2",a)},get:function(a){return this.fields.get(a+"_address_2")},isValid:function isValid(a){return"string"==typeof a&&0<a.length}}},wc_stripe.CheckoutFields.prototype.name=function(){return{set:function(a,b){var c=a.split(" ");0<c.length&&this.fields.set(b+"_first_name",c[0]),1<c.length&&this.fields.set(b+"_last_name",c[1])},get:function(a){return this.fields.get(a+"_first_name")+" "+this.fields.get(a+"_last_name")}}},wc_stripe.CheckoutFields.prototype.email=function(){return{set:function(a,b){this.fields.set(b+"_email",a)},get:function(a){return this.fields.get(a+"_email")},isValid:function isValid(a){return"string"==typeof a&&0<a.length}}},wc_stripe.CheckoutFields.prototype.phone=function(){return{set:function(a,b){this.fields.set(b+"_phone",a)},get:function(a){return this.fields.get(a+"_phone")},isValid:function isValid(a){return"string"==typeof a&&0<a.length}}},wc_stripe.CheckoutFields.prototype.country=function(){return{set:function(a,b){this.fields.set(b+"_country",a)},get:function(a){return this.fields.get(a+"_country")},isValid:function isValid(a){return"string"==typeof a&&2===a.length}}},wc_stripe.CheckoutFields.prototype.state=function(){return{set:function(a,c){a=a.toUpperCase(),2<a.length&&"checkout"===this.page&&b("#"+c+"_state option").each(function(){var c=b(this),d=c.text().toUpperCase();a===d&&(a=c.val())}),this.fields.set(c+"_state",a)},get:function(a){return this.fields.get(a+"_state")},isValid:function isValid(a){return"string"==typeof a&&0<a.length}}},wc_stripe.CheckoutFields.prototype.city=function(){return{set:function(a,b){this.fields.set(b+"_city",a)},get:function(a){return this.fields.get(a+"_city")},isValid:function isValid(a){return"string"==typeof a&&0<a.length}}},wc_stripe.CheckoutFields.prototype.postcode=function(){return{set:function(a,b){this.fields.set(b+"_postcode",a)},get:function(a){return this.fields.get(a+"_postcode")},isValid:function isValid(a){return"string"==typeof a&&0<a.length}}},wc_stripe.CheckoutFields.prototype.recipient=function(){return wc_stripe.CheckoutFields.prototype.name.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.payerName=function(){return wc_stripe.CheckoutFields.prototype.name.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.payerEmail=function(){return wc_stripe.CheckoutFields.prototype.email.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.payerPhone=function(){return wc_stripe.CheckoutFields.prototype.phone.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.phoneNumber=function(){return wc_stripe.CheckoutFields.prototype.phone.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.countryCode=function(){return wc_stripe.CheckoutFields.prototype.country.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.address1=function(){return wc_stripe.CheckoutFields.prototype.address_1.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.address2=function(){return wc_stripe.CheckoutFields.prototype.address_2.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.line1=function(){return wc_stripe.CheckoutFields.prototype.address_1.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.line2=function(){return wc_stripe.CheckoutFields.prototype.address_2.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.addressLine=function(){return{set:function(a,b){0<a.length&&this.fields.set(b+"_address_1",a[0]),1<a.length&&this.fields.set(b+"_address_2",a[1])},get:function(a){return[this.fields.get(a+"_address_1"),this.fields.get(a+"_address_2")]},isValid:function isValid(a){return!!(0<a.length)&&"string"==typeof a[0]&&0<a[0].length}}},wc_stripe.CheckoutFields.prototype.region=function(){return wc_stripe.CheckoutFields.prototype.state.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.administrativeArea=function(){return wc_stripe.CheckoutFields.prototype.state.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.locality=function(){return wc_stripe.CheckoutFields.prototype.city.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.postal_code=function(){return wc_stripe.CheckoutFields.prototype.postcode.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.postalCode=function(){return wc_stripe.CheckoutFields.prototype.postcode.apply(this,arguments)},wc_stripe.CheckoutFields.prototype.toJson=function(){var a={};return this.fields.forEach(function(b,c){a[c]=b}),a},wc_stripe.CheckoutFields.prototype.toFormFields=function(a){var c=[];this.fields.forEach(function(a,d){var e="[name=\""+d+"\"]";b(e).length&&""!==a&&(b(e).val()!==a&&b(e).is("select")&&c.push(e),b(e).val(a))}),0<c.length&&b(c.join(",")).trigger("change"),"undefined"!=typeof a&&b(document.body).trigger("update_checkout",a)},wc_stripe.CheckoutFields.prototype.validateFields=function(a){for(var c in this.params){var d=this.params[c];if(-1<c.indexOf(a)&&d.required&&b("#"+c).length){var e=b("#"+c).val();if("undefined"==typeof e||null===e||0===e.length)return!1}}return!0};try{c=Stripe(wc_stripe_params_v3.api_key,{stripeAccount:wc_stripe_params_v3.account})}catch(b){return a.alert(b),void console.log(b)}var f=new wc_stripe.CheckoutFields(wc_stripe_checkout_fields,wc_stripe_params_v3.page)})(window,jQuery);
i18n/languages/woo-stripe-payment.pot CHANGED
@@ -2,14 +2,14 @@
2
  # This file is distributed under the same license as the Stripe For WooCommerce plugin.
3
  msgid ""
4
  msgstr ""
5
- "Project-Id-Version: Stripe For WooCommerce 3.2.2\n"
6
  "Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/woo-stripe-payment\n"
7
  "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
8
  "Language-Team: LANGUAGE <LL@li.org>\n"
9
  "MIME-Version: 1.0\n"
10
  "Content-Type: text/plain; charset=UTF-8\n"
11
  "Content-Transfer-Encoding: 8bit\n"
12
- "POT-Creation-Date: 2020-09-17T20:01:51+00:00\n"
13
  "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
14
  "X-Generator: WP-CLI 2.4.0\n"
15
  "X-Domain: woo-stripe-payment\n"
@@ -98,7 +98,11 @@ msgstr ""
98
  msgid " & billing country is <strong>%s</strong>"
99
  msgstr ""
100
 
101
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:417
 
 
 
 
102
  #: includes/controllers/class-wc-stripe-controller-cart.php:136
103
  #: includes/controllers/class-wc-stripe-controller-cart.php:196
104
  #: includes/controllers/class-wc-stripe-controller-googlepay.php:137
@@ -106,137 +110,137 @@ msgstr ""
106
  msgid "Total"
107
  msgstr ""
108
 
109
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:477
110
  msgid "User must be logged in."
111
  msgstr ""
112
 
113
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:489
114
  msgid "Error saving your payment method. Reason: %s"
115
  msgstr ""
116
 
117
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:504
118
  msgid "Error saving payment method. Reason: %s"
119
  msgstr ""
120
 
121
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:523
122
  msgid "Order refunded in Stripe. Amount: %s"
123
  msgstr ""
124
 
125
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:561
126
  msgid "Order amount captured in Stripe. Amount: %s"
127
  msgstr ""
128
 
129
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:571
130
  msgid "Error capturing charge in Stripe. Reason: %s"
131
  msgstr ""
132
 
133
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:592
134
  msgid "Error voiding charge. Reason: %s"
135
  msgstr ""
136
 
137
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:594
138
  msgid "Charge voided in Stripe."
139
  msgstr ""
140
 
141
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:764
142
  msgid "n/a"
143
  msgstr ""
144
 
145
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:792
146
  #: includes/admin/meta-boxes/views/html-order-pay.php:42
147
  msgid "New Card"
148
  msgstr ""
149
 
150
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:796
151
  #: includes/admin/meta-boxes/views/html-order-pay.php:30
152
  msgid "Saved Cards"
153
  msgstr ""
154
 
155
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:999
156
  msgid "Attemp to save payment method failed. Reason: %s"
157
  msgstr ""
158
 
159
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1021
160
  msgid "We were not able to save your payment method. To prevent billing issues with your subscription, please add a payment method to the subscription."
161
  msgstr ""
162
 
163
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1023
164
  msgid "We were not able to save your payment method. Reason: %s"
165
  msgstr ""
166
 
167
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1057
168
  msgid "Payment Method Token"
169
  msgstr ""
170
 
171
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1077
172
  msgid "Recurring payment for order failed. Reason: %s"
173
  msgstr ""
174
 
175
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1090
176
  msgid "Recurring payment captured in Stripe. Payment method: %s"
177
  msgstr ""
178
 
179
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1092
180
  msgid "Recurring payment authorized in Stripe. Payment method: %s"
181
  msgstr ""
182
 
183
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1095
184
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1354
185
  msgid "Customer must manually complete payment for payment method %s"
186
  msgstr ""
187
 
188
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1111
189
  msgid "Error saving payment method for subscription. Reason: %s"
190
  msgstr ""
191
 
192
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1172
193
  #: includes/abstract/abstract-wc-stripe-payment.php:219
194
  msgid "Order %1$s from %2$s"
195
  msgstr ""
196
 
197
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1341
198
  msgid "Pre-order payment for order failed. Reason: %s"
199
  msgstr ""
200
 
201
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1349
202
  msgid "Pre-order payment captured in Stripe. Payment method: %s"
203
  msgstr ""
204
 
205
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1351
206
  msgid "Pre-order payment authorized in Stripe. Payment method: %s"
207
  msgstr ""
208
 
209
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1423
210
  msgid "Cannot process payment"
211
  msgstr ""
212
 
213
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1431
214
  msgid "Increase your conversion rate by offering %1$s on your Product and Cart pages, or at the top of the checkout page. <br/><strong>Note:</strong> you can control which products display %s by going to the product edit page."
215
  msgstr ""
216
 
217
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1542
218
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1573
219
  #: includes/gateways/class-wc-payment-gateway-stripe-klarna.php:189
220
  #: includes/wc-stripe-functions.php:405
221
  #: includes/wc-stripe-functions.php:470
222
  msgid "Shipping"
223
  msgstr ""
224
 
225
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1550
226
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1576
227
  #: includes/gateways/class-wc-payment-gateway-stripe-klarna.php:199
228
  #: includes/wc-stripe-functions.php:422
229
  #: includes/wc-stripe-functions.php:478
230
  msgid "Discount"
231
  msgstr ""
232
 
233
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1553
234
  #: includes/gateways/class-wc-payment-gateway-stripe-klarna.php:221
235
  #: includes/wc-stripe-functions.php:430
236
  msgid "Tax"
237
  msgstr ""
238
 
239
- #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1583
240
  #: includes/wc-stripe-functions.php:489
241
  msgid "Fees"
242
  msgstr ""
@@ -267,6 +271,7 @@ msgid "Error processing payment. Reason: %s"
267
  msgstr ""
268
 
269
  #: includes/abstract/abstract-wc-stripe-rest-controller.php:58
 
270
  msgid "You do not have permissions to access this resource."
271
  msgstr ""
272
 
@@ -289,10 +294,10 @@ msgstr ""
289
  msgid "Documentation"
290
  msgstr ""
291
 
292
- #: includes/admin/class-wc-stripe-admin-notices.php:51
293
  msgid ""
294
- "At Stripe's request we have updated how the Stripe for WooCommerce\n"
295
- " plugin integrates with Stripe. This new integration offers even more security and \n"
296
  " Stripe is requesting that all merchants switch. %1$sUpdate Integration%2$s"
297
  msgstr ""
298
 
@@ -352,7 +357,7 @@ msgstr ""
352
 
353
  #: includes/admin/meta-boxes/views/html-charge-data-subview.php:25
354
  #: includes/admin/settings/class-wc-stripe-api-settings.php:38
355
- #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:184
356
  msgid "Live"
357
  msgstr ""
358
 
@@ -510,7 +515,7 @@ msgid "API Settings"
510
  msgstr ""
511
 
512
  #: includes/admin/settings/class-wc-stripe-api-settings.php:37
513
- #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:184
514
  msgid "Test"
515
  msgstr ""
516
 
@@ -697,44 +702,44 @@ msgstr ""
697
  msgid "Quantity must be greater than zero."
698
  msgstr ""
699
 
700
- #: includes/controllers/class-wc-stripe-controller-checkout.php:229
701
  msgid "Some required fields were missing. Please click %1$shere%2$s to complete your payment."
702
  msgstr ""
703
 
704
- #: includes/controllers/class-wc-stripe-controller-checkout.php:278
705
  msgid "Please review your order details then click Place Order."
706
  msgstr ""
707
 
708
- #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:82
709
  msgid "You cannot register your domain until you have configured your Live API keys."
710
  msgstr ""
711
 
712
- #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:111
713
  msgid "Domain registered successfully. You can confirm in your Stripe Dashboard at https://dashboard.stripe.com/account/apple_pay."
714
  msgstr ""
715
 
716
- #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:135
717
  msgid "You must configure your secret key before creating webhooks."
718
  msgstr ""
719
 
720
- #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:148
721
  msgid "There is already a webhook configured for this site. If you want to delete the webhook, login to your Stripe Dashboard."
722
  msgstr ""
723
 
724
- #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:182
725
  msgid "Webhook created in Stripe for %s environment. You can test your webhook by logging in to the Stripe dashboard"
726
  msgstr ""
727
 
728
- #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:205
729
  msgid "Mode: %s. Invalid secret key. Please check your entry."
730
  msgstr ""
731
 
732
- #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:217
733
- #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:220
734
  msgid "Mode: %s. Invalid publishable key. Please check your entry."
735
  msgstr ""
736
 
737
- #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:226
738
  msgid "Connection test to Stripe was successful. Mode: %s."
739
  msgstr ""
740
 
2
  # This file is distributed under the same license as the Stripe For WooCommerce plugin.
3
  msgid ""
4
  msgstr ""
5
+ "Project-Id-Version: Stripe For WooCommerce 3.2.3\n"
6
  "Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/woo-stripe-payment\n"
7
  "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
8
  "Language-Team: LANGUAGE <LL@li.org>\n"
9
  "MIME-Version: 1.0\n"
10
  "Content-Type: text/plain; charset=UTF-8\n"
11
  "Content-Transfer-Encoding: 8bit\n"
12
+ "POT-Creation-Date: 2020-10-06T19:14:35+00:00\n"
13
  "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
14
  "X-Generator: WP-CLI 2.4.0\n"
15
  "X-Domain: woo-stripe-payment\n"
98
  msgid " & billing country is <strong>%s</strong>"
99
  msgstr ""
100
 
101
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:406
102
+ msgid "Please fill out all required fields."
103
+ msgstr ""
104
+
105
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:421
106
  #: includes/controllers/class-wc-stripe-controller-cart.php:136
107
  #: includes/controllers/class-wc-stripe-controller-cart.php:196
108
  #: includes/controllers/class-wc-stripe-controller-googlepay.php:137
110
  msgid "Total"
111
  msgstr ""
112
 
113
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:481
114
  msgid "User must be logged in."
115
  msgstr ""
116
 
117
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:493
118
  msgid "Error saving your payment method. Reason: %s"
119
  msgstr ""
120
 
121
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:508
122
  msgid "Error saving payment method. Reason: %s"
123
  msgstr ""
124
 
125
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:527
126
  msgid "Order refunded in Stripe. Amount: %s"
127
  msgstr ""
128
 
129
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:565
130
  msgid "Order amount captured in Stripe. Amount: %s"
131
  msgstr ""
132
 
133
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:575
134
  msgid "Error capturing charge in Stripe. Reason: %s"
135
  msgstr ""
136
 
137
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:596
138
  msgid "Error voiding charge. Reason: %s"
139
  msgstr ""
140
 
141
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:598
142
  msgid "Charge voided in Stripe."
143
  msgstr ""
144
 
145
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:768
146
  msgid "n/a"
147
  msgstr ""
148
 
149
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:796
150
  #: includes/admin/meta-boxes/views/html-order-pay.php:42
151
  msgid "New Card"
152
  msgstr ""
153
 
154
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:800
155
  #: includes/admin/meta-boxes/views/html-order-pay.php:30
156
  msgid "Saved Cards"
157
  msgstr ""
158
 
159
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1007
160
  msgid "Attemp to save payment method failed. Reason: %s"
161
  msgstr ""
162
 
163
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1029
164
  msgid "We were not able to save your payment method. To prevent billing issues with your subscription, please add a payment method to the subscription."
165
  msgstr ""
166
 
167
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1031
168
  msgid "We were not able to save your payment method. Reason: %s"
169
  msgstr ""
170
 
171
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1065
172
  msgid "Payment Method Token"
173
  msgstr ""
174
 
175
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1085
176
  msgid "Recurring payment for order failed. Reason: %s"
177
  msgstr ""
178
 
179
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1098
180
  msgid "Recurring payment captured in Stripe. Payment method: %s"
181
  msgstr ""
182
 
183
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1100
184
  msgid "Recurring payment authorized in Stripe. Payment method: %s"
185
  msgstr ""
186
 
187
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1103
188
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1362
189
  msgid "Customer must manually complete payment for payment method %s"
190
  msgstr ""
191
 
192
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1119
193
  msgid "Error saving payment method for subscription. Reason: %s"
194
  msgstr ""
195
 
196
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1180
197
  #: includes/abstract/abstract-wc-stripe-payment.php:219
198
  msgid "Order %1$s from %2$s"
199
  msgstr ""
200
 
201
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1349
202
  msgid "Pre-order payment for order failed. Reason: %s"
203
  msgstr ""
204
 
205
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1357
206
  msgid "Pre-order payment captured in Stripe. Payment method: %s"
207
  msgstr ""
208
 
209
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1359
210
  msgid "Pre-order payment authorized in Stripe. Payment method: %s"
211
  msgstr ""
212
 
213
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1431
214
  msgid "Cannot process payment"
215
  msgstr ""
216
 
217
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1439
218
  msgid "Increase your conversion rate by offering %1$s on your Product and Cart pages, or at the top of the checkout page. <br/><strong>Note:</strong> you can control which products display %s by going to the product edit page."
219
  msgstr ""
220
 
221
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1550
222
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1581
223
  #: includes/gateways/class-wc-payment-gateway-stripe-klarna.php:189
224
  #: includes/wc-stripe-functions.php:405
225
  #: includes/wc-stripe-functions.php:470
226
  msgid "Shipping"
227
  msgstr ""
228
 
229
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1558
230
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1584
231
  #: includes/gateways/class-wc-payment-gateway-stripe-klarna.php:199
232
  #: includes/wc-stripe-functions.php:422
233
  #: includes/wc-stripe-functions.php:478
234
  msgid "Discount"
235
  msgstr ""
236
 
237
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1561
238
  #: includes/gateways/class-wc-payment-gateway-stripe-klarna.php:221
239
  #: includes/wc-stripe-functions.php:430
240
  msgid "Tax"
241
  msgstr ""
242
 
243
+ #: includes/abstract/abstract-wc-payment-gateway-stripe.php:1591
244
  #: includes/wc-stripe-functions.php:489
245
  msgid "Fees"
246
  msgstr ""
271
  msgstr ""
272
 
273
  #: includes/abstract/abstract-wc-stripe-rest-controller.php:58
274
+ #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:26
275
  msgid "You do not have permissions to access this resource."
276
  msgstr ""
277
 
294
  msgid "Documentation"
295
  msgstr ""
296
 
297
+ #: includes/admin/class-wc-stripe-admin-notices.php:52
298
  msgid ""
299
+ "At Stripe's request we have updated how the Stripe for WooCommerce\r\n"
300
+ " plugin integrates with Stripe. This new integration offers even more security and \r\n"
301
  " Stripe is requesting that all merchants switch. %1$sUpdate Integration%2$s"
302
  msgstr ""
303
 
357
 
358
  #: includes/admin/meta-boxes/views/html-charge-data-subview.php:25
359
  #: includes/admin/settings/class-wc-stripe-api-settings.php:38
360
+ #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:190
361
  msgid "Live"
362
  msgstr ""
363
 
515
  msgstr ""
516
 
517
  #: includes/admin/settings/class-wc-stripe-api-settings.php:37
518
+ #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:190
519
  msgid "Test"
520
  msgstr ""
521
 
702
  msgid "Quantity must be greater than zero."
703
  msgstr ""
704
 
705
+ #: includes/controllers/class-wc-stripe-controller-checkout.php:273
706
  msgid "Some required fields were missing. Please click %1$shere%2$s to complete your payment."
707
  msgstr ""
708
 
709
+ #: includes/controllers/class-wc-stripe-controller-checkout.php:322
710
  msgid "Please review your order details then click Place Order."
711
  msgstr ""
712
 
713
+ #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:88
714
  msgid "You cannot register your domain until you have configured your Live API keys."
715
  msgstr ""
716
 
717
+ #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:117
718
  msgid "Domain registered successfully. You can confirm in your Stripe Dashboard at https://dashboard.stripe.com/account/apple_pay."
719
  msgstr ""
720
 
721
+ #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:141
722
  msgid "You must configure your secret key before creating webhooks."
723
  msgstr ""
724
 
725
+ #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:154
726
  msgid "There is already a webhook configured for this site. If you want to delete the webhook, login to your Stripe Dashboard."
727
  msgstr ""
728
 
729
+ #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:188
730
  msgid "Webhook created in Stripe for %s environment. You can test your webhook by logging in to the Stripe dashboard"
731
  msgstr ""
732
 
733
+ #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:211
734
  msgid "Mode: %s. Invalid secret key. Please check your entry."
735
  msgstr ""
736
 
737
+ #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:223
738
+ #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:226
739
  msgid "Mode: %s. Invalid publishable key. Please check your entry."
740
  msgstr ""
741
 
742
+ #: includes/controllers/class-wc-stripe-controller-gateway-settings.php:232
743
  msgid "Connection test to Stripe was successful. Mode: %s."
744
  msgstr ""
745
 
includes/abstract/abstract-wc-payment-gateway-stripe.php CHANGED
@@ -1,1713 +1,1730 @@
1
- <?php
2
- defined( 'ABSPATH' ) || exit();
3
-
4
- if ( ! class_exists( 'WC_Payment_Gateway' ) ) {
5
- return;
6
- }
7
-
8
- require_once( WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-payment-intent.php' );
9
- require_once( WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-payment-charge.php' );
10
- require_once( WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-payment-charge-local.php' );
11
-
12
- require_once( WC_STRIPE_PLUGIN_FILE_PATH . 'includes/traits/wc-stripe-payment-traits.php' );
13
-
14
- /**
15
- *
16
- * @since 3.0.0
17
- * @author PaymentPlugins
18
- * @package Stripe/Abstract
19
- *
20
- */
21
- abstract class WC_Payment_Gateway_Stripe extends WC_Payment_Gateway {
22
-
23
- use WC_Stripe_Settings_Trait;
24
-
25
- /**
26
- *
27
- * @var WC_Stripe_Payment
28
- */
29
- public $payment_object;
30
-
31
- /**
32
- * @var bool
33
- * @since 3.1.8
34
- */
35
- protected $has_digital_wallet = false;
36
-
37
- /**
38
- *
39
- * @var string
40
- */
41
- public $token_key;
42
-
43
- /**
44
- *
45
- * @var string
46
- */
47
- public $saved_method_key;
48
-
49
- /**
50
- *
51
- * @var string
52
- */
53
- public $payment_type_key;
54
-
55
- /**
56
- *
57
- * @var string
58
- */
59
- public $payment_intent_key;
60
-
61
- /**
62
- *
63
- * @var string
64
- */
65
- public $save_source_key;
66
-
67
- /**
68
- *
69
- * @var string
70
- */
71
- public $template_name;
72
-
73
- /**
74
- *
75
- * @var bool
76
- */
77
- protected $checkout_error = false;
78
-
79
- /**
80
- * Used to create an instance of a WC_Payment_Token
81
- *
82
- * @var string
83
- */
84
- protected $token_type;
85
-
86
- /**
87
- *
88
- * @var WC_Stripe_Gateway
89
- */
90
- protected $gateway;
91
-
92
- /**
93
- *
94
- * @var WP_Error
95
- */
96
- protected $wp_error;
97
-
98
- /**
99
- *
100
- * @var string
101
- */
102
- protected $payment_method_token = null;
103
-
104
- /**
105
- *
106
- * @var string
107
- */
108
- protected $new_source_token = null;
109
-
110
- /**
111
- * Is the payment method synchronous or asynchronous
112
- *
113
- * @var bool
114
- */
115
- public $synchronous = true;
116
-
117
- /**
118
- *
119
- * @var array
120
- */
121
- protected $post_payment_processes = array();
122
-
123
- /**
124
- *
125
- * @var bool
126
- */
127
- public $processing_payment = false;
128
-
129
- public function __construct() {
130
- $this->token_key = $this->id . '_token_key';
131
- $this->saved_method_key = $this->id . '_saved_method_key';
132
- $this->save_source_key = $this->id . '_save_source_key';
133
- $this->payment_type_key = $this->id . '_payment_type_key';
134
- $this->payment_intent_key = $this->id . '_payment_intent_key';
135
- $this->has_fields = true;
136
- $this->init_form_fields();
137
- $this->init_settings();
138
- $this->title = $this->get_option( 'title_text' );
139
- $this->description = $this->get_option( 'description' );
140
- $this->hooks();
141
- $this->init_supports();
142
- $this->gateway = WC_Stripe_Gateway::load();
143
-
144
- $this->payment_object = $this->get_payment_object();
145
- }
146
-
147
- public function hooks() {
148
- add_filter( 'wc_stripe_settings_nav_tabs', array( $this, 'admin_nav_tab' ) );
149
- add_action( 'woocommerce_settings_checkout_' . $this->id, array( $this, 'enqueue_admin_scripts' ) );
150
- add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
151
- add_filter( 'woocommerce_payment_methods_list_item', array( $this, 'payment_methods_list_item' ), 10, 2 );
152
- add_action( 'wc_stripe_payment_token_deleted_' . $this->id, array( $this, 'delete_payment_method' ), 10, 2 );
153
- add_filter( 'woocommerce_subscription_payment_meta', array( $this, 'subscription_payment_meta' ), 10, 2 );
154
- add_action( 'woocommerce_scheduled_subscription_payment_' . $this->id, array( $this, 'scheduled_subscription_payment' ), 10, 2 );
155
- if ( ! is_admin() ) {
156
- add_action( 'woocommerce_subscriptions_pre_update_payment_method', array( $this, 'subscriptions_pre_update_payment_method' ), 10, 3 );
157
- add_action( 'woocommerce_subscription_payment_method_updated_to_' . $this->id, array( $this, 'subscription_payment_method_updated' ) );
158
- }
159
- add_action( 'wc_pre_orders_process_pre_order_completion_payment_' . $this->id, array( $this, 'process_pre_order_payment' ) );
160
-
161
- /**
162
- * @since 3.1.8
163
- */
164
- add_filter( 'wc_stripe_mini_cart_dependencies', array( $this, 'get_mini_cart_dependencies' ), 10, 2 );
165
- }
166
-
167
- public function init_supports() {
168
- $this->supports = array(
169
- 'tokenization',
170
- 'products',
171
- 'subscriptions',
172
- 'add_payment_method',
173
- 'subscription_cancellation',
174
- 'multiple_subscriptions',
175
- 'subscription_amount_changes',
176
- 'subscription_date_changes',
177
- 'default_credit_card_form',
178
- 'refunds',
179
- 'pre-orders',
180
- 'subscription_payment_method_change_admin',
181
- 'subscription_reactivation',
182
- 'subscription_suspension',
183
- 'subscription_payment_method_change_customer',
184
- );
185
- }
186
-
187
- public function init_form_fields() {
188
- $this->form_fields = include wc_stripe()->plugin_path() . 'includes/gateways/settings/' . str_replace( array( 'stripe_', '_' ), array(
189
- '',
190
- '-'
191
- ), $this->id ) . '-settings.php';
192
- $this->form_fields = apply_filters( 'wc_stripe_form_fields_' . $this->id, $this->form_fields );
193
- }
194
-
195
- public function get_method_formats() {
196
- $class_name = 'WC_Payment_Token_' . $this->token_type;
197
- if ( class_exists( $class_name ) ) {
198
- /**
199
- *
200
- * @var WC_Payment_Token_Stripe
201
- */
202
- $token = new $class_name();
203
-
204
- return $token->get_formats();
205
- }
206
-
207
- return array();
208
- }
209
-
210
- public function enqueue_admin_scripts() {
211
- }
212
-
213
- public function payment_fields() {
214
- $this->enqueue_frontend_scripts();
215
- wc_stripe_token_field( $this );
216
- wc_stripe_payment_intent_field( $this );
217
- $this->output_display_items( 'checkout' );
218
- wc_stripe_get_template(
219
- 'checkout/stripe-payment-method.php',
220
- array(
221
- 'gateway' => $this,
222
- 'tokens' => is_add_payment_method_page() ? null : $this->get_tokens(),
223
- )
224
- );
225
- }
226
-
227
- /**
228
- * Output the product payment fields.
229
- */
230
- public function product_fields() {
231
- global $product;
232
- $this->enqueue_frontend_scripts( 'product' );
233
- $this->output_display_items( 'product' );
234
- wc_stripe_get_template(
235
- 'product/' . $this->template_name,
236
- array(
237
- 'gateway' => $this,
238
- 'product' => $product,
239
- )
240
- );
241
- }
242
-
243
- public function cart_fields() {
244
- $this->enqueue_frontend_scripts( 'cart' );
245
- $this->output_display_items( 'cart' );
246
- wc_stripe_get_template( 'cart/' . $this->template_name, array( 'gateway' => $this ) );
247
- }
248
-
249
- public function mini_cart_fields() {
250
- $this->output_display_items( 'cart' );
251
- wc_stripe_get_template( 'mini-cart/' . $this->template_name, array( 'gateway' => $this ) );
252
- }
253
-
254
- /**
255
- * Enqueue scripts needed by the gateway on the frontend of the WC shop.
256
- *
257
- * @param WC_Stripe_Frontend_Scripts $scripts
258
- */
259
- public function enqueue_frontend_scripts( $page = '' ) {
260
- global $wp;
261
- if ( $page ) {
262
- if ( 'product' === $page ) {
263
- $this->enqueue_product_scripts( wc_stripe()->scripts() );
264
- } elseif ( 'cart' === $page ) {
265
- $this->enqueue_cart_scripts( wc_stripe()->scripts() );
266
- } elseif ( 'checkout' === $page ) {
267
- $this->enqueue_checkout_scripts( wc_stripe()->scripts() );
268
- } elseif ( 'mini_cart' === $page ) {
269
- $this->enqueue_mini_cart_scripts( wc_stripe()->scripts() );
270
- } else {
271
- $this->enqueue_frontend_scripts();
272
- }
273
- } else {
274
- if ( is_add_payment_method_page() ) {
275
- $this->enqueue_add_payment_method_scripts( wc_stripe()->scripts() );
276
- }
277
- if ( is_checkout() ) {
278
- $this->enqueue_checkout_scripts( wc_stripe()->scripts() );
279
- }
280
- if ( is_cart() ) {
281
- $this->enqueue_cart_scripts( wc_stripe()->scripts() );
282
- }
283
- if ( is_product() ) {
284
- $this->enqueue_product_scripts( wc_stripe()->scripts() );
285
- }
286
- }
287
- if ( ! empty( wc_stripe()->scripts()->enqueued_scripts ) ) {
288
- wp_enqueue_style( wc_stripe()->scripts()->prefix . 'styles', wc_stripe()->assets_url( 'css/stripe.css' ), array(), wc_stripe()->version() );
289
- }
290
- }
291
-
292
- /**
293
- * Enqueue scripts needed by the gateway on the checkout page.
294
- *
295
- * @param WC_Stripe_Frontend_Scripts $scripts
296
- */
297
- public function enqueue_checkout_scripts( $scripts ) {
298
- }
299
-
300
- /**
301
- * Enqueue scripts needed by the gateway on the add payment method page.
302
- *
303
- * @param WC_Stripe_Frontend_Scripts $scripts
304
- */
305
- public function enqueue_add_payment_method_scripts( $scripts ) {
306
- $this->enqueue_checkout_scripts( $scripts );
307
- }
308
-
309
- /**
310
- * Enqueue scripts needed by the gateway on the cart page.
311
- *
312
- * @param WC_Stripe_Frontend_Scripts $scripts
313
- */
314
- public function enqueue_cart_scripts( $scripts ) {
315
- }
316
-
317
- /**
318
- * Enqueue scripts needed by the gateway on the product page.
319
- *
320
- * @param WC_Stripe_Frontend_Scripts $scripts
321
- */
322
- public function enqueue_product_scripts( $scripts ) {
323
- }
324
-
325
- /**
326
- * @param WC_Stripe_Frontend_Scripts $scripts
327
- *
328
- * @since 3.1.8
329
- */
330
- public function enqueue_mini_cart_scripts( $scripts ) {
331
- if ( ! wp_script_is( $scripts->get_handle( 'mini-cart' ) ) ) {
332
- $scripts->enqueue_script( 'mini-cart', $scripts->assets_url( 'js/frontend/mini-cart.js' ), apply_filters( 'wc_stripe_mini_cart_dependencies', array( $scripts->get_handle( 'wc-stripe' ) ), $scripts ) );
333
- }
334
- $scripts->localize_script( 'mini-cart', $this->get_localized_params(), 'wc_' . $this->id . '_mini_cart_params' );
335
- }
336
-
337
- /**
338
- *
339
- * {@inheritDoc}
340
- *
341
- * @see WC_Payment_Gateway::process_payment()
342
- */
343
- public function process_payment( $order_id ) {
344
- $order = wc_get_order( $order_id );
345
-
346
- if ( $this->is_change_payment_method_request() ) {
347
- return array(
348
- 'result' => 'success',
349
- 'redirect' => $order->get_view_order_url(),
350
- );
351
- }
352
-
353
- do_action( 'wc_stripe_before_process_payment', $order, $this->id );
354
-
355
- if ( wc_notice_count( 'error' ) > 0 ) {
356
- return $this->get_order_error();
357
- }
358
- $this->processing_payment = true;
359
-
360
- if ( $this->order_contains_pre_order( $order ) && $this->pre_order_requires_tokenization( $order ) ) {
361
- return $this->process_pre_order( $order );
362
- }
363
-
364
- // if order total is zero, then save meta but don't process payment.
365
- if ( $order->get_total() == 0 ) {
366
- return $this->process_zero_total_order( $order );
367
- }
368
-
369
- $result = $this->payment_object->process_payment( $order, $this );
370
-
371
- if ( is_wp_error( $result ) ) {
372
- wc_add_notice( $this->is_active( 'generic_error' ) ? $this->get_generic_error( $result ) : $result->get_error_message(), 'error' );
373
-
374
- return $this->get_order_error();
375
- }
376
-
377
- if ( $result->complete_payment ) {
378
- $this->payment_object->payment_complete( $order, $result->charge );
379
- $this->trigger_post_payment_processes( $order, $this );
380
- WC()->cart->empty_cart();
381
-
382
- return array(
383
- 'result' => 'success',
384
- 'redirect' => $order->get_checkout_order_received_url(),
385
- );
386
- } else {
387
- return array(
388
- 'result' => 'success',
389
- 'redirect' => $result->redirect,
390
- );
391
- }
392
- }
393
-
394
- /**
395
- *
396
- * @return array
397
- */
398
- public function get_localized_params() {
399
- return array(
400
- 'gateway_id' => $this->id,
401
- 'api_key' => wc_stripe_get_publishable_key(),
402
- 'saved_method_selector' => '[name="' . $this->saved_method_key . '"]',
403
- 'token_selector' => '[name="' . $this->token_key . '"]',
404
- 'messages' => array( 'terms' => __( 'Please read and accept the terms and conditions to proceed with your order.', 'woocommerce' ) ),
405
- 'routes' => array(
406
- 'setup_intent' => wc_stripe()->rest_api->payment_intent->rest_url( 'setup-intent' ),
407
- 'sync_intent' => wc_stripe()->rest_api->payment_intent->rest_url( 'sync-payment-intent' ),
408
- 'add_to_cart' => wc_stripe()->rest_api->cart->rest_url( 'add-to-cart' ),
409
- 'cart_calculation' => wc_stripe()->rest_api->cart->rest_url( 'cart-calculation' ),
410
- 'shipping_method' => wc_stripe()->rest_api->cart->rest_url( 'shipping-method' ),
411
- 'shipping_address' => wc_stripe()->rest_api->cart->rest_url( 'shipping-address' ),
412
- 'checkout' => wc_stripe()->rest_api->checkout->rest_url( 'checkout' ),
413
- ),
414
- 'rest_nonce' => wp_create_nonce( 'wp_rest' ),
415
- 'banner_enabled' => $this->banner_checkout_enabled(),
416
- 'currency' => get_woocommerce_currency(),
417
- 'total_label' => __( 'Total', 'woo-stripe-payment' ),
418
- 'country_code' => wc_get_base_location()['country'],
419
- 'user_id' => get_current_user_id()
420
- );
421
- }
422
-
423
- /**
424
- * Save the Stripe data to the order.
425
- *
426
- * @param WC_Order $order
427
- * @param \Stripe\Charge $charge
428
- */
429
- public function save_order_meta( $order, $charge ) {
430
- /**
431
- *
432
- * @var WC_Payment_Token_Stripe $token
433
- */
434
- $token = $this->get_payment_token( $this->get_payment_method_from_charge( $charge ), $charge->payment_method_details );
435
- $order->set_transaction_id( $charge->id );
436
- $order->set_payment_method_title( $token->get_payment_method_title() );
437
- $order->update_meta_data( WC_Stripe_Constants::MODE, wc_stripe_mode() );
438
- $order->update_meta_data( WC_Stripe_Constants::CHARGE_STATUS, $charge->status );
439
- $order->update_meta_data( WC_Stripe_Constants::PAYMENT_METHOD_TOKEN, $token->get_token() );
440
- $order->save();
441
-
442
- // if WCS is active and there are subscriptions in the order, save meta data
443
- if ( wcs_stripe_active() && wcs_order_contains_subscription( $order ) ) {
444
- foreach ( wcs_get_subscriptions_for_order( $order ) as $subscription ) {
445
- $subscription->set_transaction_id( $charge->id );
446
- $subscription->set_payment_method_title( $token->get_payment_method_title() );
447
- $subscription->update_meta_data( WC_Stripe_Constants::MODE, wc_stripe_mode() );
448
- $subscription->update_meta_data( WC_Stripe_Constants::CHARGE_STATUS, $charge->status );
449
- $subscription->update_meta_data( WC_Stripe_Constants::PAYMENT_METHOD_TOKEN, $token->get_token() );
450
- $subscription->update_meta_data( WC_Stripe_Constants::CUSTOMER_ID, wc_stripe_get_customer_id( $order->get_user_id() ) );
451
- $subscription->save();
452
- }
453
- }
454
- }
455
-
456
- /**
457
- * Given a charge object, return the ID of the payment method used for the charge.
458
- *
459
- * @param \Stripe\Charge $charge
460
- *
461
- * @since 3.0.6
462
- */
463
- public function get_payment_method_from_charge( $charge ) {
464
- return $this->payment_object->get_payment_method_from_charge( $charge );
465
- }
466
-
467
- /**
468
- *
469
- * {@inheritDoc}
470
- *
471
- * @see WC_Payment_Gateway::add_payment_method()
472
- */
473
- public function add_payment_method() {
474
- $user_id = get_current_user_id();
475
- try {
476
- if ( ! is_user_logged_in() ) {
477
- throw new Exception( __( 'User must be logged in.', 'woo-stripe-payment' ) );
478
- }
479
-
480
- $customer_id = wc_stripe_get_customer_id( $user_id );
481
-
482
- if ( empty( $customer_id ) ) {
483
- $customer_id = $this->create_customer( $user_id );
484
- }
485
-
486
- $result = $this->create_payment_method( $this->get_new_source_token(), $customer_id );
487
-
488
- if ( is_wp_error( $result ) ) {
489
- wc_add_notice( sprintf( __( 'Error saving your payment method. Reason: %s', 'woo-stripe-payment' ), $result->get_error_message() ), 'error' );
490
-
491
- return array( 'result' => 'error' );
492
- }
493
- $result->set_user_id( $user_id );
494
- $result->save();
495
- WC_Payment_Tokens::set_users_default( $user_id, $result->get_id() );
496
-
497
- do_action( 'wc_stripe_add_payment_method_success', $result );
498
-
499
- return array(
500
- 'result' => 'success',
501
- 'redirect' => wc_get_account_endpoint_url( 'payment-methods' ),
502
- );
503
- } catch ( \Stripe\Error\Base $e ) {
504
- wc_add_notice( sprintf( __( 'Error saving payment method. Reason: %s', 'woo-stripe-payment' ), $e->getMessage() ), 'error' );
505
-
506
- return array( 'result' => 'error' );
507
- }
508
- }
509
-
510
- /**
511
- *
512
- * {@inheritDoc}
513
- *
514
- * @see WC_Payment_Gateway::process_refund()
515
- */
516
- public function process_refund( $order_id, $amount = null, $reason = '' ) {
517
- $order = wc_get_order( $order_id );
518
- $result = $this->payment_object->process_refund( $order, $amount );
519
-
520
- if ( ! is_wp_error( $result ) ) {
521
- $order->add_order_note(
522
- sprintf(
523
- __( 'Order refunded in Stripe. Amount: %s', 'woo-stripe-payment' ),
524
- wc_price(
525
- $amount,
526
- array(
527
- 'currency' => $order->get_currency(),
528
- )
529
- )
530
- )
531
- );
532
- }
533
-
534
- return $result;
535
- }
536
-
537
- /**
538
- * Captures the charge for the Stripe order.
539
- *
540
- * @param float $amount
541
- * @param WC_Order $order
542
- */
543
- public function capture_charge( $amount, $order ) {
544
- $result = $this->gateway->charges->mode( wc_stripe_order_mode( $order ) )->retrieve( $order->get_transaction_id() );
545
-
546
- if ( is_wp_error( $result ) ) {
547
- return;
548
- } else {
549
- if ( ! $result->captured ) {
550
- $result = $this->payment_object->capture_charge( $amount, $order );
551
-
552
- if ( ! is_wp_error( $result ) ) {
553
- remove_action( 'woocommerce_order_status_completed', 'wc_stripe_order_status_completed' );
554
- $order->payment_complete();
555
- if ( $amount != $order->get_total() ) {
556
- $order->set_total( $amount );
557
- $order->save();
558
- }
559
- $order->add_order_note(
560
- sprintf(
561
- __( 'Order amount captured in Stripe. Amount: %s', 'woo-stripe-payment' ),
562
- wc_price(
563
- $amount,
564
- array(
565
- 'currency' => $order->get_currency(),
566
- )
567
- )
568
- )
569
- );
570
- } else {
571
- $order->add_order_note( sprintf( __( 'Error capturing charge in Stripe. Reason: %s', 'woo-stripe-payment' ), $result->get_error_message() ) );
572
- }
573
- }
574
- }
575
-
576
- return $result;
577
- }
578
-
579
- /**
580
- * Void the Stripe charge.
581
- *
582
- * @param WC_Order $order
583
- */
584
- public function void_charge( $order ) {
585
- // @3.1.1 - check added so errors aren't encountered if the order can't be voided
586
- if ( ! $this->payment_object->can_void_order( $order ) ) {
587
- return;
588
- }
589
- $result = $this->payment_object->void_charge( $order );
590
-
591
- if ( is_wp_error( $result ) ) {
592
- $order->add_order_note( sprintf( __( 'Error voiding charge. Reason: %s', 'woo-stripe-payment' ), $result->get_error_message() ) );
593
- } else {
594
- $order->add_order_note( __( 'Charge voided in Stripe.', 'woo-stripe-payment' ) );
595
- }
596
- }
597
-
598
- /**
599
- * Return the \Stripe\Charge object
600
- *
601
- * @param String $charge_id
602
- * @param String $mode
603
- *
604
- * @return WP_Error|\Stripe\Charge
605
- */
606
- public function retrieve_charge( $charge_id, $mode = '' ) {
607
- return $this->gateway->charges->mode( $mode )->retrieve( $charge_id );
608
- }
609
-
610
- /**
611
- *
612
- * @param string $method_id
613
- * @param \Stripe\Card|array $method_details
614
- */
615
- public function get_payment_token( $method_id, $method_details = null ) {
616
- $class_name = 'WC_Payment_Token_' . $this->token_type;
617
- if ( class_exists( $class_name ) ) {
618
- /**
619
- *
620
- * @var WC_Payment_Token_Stripe $token
621
- */
622
- $token = new $class_name( '', $method_details );
623
- $token->set_token( $method_id );
624
- $token->set_gateway_id( $this->id );
625
- $token->set_format( $this->get_option( 'method_format' ) );
626
- $token->set_environment( wc_stripe_mode() );
627
- if ( $method_details ) {
628
- $token->details_to_props( $method_details );
629
- }
630
-
631
- return $token;
632
- }
633
- }
634
-
635
- /**
636
- * Return a failed order response.
637
- *
638
- * @return array
639
- */
640
- public function get_order_error() {
641
- wc_stripe_set_checkout_error();
642
-
643
- return array( 'result' => WC_Stripe_Constants::FAILURE );
644
- }
645
-
646
- /**
647
- * Return the payment source the customer has chosen to use.
648
- * This can be a saved source
649
- * or a one time use source.
650
- */
651
- public function get_payment_source() {
652
- if ( $this->use_saved_source() ) {
653
- return $this->get_saved_source_id();
654
- } else {
655
- if ( $this->payment_method_token ) {
656
- return $this->payment_method_token;
657
- }
658
-
659
- return $this->get_new_source_token();
660
- }
661
- }
662
-
663
- /**
664
- * Returns the payment method the customer wants to use.
665
- * This can be a saved payment method
666
- * or a new payment method.
667
- */
668
- public function get_payment_method_from_request() {
669
- return $this->get_payment_source();
670
- }
671
-
672
- public function get_payment_intent_id() {
673
- return ! empty( $_POST[ $this->payment_intent_key ] ) ? $_POST[ $this->payment_intent_key ] : '';
674
- }
675
-
676
- /**
677
- * Return true of the customer is using a saved payment method.
678
- */
679
- public function use_saved_source() {
680
- return ( ! empty( $_POST[ $this->payment_type_key ] ) && $_POST[ $this->payment_type_key ] === 'saved' ) || $this->payment_method_token;
681
- }
682
-
683
- /**
684
- *
685
- * @deprecated
686
- *
687
- */
688
- public function get_new_source_id() {
689
- return $this->get_new_source_token();
690
- }
691
-
692
- public function get_new_source_token() {
693
- return null != $this->new_source_token ? $this->new_source_token : ( ! empty( $_POST[ $this->token_key ] ) ? $_POST[ $this->token_key ] : '' );
694
- }
695
-
696
- public function get_saved_source_id() {
697
- return ! empty( $_POST[ $this->saved_method_key ] ) ? $_POST[ $this->saved_method_key ] : $this->payment_method_token;
698
- }
699
-
700
- /**
701
- * Create a customer in the stripe gateway.
702
- *
703
- * @param int $user_id
704
- */
705
- public function create_customer( $user_id ) {
706
- $customer = WC()->customer;
707
- $response = $this->gateway->customers->create(
708
- apply_filters( 'wc_stripe_customer_args', array(
709
- 'email' => $customer->get_email(),
710
- 'name' => sprintf( '%s %s', $customer->get_first_name(), $customer->get_last_name() ),
711
- 'phone' => $customer->get_billing_phone(),
712
- 'metadata' => array(
713
- 'user_id' => $customer->get_id(),
714
- 'username' => $customer->get_username(),
715
- 'website' => get_site_url(),
716
- ),
717
- ) )
718
- );
719
- if ( ! is_wp_error( $response ) ) {
720
- wc_stripe_save_customer( $response->id, $user_id );
721
- }
722
-
723
- return $customer;
724
- }
725
-
726
- /**
727
- * Creates a payment method in Stripe.
728
- *
729
- * @param string $id
730
- * payment method id
731
- * @param string $customer_id
732
- * WC Stripe customer ID
733
- *
734
- * @return WC_Payment_Token_Stripe|WP_Error
735
- */
736
- public function create_payment_method( $id, $customer_id ) {
737
- $token = $this->get_payment_token( $id );
738
- $token->set_customer_id( $customer_id );
739
-
740
- $result = $token->save_payment_method();
741
-
742
- if ( is_wp_error( $result ) ) {
743
- return $result;
744
- } else {
745
- $token->set_token( $result->id );
746
- $token->details_to_props( $result );
747
-
748
- return $token;
749
- }
750
- }
751
-
752
- /**
753
- *
754
- * @param array $item
755
- * @param WC_Payment_Token_Stripe_CC $payment_token
756
- */
757
- public function payment_methods_list_item( $item, $payment_token ) {
758
- if ( $payment_token->get_type() === $this->token_type ) {
759
- $item['method']['last4'] = $payment_token->get_last4();
760
- $item['method']['brand'] = ucfirst( $payment_token->get_brand() );
761
- if ( $payment_token->has_expiration() ) {
762
- $item['expires'] = sprintf( '%s / %s', $payment_token->get_exp_month(), $payment_token->get_exp_year() );
763
- } else {
764
- $item['expires'] = __( 'n/a', 'woo-stripe-payment' );
765
- }
766
- $item['wc_stripe_method'] = true;
767
- }
768
-
769
- return $item;
770
- }
771
-
772
- /**
773
- *
774
- * @param string $token_id
775
- * @param WC_Payment_Token_Stripe $token
776
- */
777
- public function delete_payment_method( $token_id, $token ) {
778
- $token->delete_from_stripe();
779
- }
780
-
781
- public function saved_payment_methods( $tokens = array() ) {
782
- wc_stripe_get_template(
783
- 'payment-methods.php',
784
- array(
785
- 'tokens' => $tokens,
786
- 'gateway' => $this,
787
- )
788
- );
789
- }
790
-
791
- public function get_new_method_label() {
792
- return __( 'New Card', 'woo-stripe-payment' );
793
- }
794
-
795
- public function get_saved_methods_label() {
796
- return __( 'Saved Cards', 'woo-stripe-payment' );
797
- }
798
-
799
- /**
800
- * Return true if shipping is needed.
801
- * Shipping is based on things like if the cart or product needs shipping.
802
- *
803
- * @return bool
804
- */
805
- public function get_needs_shipping() {
806
- if ( is_checkout() || is_cart() ) {
807
- global $wp;
808
- if ( wcs_stripe_active() && WC_Subscriptions_Change_Payment_Gateway::$is_request_to_change_payment ) {
809
- return false;
810
- }
811
- // return false if this is the order pay page. Gateways that have payment sheets don't need
812
- // to make any changes to the order.
813
- if ( ! empty( $wp->query_vars['order-pay'] ) ) {
814
- return false;
815
- }
816
-
817
- return WC()->cart->needs_shipping();
818
- }
819
- if ( is_product() ) {
820
- global $product;
821
-
822
- return is_a( $product, 'WC_Product' ) && $product->needs_shipping();
823
- }
824
- }
825
-
826
- /**
827
- * Return true of the payment method should be saved.
828
- *
829
- * @param WC_Order $order
830
- *
831
- * @return bool
832
- */
833
- public function should_save_payment_method( $order ) {
834
- if ( ! $this->use_saved_source() ) {
835
- if ( wcs_stripe_active() ) {
836
- if ( wcs_order_contains_subscription( $order ) && $this->supports( 'subscriptions' ) ) {
837
- return true;
838
- }
839
- if ( wcs_cart_contains_renewal() ) {
840
- return true;
841
- }
842
- }
843
- if ( ! empty( $_POST[ $this->save_source_key ] ) ) {
844
- return true;
845
- }
846
- }
847
-
848
- return false;
849
- }
850
-
851
- /**
852
- * Returns true if the save payment method checkbox can be displayed.
853
- *
854
- * @return boolean
855
- */
856
- public function show_save_source() {
857
- global $wp;
858
- if ( wcs_stripe_active() ) {
859
- if ( WC_Subscriptions_Cart::cart_contains_subscription() ) {
860
- return false;
861
- }
862
- if ( WC_Subscriptions_Change_Payment_Gateway::$is_request_to_change_payment ) {
863
- return false;
864
- }
865
- if ( wcs_cart_contains_renewal() ) {
866
- return false;
867
- }
868
- }
869
- // @since 3.1.5
870
- if ( wc_stripe_pre_orders_active() && WC_Pre_Orders_Cart::cart_contains_pre_order() ) {
871
- return ! WC_Pre_Orders_Product::product_is_charged_upon_release( WC_Pre_Orders_Cart::get_pre_order_product() );
872
- }
873
-
874
- return is_user_logged_in() && is_checkout() && $this->is_active( 'save_card_enabled' );
875
- }
876
-
877
- /**
878
- * Returns a formatted array of items for display in the payment gateway's payment sheet.
879
- *
880
- * @param stirng $page
881
- *
882
- * @return []
883
- */
884
- public function get_display_items( $page = 'checkout', $order = null ) {
885
- global $wp;
886
- $items = array();
887
- if ( in_array( $page, array( 'cart', 'checkout' ) ) ) {
888
- $items = $this->get_display_items_for_cart( WC()->cart );
889
- } elseif ( 'order_pay' === $page ) {
890
- $order = ! is_null( $order ) ? $order : wc_get_order( absint( $wp->query_vars['order-pay'] ) );
891
- $items = $this->get_display_items_for_order( $order );
892
- } elseif ( 'product' === $page ) {
893
- global $product;
894
- $items = array( $this->get_display_item_for_product( $product ) );
895
- }
896
-
897
- /**
898
- * @param array $items
899
- * @param WC_Order|null $order
900
- * @param string $page
901
- */
902
- return apply_filters( 'wc_stripe_get_display_items', $items, $order, $page );
903
- }
904
-
905
- /**
906
- * Returns a formatted array of shipping methods for display in the payment gateway's
907
- * payment sheet.
908
- *
909
- * @param bool $encode
910
- *
911
- * @return array
912
- * @deprecated
913
- */
914
- public function get_shipping_methods() {
915
- return $this->get_formatted_shipping_methods();
916
- }
917
-
918
- /**
919
- * Return true if product page checkout is enabled for this gateway
920
- *
921
- * @return bool
922
- */
923
- public function product_checkout_enabled() {
924
- return in_array( 'product', $this->get_option( 'payment_sections', array() ) );
925
- }
926
-
927
- /**
928
- * Return true if cart page checkout is enabled for this gateway
929
- *
930
- * @return bool
931
- */
932
- public function cart_checkout_enabled() {
933
- return in_array( 'cart', $this->get_option( 'payment_sections', array() ) );
934
- }
935
-
936
- /**
937
- * Return true if mini-cart checkout is enabled for this gateway
938
- *
939
- * @return bool
940
- * @since 3.1.8
941
- */
942
- public function mini_cart_enabled() {
943
- return in_array( 'mini_cart', $this->get_option( 'payment_sections', array() ) );
944
- }
945
-
946
- /**
947
- * Return true if checkout page banner is enabled for this gateway
948
- *
949
- * @return bool
950
- */
951
- public function banner_checkout_enabled() {
952
- global $wp;
953
-
954
- return empty( $wp->query_vars['order-pay'] ) && $this->supports( 'wc_stripe_banner_checkout' ) &&
955
- in_array( 'checkout_banner', $this->get_option( 'payment_sections', array() ) );
956
- }
957
-
958
- /**
959
- * Decorate the response with data specific to the gateway.
960
- *
961
- * @param [] $data
962
- */
963
- public function add_to_cart_response( $data ) {
964
- return $data;
965
- }
966
-
967
- /**
968
- * Decorate the update shipping method reponse with data.
969
- *
970
- * @param [] $data
971
- */
972
- public function get_update_shipping_method_response( $data ) {
973
- return $data;
974
- }
975
-
976
- /**
977
- * Decorate the update shipping address respond with data.
978
- *
979
- * @param [] $data
980
- */
981
- public function get_update_shipping_address_response( $data ) {
982
- return apply_filters( 'wc_stripe_update_shipping_address_response', $data );
983
- }
984
-
985
- /**
986
- * Save the customer's payment method.
987
- * If the payment method has already been saved to the customer
988
- * then simply return true.
989
- *
990
- * @param string $id
991
- * @param WC_Order $order
992
- *
993
- * @return WP_Error|bool
994
- */
995
- public function save_payment_method( $id, $order ) {
996
- $token = $this->create_payment_method( $id, wc_stripe_get_customer_id( $order->get_user_id() ) );
997
- if ( is_wp_error( $token ) ) {
998
- $this->wp_error = $token;
999
- $order->add_order_note( sprintf( __( 'Attemp to save payment method failed. Reason: %s', 'woo-stripe-payment' ), $token->get_error_message() ) );
1000
-
1001
- return $token;
1002
- }
1003
- $token->set_user_id( $order->get_user_id() );
1004
- $token->save();
1005
-
1006
- // set token value so it can be used for other processes.
1007
- $this->payment_method_token = $token->get_token();
1008
-
1009
- return true;
1010
- }
1011
-
1012
- /**
1013
- * Set an error on the order.
1014
- * This error is used on the frontend to alert customer's to a failed payment method save.
1015
- *
1016
- * @param WC_Order $order
1017
- * @param WP_Error $error
1018
- */
1019
- public function set_payment_save_error( $order, $error ) {
1020
- if ( wcs_stripe_active() && wcs_order_contains_subscription( $order ) ) {
1021
- $message = __( 'We were not able to save your payment method. To prevent billing issues with your subscription, please add a payment method to the subscription.', 'woo-stripe-payment' );
1022
- } else {
1023
- $message = sprintf( __( 'We were not able to save your payment method. Reason: %s', 'woo-stripe-payment' ), $error->get_error_message() );
1024
- }
1025
- $order->update_meta_data( '_wc_stripe_order_error', $message );
1026
- $order->save();
1027
- }
1028
-
1029
- /**
1030
- *
1031
- * @param string $token_id
1032
- * @param int $user_id
1033
- *
1034
- * @return null|WC_Payment_Token_Stripe_CC
1035
- */
1036
- public function get_token( $token_id, $user_id ) {
1037
- $tokens = WC_Payment_Tokens::get_tokens( array( 'user_id' => $user_id, 'gateway_id' => $this->id, 'limit' => 20 ) );
1038
- foreach ( $tokens as $token ) {
1039
- if ( $token_id === $token->get_token() ) {
1040
- return $token;
1041
- }
1042
- }
1043
-
1044
- return null;
1045
- }
1046
-
1047
- /**
1048
- *
1049
- * @param array $payment_meta
1050
- * @param WC_Subscription $subscription
1051
- */
1052
- public function subscription_payment_meta( $payment_meta, $subscription ) {
1053
- $payment_meta[ $this->id ] = array(
1054
- 'post_meta' => array(
1055
- WC_Stripe_Constants::PAYMENT_METHOD_TOKEN => array(
1056
- 'value' => $this->get_order_meta_data( WC_Stripe_Constants::PAYMENT_METHOD_TOKEN, $subscription ),
1057
- 'label' => __( 'Payment Method Token', 'woo-stripe-payment' ),
1058
- ),
1059
- ),
1060
- );
1061
-
1062
- return $payment_meta;
1063
- }
1064
-
1065
- /**
1066
- *
1067
- * @param float $amount
1068
- * @param WC_Order $order
1069
- */
1070
- public function scheduled_subscription_payment( $amount, $order ) {
1071
- $this->processing_payment = true;
1072
-
1073
- $result = $this->payment_object->scheduled_subscription_payment( $amount, $order );
1074
-
1075
- if ( is_wp_error( $result ) ) {
1076
- $order->update_status( 'failed' );
1077
- $order->add_order_note( sprintf( __( 'Recurring payment for order failed. Reason: %s', 'woo-stripe-payment' ), $result->get_error_message() ) );
1078
-
1079
- return;
1080
- }
1081
-
1082
- $this->save_order_meta( $order, $result->charge );
1083
-
1084
- // set the payment method token that was used to process the renewal order.
1085
- $this->payment_method_token = $order->get_meta( WC_Stripe_Constants::PAYMENT_METHOD_TOKEN );
1086
-
1087
- if ( $result->complete_payment ) {
1088
- if ( $result->charge->captured ) {
1089
- $order->payment_complete( $result->charge->id );
1090
- $order->add_order_note( sprintf( __( 'Recurring payment captured in Stripe. Payment method: %s', 'woo-stripe-payment' ), $order->get_payment_method_title() ) );
1091
- } else {
1092
- $order->update_status( apply_filters( 'wc_stripe_authorized_renewal_order_status', 'on-hold', $order, $this ), sprintf( __( 'Recurring payment authorized in Stripe. Payment method: %s', 'woo-stripe-payment' ), $order->get_payment_method_title() ) );
1093
- }
1094
- } else {
1095
- $order->update_status( 'pending', sprintf( __( 'Customer must manually complete payment for payment method %s', 'woo-stripe-payment' ), $order->get_payment_method_title() ) );
1096
- }
1097
- }
1098
-
1099
- /**
1100
- *
1101
- * @param WC_Subscription $subscription
1102
- * @param string $new_payment_method
1103
- * @param string $old_payment_method
1104
- */
1105
- public function subscriptions_pre_update_payment_method( $subscription, $new_payment_method, $old_payment_method ) {
1106
- if ( $new_payment_method === $this->id ) {
1107
- // customer is using a new payment method so we need to save it.
1108
- if ( ! $this->use_saved_source() ) {
1109
- $result = $this->save_payment_method( $this->get_new_source_token(), $subscription );
1110
- if ( is_wp_error( $result ) ) {
1111
- wc_add_notice( sprintf( __( 'Error saving payment method for subscription. Reason: %s', 'woo-stripe-payment' ), $result->get_error_message() ), 'error' );
1112
- // redirect to change payment method page.
1113
- wp_safe_redirect( $subscription->get_view_order_url() );
1114
- exit();
1115
- }
1116
- } else {
1117
- if ( ! $this->payment_method_token ) {
1118
- // set the payment method token so it can be used downstream.
1119
- $this->payment_method_token = $this->get_payment_source();
1120
- }
1121
- }
1122
- }
1123
- }
1124
-
1125
- /**
1126
- * Update the subscription with the new meta data for the gateway.
1127
- * Save any new method the customer is trying to use.
1128
- *
1129
- * @param WC_Subscription $subscription
1130
- */
1131
- public function subscription_payment_method_updated( $subscription ) {
1132
- $token = $this->get_token( $this->payment_method_token, $subscription->get_user_id() );
1133
-
1134
- // update the meta data needed by the gateway to process a subscription payment.
1135
- $subscription->update_meta_data( WC_Stripe_Constants::PAYMENT_METHOD_TOKEN, $this->payment_method_token );
1136
- if ( $token ) {
1137
- $subscription->set_payment_method_title( $token->get_payment_method_title() );
1138
- }
1139
- $subscription->save();
1140
- }
1141
-
1142
- /**
1143
- * Return true if this request is to change the payment method of a WC Subscription.
1144
- *
1145
- * @return bool
1146
- */
1147
- public function is_change_payment_method_request() {
1148
- return wcs_stripe_active() && did_action( 'woocommerce_subscriptions_pre_update_payment_method' );
1149
- }
1150
-
1151
- /**
1152
- * Sets the ID of a payment token.
1153
- *
1154
- * @param string $id
1155
- */
1156
- public function set_payment_method_token( $id ) {
1157
- $this->payment_method_token = $id;
1158
- }
1159
-
1160
- public function set_new_source_token( $token ) {
1161
- $this->new_source_token = $token;
1162
- }
1163
-
1164
- /**
1165
- *
1166
- * @param WC_Order $order
1167
- *
1168
- * @deprecated
1169
- *
1170
- */
1171
- public function get_order_description( $order ) {
1172
- return sprintf( __( 'Order %1$s from %2$s', 'woo-stripe-payment' ), $order->get_order_number(), get_bloginfo( 'name' ) );
1173
- }
1174
-
1175
- /**
1176
- *
1177
- * @param WC_Order $order
1178
- */
1179
- public function process_zero_total_order( $order ) {
1180
- // save payment method if necessary
1181
- if ( $this->should_save_payment_method( $order ) ) {
1182
- $result = $this->save_payment_method( $this->get_new_source_token(), $order );
1183
- if ( is_wp_error( $result ) ) {
1184
- wc_add_notice( $result->get_error_message(), 'error' );
1185
-
1186
- return $this->get_order_error();
1187
- }
1188
- } else {
1189
- $this->payment_method_token = $this->get_saved_source_id();
1190
- }
1191
- $this->save_zero_total_meta( $order );
1192
- $order_status = $this->get_option( 'order_status' );
1193
- if ( 'capture' === $this->get_option( 'charge_type' ) ) {
1194
- $order->payment_complete();
1195
- } else {
1196
- $order_status = $this->get_option( 'order_status' );
1197
- $order->update_status( apply_filters( 'wc_stripe_authorized_order_status', 'default' === $order_status ? 'on-hold' : $order_status, $order, $this ) );
1198
- }
1199
- WC()->cart->empty_cart();
1200
-
1201
- return array(
1202
- 'result' => 'success',
1203
- 'redirect' => $order->get_checkout_order_received_url(),
1204
- );
1205
- }
1206
-
1207
- public function process_pre_order( $order ) {
1208
- // maybe save payment method
1209
- if ( ! $this->use_saved_source() ) {
1210
- $result = $this->save_payment_method( $this->get_new_source_token(), $order );
1211
- if ( is_wp_error( $result ) ) {
1212
- wc_add_notice( $result->get_error_message(), 'error' );
1213
-
1214
- return $this->get_order_error();
1215
- }
1216
- } else {
1217
- $this->payment_method_token = $this->get_saved_source_id();
1218
- }
1219
- WC_Pre_Orders_Order::mark_order_as_pre_ordered( $order );
1220
- $this->save_zero_total_meta( $order );
1221
-
1222
- return array(
1223
- 'result' => 'success',
1224
- 'redirect' => $order->get_checkout_order_received_url(),
1225
- );
1226
- }
1227
-
1228
- /**
1229
- *
1230
- * @param WC_Order $order
1231
- */
1232
- protected function save_zero_total_meta( $order ) {
1233
- $token = $this->get_token( $this->payment_method_token, $order->get_user_id() );
1234
- $order->set_payment_method_title( $token->get_payment_method_title() );
1235
- $order->update_meta_data( WC_Stripe_Constants::MODE, wc_stripe_mode() );
1236
- $order->update_meta_data( WC_Stripe_Constants::PAYMENT_METHOD_TOKEN, $token->get_token() );
1237
- $order->update_meta_data( WC_Stripe_Constants::CUSTOMER_ID, wc_stripe_get_customer_id( $order->get_user_id() ) );
1238
- $order->save();
1239
-
1240
- if ( wcs_stripe_active() && wcs_order_contains_subscription( $order ) ) {
1241
- foreach ( wcs_get_subscriptions_for_order( $order ) as $subscription ) {
1242
- /**
1243
- *
1244
- * @var WC_Subscription $subscription
1245
- */
1246
- $subscription->set_payment_method_title( $token->get_payment_method_title() );
1247
- $subscription->update_meta_data( WC_Stripe_Constants::MODE, wc_stripe_mode() );
1248
- $subscription->update_meta_data( WC_Stripe_Constants::PAYMENT_METHOD_TOKEN, $token->get_token() );
1249
- $subscription->update_meta_data( WC_Stripe_Constants::CUSTOMER_ID, wc_stripe_get_customer_id( $order->get_user_id() ) );
1250
- $subscription->save();
1251
- }
1252
- }
1253
- }
1254
-
1255
- /**
1256
- * Pre orders can't be mixed with regular products.
1257
- *
1258
- * @param WC_Order $order
1259
- */
1260
- protected function order_contains_pre_order( $order ) {
1261
- return wc_stripe_pre_orders_active() && WC_Pre_Orders_Order::order_contains_pre_order( $order );
1262
- }
1263
-
1264
- /**
1265
- *
1266
- * @param WC_Order $order
1267
- *
1268
- * @return boolean
1269
- */
1270
- protected function pre_order_requires_tokenization( $order ) {
1271
- return WC_Pre_Orders_Order::order_requires_payment_tokenization( $order );
1272
- }
1273
-
1274
- /**
1275
- * Sets a lock on the order.
1276
- * Default behavior is a 2 minute lock.
1277
- *
1278
- * @param WC_Order|int $order
1279
- */
1280
- public function set_order_lock( $order ) {
1281
- $order_id = ( is_object( $order ) ? $order->get_id() : $order );
1282
- set_transient( 'stripe_lock_order_' . $order_id, $order_id, apply_filters( 'wc_stripe_set_order_lock', 2 * MINUTE_IN_SECONDS ) );
1283
- }
1284
-
1285
- /**
1286
- * Removes the lock on the order
1287
- *
1288
- * @param WC_Order|int $order
1289
- */
1290
- public function release_order_lock( $order ) {
1291
- delete_transient( 'stripe_lock_order_' . ( is_object( $order ) ? $order->get_id() : $order ) );
1292
- }
1293
-
1294
- /**
1295
- * Returns true of the order has been locked.
1296
- * If the lock exists and is greater than current time
1297
- * method returns true;
1298
- *
1299
- * @param WC_Order|int $order
1300
- */
1301
- public function has_order_lock( $order ) {
1302
- $lock = get_transient( 'stripe_lock_order_' . ( is_object( $order ) ? $order->get_id() : $order ) );
1303
-
1304
- return $lock !== false;
1305
- }
1306
-
1307
- public function set_post_payment_process( $callback ) {
1308
- $this->post_payment_processes[] = $callback;
1309
- }
1310
-
1311
- /**
1312
- *
1313
- * @param WC_Order $order
1314
- * @param WC_Payment_Gateway_Stripe $gateway
1315
- */
1316
- public function trigger_post_payment_processes( $order, $gateway ) {
1317
- foreach ( $this->post_payment_processes as $callback ) {
1318
- call_user_func_array( $callback, func_get_args() );
1319
- }
1320
- }
1321
-
1322
- public function validate_payment_sections_field( $key, $value ) {
1323
- if ( empty( $value ) ) {
1324
- $value = array();
1325
- }
1326
-
1327
- return $value;
1328
- }
1329
-
1330
- /**
1331
- *
1332
- * @param WC_Order $order
1333
- */
1334
- public function process_pre_order_payment( $order ) {
1335
- $this->processing_payment = true;
1336
-
1337
- $result = $this->payment_object->process_pre_order_payment( $order );
1338
-
1339
- if ( is_wp_error( $result ) ) {
1340
- $order->update_status( 'failed' );
1341
- $order->add_order_note( sprintf( __( 'Pre-order payment for order failed. Reason: %s', 'woo-stripe-payment' ), $result->get_error_message() ) );
1342
- } else {
1343
- if ( $result->complete_payment ) {
1344
-
1345
- $this->save_order_meta( $order, $result->charge );
1346
-
1347
- if ( $result->charge->captured ) {
1348
- $order->payment_complete( $result->charge->id );
1349
- $order->add_order_note( sprintf( __( 'Pre-order payment captured in Stripe. Payment method: %s', 'woo-stripe-payment' ), $order->get_payment_method_title() ) );
1350
- } else {
1351
- $order->update_status( apply_filters( 'wc_stripe_authorized_preorder_order_status', 'on-hold', $order, $this ), sprintf( __( 'Pre-order payment authorized in Stripe. Payment method: %s', 'woo-stripe-payment' ), $order->get_payment_method_title() ) );
1352
- }
1353
- } else {
1354
- $order->update_status( 'pending', sprintf( __( 'Customer must manually complete payment for payment method %s', 'woo-stripe-payment' ), $order->get_payment_method_title() ) );
1355
- }
1356
- }
1357
- }
1358
-
1359
- /**
1360
- * Given a meta key, see if there is a value for that key in another plugin.
1361
- * This acts as a lazy conversion
1362
- * method for merchants that have switched to our plugin from other plugins.
1363
- *
1364
- * @param string $meta_key
1365
- * @param WC_Order $order
1366
- * @param string $context
1367
- *
1368
- * @since 3.1.0
1369
- */
1370
- public function get_order_meta_data( $meta_key, $order, $context = 'view' ) {
1371
- $value = $order->get_meta( $meta_key, true, $context );
1372
- // value is empty so check metadata from other plugins
1373
- if ( empty( $value ) ) {
1374
- $keys = array();
1375
- switch ( $meta_key ) {
1376
- case WC_Stripe_Constants::PAYMENT_METHOD_TOKEN:
1377
- $keys = array( WC_Stripe_Constants::SOURCE_ID );
1378
- break;
1379
- case WC_Stripe_Constants::CUSTOMER_ID:
1380
- $keys = array( WC_Stripe_Constants::STRIPE_CUSTOMER_ID );
1381
- break;
1382
- case WC_Stripe_Constants::PAYMENT_INTENT_ID:
1383
- $keys = array( WC_Stripe_Constants::STRIPE_INTENT_ID );
1384
- }
1385
- if ( $keys ) {
1386
- $meta_data = $order->get_meta_data();
1387
- if ( $meta_data ) {
1388
- $keys = array_intersect( wp_list_pluck( $meta_data, 'key' ), $keys );
1389
- $array_keys = array_keys( $keys );
1390
- if ( ! empty( $array_keys ) ) {
1391
- $value = $meta_data[ current( $array_keys ) ]->value;
1392
- update_post_meta( $order->get_id(), $meta_key, $value );
1393
- }
1394
- }
1395
- }
1396
- }
1397
-
1398
- return $value;
1399
- }
1400
-
1401
- /**
1402
- * Gateways can override this method to add attributes to the Stripe object before it's
1403
- * sent to Stripe.
1404
- *
1405
- * @param array $args
1406
- * @param WC_Order $order
1407
- */
1408
- public function add_stripe_order_args( &$args, $order ) {
1409
- }
1410
-
1411
- /**
1412
- *
1413
- * @param WP_Error $result
1414
- *
1415
- * @since 3.1.1
1416
- */
1417
- public function get_generic_error( $result = null ) {
1418
- $messages = wc_stripe_get_error_messages();
1419
- if ( isset( $messages["{$this->id}_generic"] ) ) {
1420
- return $messages["{$this->id}_generic"];
1421
- }
1422
-
1423
- return null != $result ? $result->get_error_message() : __( 'Cannot process payment', 'woo-stripe-payment' );
1424
- }
1425
-
1426
- /**
1427
- *
1428
- * @since 3.1.2
1429
- */
1430
- private function get_payment_section_description() {
1431
- return sprintf( __( 'Increase your conversion rate by offering %1$s on your Product and Cart pages, or at the top of the checkout page. <br/><strong>Note:</strong> you can control which products display %s by going to the product edit page.', 'woo-stripe-payment' ), $this->get_method_title() );
1432
- }
1433
-
1434
- /**
1435
- * Outputs fields required by Google Pay to render the payment wallet.
1436
- *
1437
- * @param string $page
1438
- */
1439
- public function output_display_items( $page = 'checkout' ) {
1440
- global $wp;
1441
- $order = null;
1442
- $data = array(
1443
- 'items' => $this->has_digital_wallet ? $this->get_display_items( $page ) : array(),
1444
- 'shipping_options' => $this->has_digital_wallet ? $this->get_formatted_shipping_methods() : array(),
1445
- 'total' => WC()->cart->total,
1446
- 'total_cents' => wc_stripe_add_number_precision( WC()->cart->total, get_woocommerce_currency() ),
1447
- 'currency' => get_woocommerce_currency()
1448
- );
1449
- if ( in_array( $page, array( 'checkout', 'cart' ) ) ) {
1450
- if ( ! empty( $wp->query_vars['order-pay'] ) ) {
1451
- $order = wc_get_order( absint( $wp->query_vars['order-pay'] ) );
1452
- $page = 'order_pay';
1453
- $data['needs_shipping'] = false;
1454
- $data['items'] = $this->has_digital_wallet ? $this->get_display_items( $page, $order ) : array();
1455
- $data['total'] = $order->get_total();
1456
- $data['total_cents'] = wc_stripe_add_number_precision( $order->get_total(), $order->get_currency() );
1457
- $data['currency'] = $order->get_currency();
1458
- } else {
1459
- $data['needs_shipping'] = WC()->cart->needs_shipping();
1460
- if ( 'checkout' === $page && is_cart() ) {
1461
- $page = 'cart';
1462
- } elseif ( is_add_payment_method_page() ) {
1463
- $page = 'add_payment_method';
1464
- }
1465
- }
1466
- } elseif ( 'product' === $page ) {
1467
- global $product;
1468
- $data['needs_shipping'] = $product->needs_shipping();
1469
- $data['product'] = array(
1470
- 'id' => $product->get_id(),
1471
- 'price' => $product->get_price(),
1472
- 'variation' => false
1473
- );
1474
- }
1475
- /**
1476
- * @param array $data
1477
- * @param string $page
1478
- * @param WC_Payment_Gateway_Stripe $this
1479
- *
1480
- * @since 3.1.8
1481
- */
1482
- $data = apply_filters( 'wc_stripe_output_display_items', $data, $page, $this );
1483
- printf( '<input type="hidden" class="%1$s" data-gateway="%2$s"/>', "woocommerce_{$this->id}_gateway_data {$page}-page", htmlspecialchars( wp_json_encode( $data ) ) );
1484
- }
1485
-
1486
- /**
1487
- * @param array $deps
1488
- * @param $scripts
1489
- *
1490
- * @since 3.1.8
1491
- */
1492
- public function get_mini_cart_dependencies( $deps, $scripts ) {
1493
- return $deps;
1494
- }
1495
-
1496
- /**
1497
- * @return array
1498
- * @since 3.2.0
1499
- */
1500
- public function get_shipping_packages() {
1501
- $packages = WC()->shipping()->get_packages();
1502
- if ( empty( $packages ) && wcs_stripe_active() && WC_Subscriptions_Cart::cart_contains_free_trial() ) {
1503
- // there is a subscription with a free trial in the cart. Shipping packages will be in the recurring cart.
1504
- WC_Subscriptions_Cart::set_calculation_type( 'recurring_total' );
1505
- $count = 0;
1506
- if ( isset( WC()->cart->recurring_carts ) ) {
1507
- foreach ( WC()->cart->recurring_carts as $recurring_cart_key => $recurring_cart ) {
1508
- foreach ( $recurring_cart->get_shipping_packages() as $i => $base_package ) {
1509
- $packages[ $recurring_cart_key . '_' . $count ] = WC_Subscriptions_Cart::get_calculated_shipping_for_package( $base_package );
1510
- }
1511
- $count ++;
1512
- }
1513
- }
1514
- WC_Subscriptions_Cart::set_calculation_type( 'none' );
1515
- }
1516
-
1517
- return $packages;
1518
- }
1519
-
1520
- /**
1521
- * @param WC_Cart $cart
1522
- * @param array $items
1523
- *
1524
- * @return array
1525
- * @since 3.2.1
1526
- */
1527
- protected function get_display_items_for_cart( $cart, $items = array() ) {
1528
- $incl_tax = wc_stripe_display_prices_including_tax();
1529
- foreach ( $cart->get_cart() as $cart_item ) {
1530
- /**
1531
- *
1532
- * @var WC_Product $product
1533
- */
1534
- $product = $cart_item['data'];
1535
- $qty = $cart_item['quantity'];
1536
- $label = $qty > 1 ? sprintf( '%s X %s', $product->get_name(), $qty ) : $product->get_name();
1537
- $price = $incl_tax ? wc_get_price_including_tax( $product, array( 'qty' => $qty ) ) : wc_get_price_excluding_tax( $product, array( 'qty' => $qty ) );
1538
- $items[] = $this->get_display_item_for_cart( $price, $label, 'product', $cart_item, $cart );
1539
- }
1540
- if ( $cart->needs_shipping() ) {
1541
- $price = $incl_tax ? $cart->shipping_total + $cart->shipping_tax_total : $cart->shipping_total;
1542
- $items[] = $this->get_display_item_for_cart( $price, __( 'Shipping', 'woo-stripe-payment' ), 'shipping' );
1543
- }
1544
- foreach ( $cart->get_fees() as $fee ) {
1545
- $price = $incl_tax ? $fee->total + $fee->tax : $fee->total;
1546
- $items[] = $this->get_display_item_for_cart( $price, $fee->name, 'fee', $fee, $cart );
1547
- }
1548
- if ( 0 < $cart->discount_cart ) {
1549
- $price = - 1 * abs( $incl_tax ? $cart->discount_cart + $cart->discount_cart_tax : $cart->discount_cart );
1550
- $items[] = $this->get_display_item_for_cart( $price, __( 'Discount', 'woo-stripe-payment' ), 'discount', $cart );
1551
- }
1552
- if ( ! $incl_tax && wc_tax_enabled() ) {
1553
- $items[] = $this->get_display_item_for_cart( $cart->get_taxes_total(), __( 'Tax', 'woo-stripe-payment' ), 'tax', $cart );
1554
- }
1555
-
1556
- return $items;
1557
- }
1558
-
1559
- /**
1560
- * @param WC_Order $order
1561
- * @param array $items
1562
- *
1563
- * @return array
1564
- * @since 3.2.1
1565
- */
1566
- protected function get_display_items_for_order( $order, $items = array() ) {
1567
- foreach ( $order->get_items() as $item ) {
1568
- $qty = $item->get_quantity();
1569
- $label = $qty > 1 ? sprintf( '%s X %s', $item->get_name(), $qty ) : $item->get_name();
1570
- $items[] = $this->get_display_item_for_order( $item->get_subtotal(), $label, $order, 'item', $item );
1571
- }
1572
- if ( 0 < $order->get_shipping_total() ) {
1573
- $items[] = $this->get_display_item_for_order( $order->get_shipping_total(), __( 'Shipping', 'woo-stripe-payment' ), $order, 'shipping' );
1574
- }
1575
- if ( 0 < $order->get_total_discount() ) {
1576
- $items[] = $this->get_display_item_for_order( - 1 * $order->get_total_discount(), __( 'Discount', 'woo-stripe-payment' ), $order, 'discount' );
1577
- }
1578
- if ( 0 < $order->get_fees() ) {
1579
- $fee_total = 0;
1580
- foreach ( $order->get_fees() as $fee ) {
1581
- $fee_total += $fee->get_total();
1582
- }
1583
- $items[] = $this->get_display_item_for_order( $fee_total, __( 'Fees', 'woo-stripe-payment' ), $order, 'fee' );
1584
- }
1585
- if ( 0 < $order->get_total_tax() ) {
1586
- $items[] = $this->get_display_item_for_order( $order->get_total_tax(), __( 'Tax', 'woocommerce' ), $order, 'tax' );
1587
- }
1588
-
1589
- return $items;
1590
- }
1591
-
1592
- /**
1593
- * @param float $price
1594
- * @param string $label
1595
- * @param string $type
1596
- * @param mixed ...$args
1597
- *
1598
- * @return array
1599
- * @since 3.2.1
1600
- */
1601
- protected function get_display_item_for_cart( $price, $label, $type, ...$args ) {
1602
- return array(
1603
- 'label' => $label,
1604
- 'pending' => false,
1605
- 'amount' => wc_stripe_add_number_precision( $price )
1606
- );
1607
- }
1608
-
1609
- /**
1610
- * @param float $price
1611
- * @param string $label
1612
- * @param WC_Order $order
1613
- * @param string $type
1614
- * @param mixed ...$args
1615
- */
1616
- protected function get_display_item_for_order( $price, $label, $order, $type, ...$args ) {
1617
- return array(
1618
- 'label' => $label,
1619
- 'pending' => false,
1620
- 'amount' => wc_stripe_add_number_precision( $price, $order->get_currency() )
1621
- );
1622
- }
1623
-
1624
- /**
1625
- * @param WC_Product $product
1626
- *
1627
- * @return array
1628
- * @since 3.2.1
1629
- *
1630
- */
1631
- protected function get_display_item_for_product( $product ) {
1632
- return array(
1633
- 'label' => esc_attr( $product->get_name() ),
1634
- 'pending' => true,
1635
- 'amount' => wc_stripe_add_number_precision( $product->get_price() )
1636
- );
1637
- }
1638
-
1639
- /**
1640
- * @param array $methods
1641
- *
1642
- * @return array
1643
- * @since 3.2.1
1644
- */
1645
- public function get_formatted_shipping_methods( $methods = array() ) {
1646
- if ( wcs_stripe_active() && WC_Subscriptions_Change_Payment_Gateway::$is_request_to_change_payment ) {
1647
- return $methods;
1648
- } else {
1649
- $methods = array();
1650
- $packages = $this->get_shipping_packages();
1651
- $incl_tax = wc_stripe_display_prices_including_tax();
1652
- foreach ( $packages as $i => $package ) {
1653
- foreach ( $package['rates'] as $rate ) {
1654
- $price = $incl_tax ? $rate->cost + $rate->get_shipping_tax() : $rate->cost;
1655
- $methods[] = $this->get_formatted_shipping_method( $price, $rate, $i, $package, $incl_tax );
1656
- }
1657
- }
1658
- }
1659
-
1660
- return $methods;
1661
- }
1662
-
1663
- /**
1664
- * @param float $price
1665
- * @param WC_Shipping_Rate $rate
1666
- * @param string $i
1667
- * @param array $package
1668
- * @param bool $incl_tax
1669
- *
1670
- * @return array
1671
- * @since 3.2.1
1672
- */
1673
- public function get_formatted_shipping_method( $price, $rate, $i, $package, $incl_tax ) {
1674
- $method = array(
1675
- 'id' => $this->get_shipping_method_id( $rate->id, $i ),
1676
- 'label' => $this->get_formatted_shipping_label( $price, $rate, $incl_tax ),
1677
- 'detail' => '',
1678
- 'amount' => wc_stripe_add_number_precision( $price )
1679
- );
1680
- if ( $incl_tax ) {
1681
- if ( $rate->get_shipping_tax() > 0 && ! wc_prices_include_tax() ) {
1682
- $method['detail'] = WC()->countries->inc_tax_or_vat();
1683
- }
1684
- } else {
1685
- if ( $rate->get_shipping_tax() > 0 && wc_prices_include_tax() ) {
1686
- $method['detail'] = WC()->countries->ex_tax_or_vat();
1687
- }
1688
- }
1689
-
1690
- return $method;
1691
- }
1692
-
1693
- /**
1694
- * @param string $id
1695
- * @param string $index
1696
- *
1697
- * @return mixed
1698
- */
1699
- protected function get_shipping_method_id( $id, $index ) {
1700
- return sprintf( '%s:%s', $index, $id );
1701
- }
1702
-
1703
- /**
1704
- * @param float $price
1705
- * @param WC_Shipping_Rate $rate
1706
- * @param bool $incl_tax
1707
- *
1708
- * @since 3.2.1
1709
- */
1710
- protected function get_formatted_shipping_label( $price, $rate, $incl_tax ) {
1711
- return sprintf( '%s', esc_attr( $rate->get_label() ) );
1712
- }
1713
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ defined( 'ABSPATH' ) || exit();
3
+
4
+ if ( ! class_exists( 'WC_Payment_Gateway' ) ) {
5
+ return;
6
+ }
7
+
8
+ require_once( WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-payment-intent.php' );
9
+ require_once( WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-payment-charge.php' );
10
+ require_once( WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-payment-charge-local.php' );
11
+
12
+ require_once( WC_STRIPE_PLUGIN_FILE_PATH . 'includes/traits/wc-stripe-payment-traits.php' );
13
+
14
+ /**
15
+ *
16
+ * @since 3.0.0
17
+ * @author PaymentPlugins
18
+ * @package Stripe/Abstract
19
+ *
20
+ */
21
+ abstract class WC_Payment_Gateway_Stripe extends WC_Payment_Gateway {
22
+
23
+ use WC_Stripe_Settings_Trait;
24
+
25
+ /**
26
+ *
27
+ * @var WC_Stripe_Payment
28
+ */
29
+ public $payment_object;
30
+
31
+ /**
32
+ * @var bool
33
+ * @since 3.1.8
34
+ */
35
+ protected $has_digital_wallet = false;
36
+
37
+ /**
38
+ *
39
+ * @var string
40
+ */
41
+ public $token_key;
42
+
43
+ /**
44
+ *
45
+ * @var string
46
+ */
47
+ public $saved_method_key;
48
+
49
+ /**
50
+ *
51
+ * @var string
52
+ */
53
+ public $payment_type_key;
54
+
55
+ /**
56
+ *
57
+ * @var string
58
+ */
59
+ public $payment_intent_key;
60
+
61
+ /**
62
+ *
63
+ * @var string
64
+ */
65
+ public $save_source_key;
66
+
67
+ /**
68
+ *
69
+ * @var string
70
+ */
71
+ public $template_name;
72
+
73
+ /**
74
+ *
75
+ * @var bool
76
+ */
77
+ protected $checkout_error = false;
78
+
79
+ /**
80
+ * Used to create an instance of a WC_Payment_Token
81
+ *
82
+ * @var string
83
+ */
84
+ protected $token_type;
85
+
86
+ /**
87
+ *
88
+ * @var WC_Stripe_Gateway
89
+ */
90
+ protected $gateway;
91
+
92
+ /**
93
+ *
94
+ * @var WP_Error
95
+ */
96
+ protected $wp_error;
97
+
98
+ /**
99
+ *
100
+ * @var string
101
+ */
102
+ protected $payment_method_token = null;
103
+
104
+ /**
105
+ *
106
+ * @var string
107
+ */
108
+ protected $new_source_token = null;
109
+
110
+ /**
111
+ * Is the payment method synchronous or asynchronous
112
+ *
113
+ * @var bool
114
+ */
115
+ public $synchronous = true;
116
+
117
+ /**
118
+ *
119
+ * @var array
120
+ */
121
+ protected $post_payment_processes = array();
122
+
123
+ /**
124
+ *
125
+ * @var bool
126
+ */
127
+ public $processing_payment = false;
128
+
129
+ public function __construct() {
130
+ $this->token_key = $this->id . '_token_key';
131
+ $this->saved_method_key = $this->id . '_saved_method_key';
132
+ $this->save_source_key = $this->id . '_save_source_key';
133
+ $this->payment_type_key = $this->id . '_payment_type_key';
134
+ $this->payment_intent_key = $this->id . '_payment_intent_key';
135
+ $this->has_fields = true;
136
+ $this->init_form_fields();
137
+ $this->init_settings();
138
+ $this->title = $this->get_option( 'title_text' );
139
+ $this->description = $this->get_option( 'description' );
140
+ $this->hooks();
141
+ $this->init_supports();
142
+ $this->gateway = WC_Stripe_Gateway::load();
143
+
144
+ $this->payment_object = $this->get_payment_object();
145
+ }
146
+
147
+ public function hooks() {
148
+ add_filter( 'wc_stripe_settings_nav_tabs', array( $this, 'admin_nav_tab' ) );
149
+ add_action( 'woocommerce_settings_checkout_' . $this->id, array( $this, 'enqueue_admin_scripts' ) );
150
+ add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
151
+ add_filter( 'woocommerce_payment_methods_list_item', array( $this, 'payment_methods_list_item' ), 10, 2 );
152
+ add_action( 'wc_stripe_payment_token_deleted_' . $this->id, array( $this, 'delete_payment_method' ), 10, 2 );
153
+ add_filter( 'woocommerce_subscription_payment_meta', array( $this, 'subscription_payment_meta' ), 10, 2 );
154
+ add_action( 'woocommerce_scheduled_subscription_payment_' . $this->id, array( $this, 'scheduled_subscription_payment' ), 10, 2 );
155
+ if ( ! is_admin() ) {
156
+ add_action( 'woocommerce_subscriptions_pre_update_payment_method', array( $this, 'subscriptions_pre_update_payment_method' ), 10, 3 );
157
+ add_action( 'woocommerce_subscription_payment_method_updated_to_' . $this->id, array( $this, 'subscription_payment_method_updated' ) );
158
+ }
159
+ add_action( 'wc_pre_orders_process_pre_order_completion_payment_' . $this->id, array( $this, 'process_pre_order_payment' ) );
160
+
161
+ /**
162
+ * @since 3.1.8
163
+ */
164
+ add_filter( 'wc_stripe_mini_cart_dependencies', array( $this, 'get_mini_cart_dependencies' ), 10, 2 );
165
+ }
166
+
167
+ public function init_supports() {
168
+ $this->supports = array(
169
+ 'tokenization',
170
+ 'products',
171
+ 'subscriptions',
172
+ 'add_payment_method',
173
+ 'subscription_cancellation',
174
+ 'multiple_subscriptions',
175
+ 'subscription_amount_changes',
176
+ 'subscription_date_changes',
177
+ 'default_credit_card_form',
178
+ 'refunds',
179
+ 'pre-orders',
180
+ 'subscription_payment_method_change_admin',
181
+ 'subscription_reactivation',
182
+ 'subscription_suspension',
183
+ 'subscription_payment_method_change_customer',
184
+ );
185
+ }
186
+
187
+ public function init_form_fields() {
188
+ $this->form_fields = include wc_stripe()->plugin_path() . 'includes/gateways/settings/' . str_replace( array( 'stripe_', '_' ), array(
189
+ '',
190
+ '-'
191
+ ), $this->id ) . '-settings.php';
192
+ $this->form_fields = apply_filters( 'wc_stripe_form_fields_' . $this->id, $this->form_fields );
193
+ }
194
+
195
+ public function get_method_formats() {
196
+ $class_name = 'WC_Payment_Token_' . $this->token_type;
197
+ if ( class_exists( $class_name ) ) {
198
+ /**
199
+ *
200
+ * @var WC_Payment_Token_Stripe
201
+ */
202
+ $token = new $class_name();
203
+
204
+ return $token->get_formats();
205
+ }
206
+
207
+ return array();
208
+ }
209
+
210
+ public function enqueue_admin_scripts() {
211
+ }
212
+
213
+ public function payment_fields() {
214
+ $this->enqueue_frontend_scripts();
215
+ wc_stripe_token_field( $this );
216
+ wc_stripe_payment_intent_field( $this );
217
+ $this->output_display_items( 'checkout' );
218
+ wc_stripe_get_template(
219
+ 'checkout/stripe-payment-method.php',
220
+ array(
221
+ 'gateway' => $this,
222
+ 'tokens' => is_add_payment_method_page() ? null : $this->get_tokens(),
223
+ )
224
+ );
225
+ }
226
+
227
+ /**
228
+ * Output the product payment fields.
229
+ */
230
+ public function product_fields() {
231
+ global $product;
232
+ $this->enqueue_frontend_scripts( 'product' );
233
+ $this->output_display_items( 'product' );
234
+ wc_stripe_get_template(
235
+ 'product/' . $this->template_name,
236
+ array(
237
+ 'gateway' => $this,
238
+ 'product' => $product,
239
+ )
240
+ );
241
+ }
242
+
243
+ public function cart_fields() {
244
+ $this->enqueue_frontend_scripts( 'cart' );
245
+ $this->output_display_items( 'cart' );
246
+ wc_stripe_get_template( 'cart/' . $this->template_name, array( 'gateway' => $this ) );
247
+ }
248
+
249
+ public function mini_cart_fields() {
250
+ $this->output_display_items( 'cart' );
251
+ wc_stripe_get_template( 'mini-cart/' . $this->template_name, array( 'gateway' => $this ) );
252
+ }
253
+
254
+ /**
255
+ * Enqueue scripts needed by the gateway on the frontend of the WC shop.
256
+ *
257
+ * @param WC_Stripe_Frontend_Scripts $scripts
258
+ */
259
+ public function enqueue_frontend_scripts( $page = '' ) {
260
+ global $wp;
261
+ if ( $page ) {
262
+ if ( 'product' === $page ) {
263
+ $this->enqueue_product_scripts( wc_stripe()->scripts() );
264
+ } elseif ( 'cart' === $page ) {
265
+ $this->enqueue_cart_scripts( wc_stripe()->scripts() );
266
+ } elseif ( 'checkout' === $page ) {
267
+ $this->enqueue_checkout_scripts( wc_stripe()->scripts() );
268
+ } elseif ( 'mini_cart' === $page ) {
269
+ $this->enqueue_mini_cart_scripts( wc_stripe()->scripts() );
270
+ } else {
271
+ $this->enqueue_frontend_scripts();
272
+ }
273
+ } else {
274
+ if ( is_add_payment_method_page() ) {
275
+ $this->enqueue_add_payment_method_scripts( wc_stripe()->scripts() );
276
+ }
277
+ if ( is_checkout() ) {
278
+ $this->enqueue_checkout_scripts( wc_stripe()->scripts() );
279
+ }
280
+ if ( is_cart() ) {
281
+ $this->enqueue_cart_scripts( wc_stripe()->scripts() );
282
+ }
283
+ if ( is_product() ) {
284
+ $this->enqueue_product_scripts( wc_stripe()->scripts() );
285
+ }
286
+ }
287
+ if ( ! empty( wc_stripe()->scripts()->enqueued_scripts ) ) {
288
+ wp_enqueue_style( wc_stripe()->scripts()->prefix . 'styles', wc_stripe()->assets_url( 'css/stripe.css' ), array(), wc_stripe()->version() );
289
+ }
290
+ }
291
+
292
+ /**
293
+ * Enqueue scripts needed by the gateway on the checkout page.
294
+ *
295
+ * @param WC_Stripe_Frontend_Scripts $scripts
296
+ */
297
+ public function enqueue_checkout_scripts( $scripts ) {
298
+ }
299
+
300
+ /**
301
+ * Enqueue scripts needed by the gateway on the add payment method page.
302
+ *
303
+ * @param WC_Stripe_Frontend_Scripts $scripts
304
+ */
305
+ public function enqueue_add_payment_method_scripts( $scripts ) {
306
+ $this->enqueue_checkout_scripts( $scripts );
307
+ }
308
+
309
+ /**
310
+ * Enqueue scripts needed by the gateway on the cart page.
311
+ *
312
+ * @param WC_Stripe_Frontend_Scripts $scripts
313
+ */
314
+ public function enqueue_cart_scripts( $scripts ) {
315
+ }
316
+
317
+ /**
318
+ * Enqueue scripts needed by the gateway on the product page.
319
+ *
320
+ * @param WC_Stripe_Frontend_Scripts $scripts
321
+ */
322
+ public function enqueue_product_scripts( $scripts ) {
323
+ }
324
+
325
+ /**
326
+ * @param WC_Stripe_Frontend_Scripts $scripts
327
+ *
328
+ * @since 3.1.8
329
+ */
330
+ public function enqueue_mini_cart_scripts( $scripts ) {
331
+ if ( ! wp_script_is( $scripts->get_handle( 'mini-cart' ) ) ) {
332
+ $scripts->enqueue_script( 'mini-cart', $scripts->assets_url( 'js/frontend/mini-cart.js' ), apply_filters( 'wc_stripe_mini_cart_dependencies', array( $scripts->get_handle( 'wc-stripe' ) ), $scripts ) );
333
+ }
334
+ $scripts->localize_script( 'mini-cart', $this->get_localized_params(), 'wc_' . $this->id . '_mini_cart_params' );
335
+ }
336
+
337
+ /**
338
+ *
339
+ * {@inheritDoc}
340
+ *
341
+ * @see WC_Payment_Gateway::process_payment()
342
+ */
343
+ public function process_payment( $order_id ) {
344
+ $order = wc_get_order( $order_id );
345
+
346
+ if ( $this->is_change_payment_method_request() ) {
347
+ return array(
348
+ 'result' => 'success',
349
+ 'redirect' => $order->get_view_order_url(),
350
+ );
351
+ }
352
+
353
+ do_action( 'wc_stripe_before_process_payment', $order, $this->id );
354
+
355
+ if ( wc_notice_count( 'error' ) > 0 ) {
356
+ return $this->get_order_error();
357
+ }
358
+ $this->processing_payment = true;
359
+
360
+ if ( $this->order_contains_pre_order( $order ) && $this->pre_order_requires_tokenization( $order ) ) {
361
+ return $this->process_pre_order( $order );
362
+ }
363
+
364
+ // if order total is zero, then save meta but don't process payment.
365
+ if ( $order->get_total() == 0 ) {
366
+ return $this->process_zero_total_order( $order );
367
+ }
368
+
369
+ $result = $this->payment_object->process_payment( $order, $this );
370
+
371
+ if ( is_wp_error( $result ) ) {
372
+ wc_add_notice( $this->is_active( 'generic_error' ) ? $this->get_generic_error( $result ) : $result->get_error_message(), 'error' );
373
+
374
+ return $this->get_order_error();
375
+ }
376
+
377
+ if ( $result->complete_payment ) {
378
+ $this->payment_object->payment_complete( $order, $result->charge );
379
+ $this->trigger_post_payment_processes( $order, $this );
380
+ WC()->cart->empty_cart();
381
+
382
+ return array(
383
+ 'result' => 'success',
384
+ 'redirect' => $order->get_checkout_order_received_url(),
385
+ );
386
+ } else {
387
+ return array(
388
+ 'result' => 'success',
389
+ 'redirect' => $result->redirect,
390
+ );
391
+ }
392
+ }
393
+
394
+ /**
395
+ *
396
+ * @return array
397
+ */
398
+ public function get_localized_params() {
399
+ return array(
400
+ 'gateway_id' => $this->id,
401
+ 'api_key' => wc_stripe_get_publishable_key(),
402
+ 'saved_method_selector' => '[name="' . $this->saved_method_key . '"]',
403
+ 'token_selector' => '[name="' . $this->token_key . '"]',
404
+ 'messages' => array(
405
+ 'terms' => __( 'Please read and accept the terms and conditions to proceed with your order.', 'woocommerce' ),
406
+ 'required_field' => __( 'Please fill out all required fields.', 'woo-stripe-payment' )
407
+ ),
408
+ 'routes' => array(
409
+ 'setup_intent' => wc_stripe()->rest_api->payment_intent->rest_url( 'setup-intent' ),
410
+ 'sync_intent' => wc_stripe()->rest_api->payment_intent->rest_url( 'sync-payment-intent' ),
411
+ 'add_to_cart' => wc_stripe()->rest_api->cart->rest_url( 'add-to-cart' ),
412
+ 'cart_calculation' => wc_stripe()->rest_api->cart->rest_url( 'cart-calculation' ),
413
+ 'shipping_method' => wc_stripe()->rest_api->cart->rest_url( 'shipping-method' ),
414
+ 'shipping_address' => wc_stripe()->rest_api->cart->rest_url( 'shipping-address' ),
415
+ 'checkout' => wc_stripe()->rest_api->checkout->rest_url( 'checkout' ),
416
+ 'checkout_payment' => wc_stripe()->rest_api->checkout->rest_url( 'checkout/payment' )
417
+ ),
418
+ 'rest_nonce' => wp_create_nonce( 'wp_rest' ),
419
+ 'banner_enabled' => $this->banner_checkout_enabled(),
420
+ 'currency' => get_woocommerce_currency(),
421
+ 'total_label' => __( 'Total', 'woo-stripe-payment' ),
422
+ 'country_code' => wc_get_base_location()['country'],
423
+ 'user_id' => get_current_user_id()
424
+ );
425
+ }
426
+
427
+ /**
428
+ * Save the Stripe data to the order.
429
+ *
430
+ * @param WC_Order $order
431
+ * @param \Stripe\Charge $charge
432
+ */
433
+ public function save_order_meta( $order, $charge ) {
434
+ /**
435
+ *
436
+ * @var WC_Payment_Token_Stripe $token
437
+ */
438
+ $token = $this->get_payment_token( $this->get_payment_method_from_charge( $charge ), $charge->payment_method_details );
439
+ $order->set_transaction_id( $charge->id );
440
+ $order->set_payment_method_title( $token->get_payment_method_title() );
441
+ $order->update_meta_data( WC_Stripe_Constants::MODE, wc_stripe_mode() );
442
+ $order->update_meta_data( WC_Stripe_Constants::CHARGE_STATUS, $charge->status );
443
+ $order->update_meta_data( WC_Stripe_Constants::PAYMENT_METHOD_TOKEN, $token->get_token() );
444
+ $order->save();
445
+
446
+ // if WCS is active and there are subscriptions in the order, save meta data
447
+ if ( wcs_stripe_active() && wcs_order_contains_subscription( $order ) ) {
448
+ foreach ( wcs_get_subscriptions_for_order( $order ) as $subscription ) {
449
+ $subscription->set_transaction_id( $charge->id );
450
+ $subscription->set_payment_method_title( $token->get_payment_method_title() );
451
+ $subscription->update_meta_data( WC_Stripe_Constants::MODE, wc_stripe_mode() );
452
+ $subscription->update_meta_data( WC_Stripe_Constants::CHARGE_STATUS, $charge->status );
453
+ $subscription->update_meta_data( WC_Stripe_Constants::PAYMENT_METHOD_TOKEN, $token->get_token() );
454
+ $subscription->update_meta_data( WC_Stripe_Constants::CUSTOMER_ID, wc_stripe_get_customer_id( $order->get_user_id() ) );
455
+ $subscription->save();
456
+ }
457
+ }
458
+ }
459
+
460
+ /**
461
+ * Given a charge object, return the ID of the payment method used for the charge.
462
+ *
463
+ * @param \Stripe\Charge $charge
464
+ *
465
+ * @since 3.0.6
466
+ */
467
+ public function get_payment_method_from_charge( $charge ) {
468
+ return $this->payment_object->get_payment_method_from_charge( $charge );
469
+ }
470
+
471
+ /**
472
+ *
473
+ * {@inheritDoc}
474
+ *
475
+ * @see WC_Payment_Gateway::add_payment_method()
476
+ */
477
+ public function add_payment_method() {
478
+ $user_id = get_current_user_id();
479
+ try {
480
+ if ( ! is_user_logged_in() ) {
481
+ throw new Exception( __( 'User must be logged in.', 'woo-stripe-payment' ) );
482
+ }
483
+
484
+ $customer_id = wc_stripe_get_customer_id( $user_id );
485
+
486
+ if ( empty( $customer_id ) ) {
487
+ $customer_id = $this->create_customer( $user_id );
488
+ }
489
+
490
+ $result = $this->create_payment_method( $this->get_new_source_token(), $customer_id );
491
+
492
+ if ( is_wp_error( $result ) ) {
493
+ wc_add_notice( sprintf( __( 'Error saving your payment method. Reason: %s', 'woo-stripe-payment' ), $result->get_error_message() ), 'error' );
494
+
495
+ return array( 'result' => 'error' );
496
+ }
497
+ $result->set_user_id( $user_id );
498
+ $result->save();
499
+ WC_Payment_Tokens::set_users_default( $user_id, $result->get_id() );
500
+
501
+ do_action( 'wc_stripe_add_payment_method_success', $result );
502
+
503
+ return array(
504
+ 'result' => 'success',
505
+ 'redirect' => wc_get_account_endpoint_url( 'payment-methods' ),
506
+ );
507
+ } catch ( \Stripe\Error\Base $e ) {
508
+ wc_add_notice( sprintf( __( 'Error saving payment method. Reason: %s', 'woo-stripe-payment' ), $e->getMessage() ), 'error' );
509
+
510
+ return array( 'result' => 'error' );
511
+ }
512
+ }
513
+
514
+ /**
515
+ *
516
+ * {@inheritDoc}
517
+ *
518
+ * @see WC_Payment_Gateway::process_refund()
519
+ */
520
+ public function process_refund( $order_id, $amount = null, $reason = '' ) {
521
+ $order = wc_get_order( $order_id );
522
+ $result = $this->payment_object->process_refund( $order, $amount );
523
+
524
+ if ( ! is_wp_error( $result ) ) {
525
+ $order->add_order_note(
526
+ sprintf(
527
+ __( 'Order refunded in Stripe. Amount: %s', 'woo-stripe-payment' ),
528
+ wc_price(
529
+ $amount,
530
+ array(
531
+ 'currency' => $order->get_currency(),
532
+ )
533
+ )
534
+ )
535
+ );
536
+ }
537
+
538
+ return $result;
539
+ }
540
+
541
+ /**
542
+ * Captures the charge for the Stripe order.
543
+ *
544
+ * @param float $amount
545
+ * @param WC_Order $order
546
+ */
547
+ public function capture_charge( $amount, $order ) {
548
+ $result = $this->gateway->charges->mode( wc_stripe_order_mode( $order ) )->retrieve( $order->get_transaction_id() );
549
+
550
+ if ( is_wp_error( $result ) ) {
551
+ return;
552
+ } else {
553
+ if ( ! $result->captured ) {
554
+ $result = $this->payment_object->capture_charge( $amount, $order );
555
+
556
+ if ( ! is_wp_error( $result ) ) {
557
+ remove_action( 'woocommerce_order_status_completed', 'wc_stripe_order_status_completed' );
558
+ $order->payment_complete();
559
+ if ( $amount != $order->get_total() ) {
560
+ $order->set_total( $amount );
561
+ $order->save();
562
+ }
563
+ $order->add_order_note(
564
+ sprintf(
565
+ __( 'Order amount captured in Stripe. Amount: %s', 'woo-stripe-payment' ),
566
+ wc_price(
567
+ $amount,
568
+ array(
569
+ 'currency' => $order->get_currency(),
570
+ )
571
+ )
572
+ )
573
+ );
574
+ } else {
575
+ $order->add_order_note( sprintf( __( 'Error capturing charge in Stripe. Reason: %s', 'woo-stripe-payment' ), $result->get_error_message() ) );
576
+ }
577
+ }
578
+ }
579
+
580
+ return $result;
581
+ }
582
+
583
+ /**
584
+ * Void the Stripe charge.
585
+ *
586
+ * @param WC_Order $order
587
+ */
588
+ public function void_charge( $order ) {
589
+ // @3.1.1 - check added so errors aren't encountered if the order can't be voided
590
+ if ( ! $this->payment_object->can_void_order( $order ) ) {
591
+ return;
592
+ }
593
+ $result = $this->payment_object->void_charge( $order );
594
+
595
+ if ( is_wp_error( $result ) ) {
596
+ $order->add_order_note( sprintf( __( 'Error voiding charge. Reason: %s', 'woo-stripe-payment' ), $result->get_error_message() ) );
597
+ } else {
598
+ $order->add_order_note( __( 'Charge voided in Stripe.', 'woo-stripe-payment' ) );
599
+ }
600
+ }
601
+
602
+ /**
603
+ * Return the \Stripe\Charge object
604
+ *
605
+ * @param String $charge_id
606
+ * @param String $mode
607
+ *
608
+ * @return WP_Error|\Stripe\Charge
609
+ */
610
+ public function retrieve_charge( $charge_id, $mode = '' ) {
611
+ return $this->gateway->charges->mode( $mode )->retrieve( $charge_id );
612
+ }
613
+
614
+ /**
615
+ *
616
+ * @param string $method_id
617
+ * @param \Stripe\Card|array $method_details
618
+ */
619
+ public function get_payment_token( $method_id, $method_details = null ) {
620
+ $class_name = 'WC_Payment_Token_' . $this->token_type;
621
+ if ( class_exists( $class_name ) ) {
622
+ /**
623
+ *
624
+ * @var WC_Payment_Token_Stripe $token
625
+ */
626
+ $token = new $class_name( '', $method_details );
627
+ $token->set_token( $method_id );
628
+ $token->set_gateway_id( $this->id );
629
+ $token->set_format( $this->get_option( 'method_format' ) );
630
+ $token->set_environment( wc_stripe_mode() );
631
+ if ( $method_details ) {
632
+ $token->details_to_props( $method_details );
633
+ }
634
+
635
+ return $token;
636
+ }
637
+ }
638
+
639
+ /**
640
+ * Return a failed order response.
641
+ *
642
+ * @return array
643
+ */
644
+ public function get_order_error() {
645
+ wc_stripe_set_checkout_error();
646
+
647
+ return array( 'result' => WC_Stripe_Constants::FAILURE );
648
+ }
649
+
650
+ /**
651
+ * Return the payment source the customer has chosen to use.
652
+ * This can be a saved source
653
+ * or a one time use source.
654
+ */
655
+ public function get_payment_source() {
656
+ if ( $this->use_saved_source() ) {
657
+ return $this->get_saved_source_id();
658
+ } else {
659
+ if ( $this->payment_method_token ) {
660
+ return $this->payment_method_token;
661
+ }
662
+
663
+ return $this->get_new_source_token();
664
+ }
665
+ }
666
+
667
+ /**
668
+ * Returns the payment method the customer wants to use.
669
+ * This can be a saved payment method
670
+ * or a new payment method.
671
+ */
672
+ public function get_payment_method_from_request() {
673
+ return $this->get_payment_source();
674
+ }
675
+
676
+ public function get_payment_intent_id() {
677
+ return ! empty( $_POST[ $this->payment_intent_key ] ) ? $_POST[ $this->payment_intent_key ] : '';
678
+ }
679
+
680
+ /**
681
+ * Return true of the customer is using a saved payment method.
682
+ */
683
+ public function use_saved_source() {
684
+ return ( ! empty( $_POST[ $this->payment_type_key ] ) && $_POST[ $this->payment_type_key ] === 'saved' ) || $this->payment_method_token;
685
+ }
686
+
687
+ /**
688
+ *
689
+ * @deprecated
690
+ *
691
+ */
692
+ public function get_new_source_id() {
693
+ return $this->get_new_source_token();
694
+ }
695
+
696
+ public function get_new_source_token() {
697
+ return null != $this->new_source_token ? $this->new_source_token : ( ! empty( $_POST[ $this->token_key ] ) ? $_POST[ $this->token_key ] : '' );
698
+ }
699
+
700
+ public function get_saved_source_id() {
701
+ return ! empty( $_POST[ $this->saved_method_key ] ) ? $_POST[ $this->saved_method_key ] : $this->payment_method_token;
702
+ }
703
+
704
+ /**
705
+ * Create a customer in the stripe gateway.
706
+ *
707
+ * @param int $user_id
708
+ */
709
+ public function create_customer( $user_id ) {
710
+ $customer = WC()->customer;
711
+ $response = $this->gateway->customers->create(
712
+ apply_filters( 'wc_stripe_customer_args', array(
713
+ 'email' => $customer->get_email(),
714
+ 'name' => sprintf( '%s %s', $customer->get_first_name(), $customer->get_last_name() ),
715
+ 'phone' => $customer->get_billing_phone(),
716
+ 'metadata' => array(
717
+ 'user_id' => $customer->get_id(),
718
+ 'username' => $customer->get_username(),
719
+ 'website' => get_site_url(),
720
+ ),
721
+ ) )
722
+ );
723
+ if ( ! is_wp_error( $response ) ) {
724
+ wc_stripe_save_customer( $response->id, $user_id );
725
+ }
726
+
727
+ return $customer;
728
+ }
729
+
730
+ /**
731
+ * Creates a payment method in Stripe.
732
+ *
733
+ * @param string $id
734
+ * payment method id
735
+ * @param string $customer_id
736
+ * WC Stripe customer ID
737
+ *
738
+ * @return WC_Payment_Token_Stripe|WP_Error
739
+ */
740
+ public function create_payment_method( $id, $customer_id ) {
741
+ $token = $this->get_payment_token( $id );
742
+ $token->set_customer_id( $customer_id );
743
+
744
+ $result = $token->save_payment_method();
745
+
746
+ if ( is_wp_error( $result ) ) {
747
+ return $result;
748
+ } else {
749
+ $token->set_token( $result->id );
750
+ $token->details_to_props( $result );
751
+
752
+ return $token;
753
+ }
754
+ }
755
+
756
+ /**
757
+ *
758
+ * @param array $item
759
+ * @param WC_Payment_Token_Stripe_CC $payment_token
760
+ */
761
+ public function payment_methods_list_item( $item, $payment_token ) {
762
+ if ( $payment_token->get_type() === $this->token_type ) {
763
+ $item['method']['last4'] = $payment_token->get_last4();
764
+ $item['method']['brand'] = ucfirst( $payment_token->get_brand() );
765
+ if ( $payment_token->has_expiration() ) {
766
+ $item['expires'] = sprintf( '%s / %s', $payment_token->get_exp_month(), $payment_token->get_exp_year() );
767
+ } else {
768
+ $item['expires'] = __( 'n/a', 'woo-stripe-payment' );
769
+ }
770
+ $item['wc_stripe_method'] = true;
771
+ }
772
+
773
+ return $item;
774
+ }
775
+
776
+ /**
777
+ *
778
+ * @param string $token_id
779
+ * @param WC_Payment_Token_Stripe $token
780
+ */
781
+ public function delete_payment_method( $token_id, $token ) {
782
+ $token->delete_from_stripe();
783
+ }
784
+
785
+ public function saved_payment_methods( $tokens = array() ) {
786
+ wc_stripe_get_template(
787
+ 'payment-methods.php',
788
+ array(
789
+ 'tokens' => $tokens,
790
+ 'gateway' => $this,
791
+ )
792
+ );
793
+ }
794
+
795
+ public function get_new_method_label() {
796
+ return __( 'New Card', 'woo-stripe-payment' );
797
+ }
798
+
799
+ public function get_saved_methods_label() {
800
+ return __( 'Saved Cards', 'woo-stripe-payment' );
801
+ }
802
+
803
+ /**
804
+ * Return true if shipping is needed.
805
+ * Shipping is based on things like if the cart or product needs shipping.
806
+ *
807
+ * @return bool
808
+ */
809
+ public function get_needs_shipping() {
810
+ if ( is_checkout() || is_cart() ) {
811
+ global $wp;
812
+ if ( wcs_stripe_active() && WC_Subscriptions_Change_Payment_Gateway::$is_request_to_change_payment ) {
813
+ return false;
814
+ }
815
+ // return false if this is the order pay page. Gateways that have payment sheets don't need
816
+ // to make any changes to the order.
817
+ if ( ! empty( $wp->query_vars['order-pay'] ) ) {
818
+ return false;
819
+ }
820
+
821
+ return WC()->cart->needs_shipping();
822
+ }
823
+ if ( is_product() ) {
824
+ global $product;
825
+
826
+ return is_a( $product, 'WC_Product' ) && $product->needs_shipping();
827
+ }
828
+ }
829
+
830
+ /**
831
+ * Return true of the payment method should be saved.
832
+ *
833
+ * @param WC_Order $order
834
+ *
835
+ * @return bool
836
+ */
837
+ public function should_save_payment_method( $order ) {
838
+ if ( ! $this->use_saved_source() && ! $this->is_processing_scheduled_payment() ) {
839
+ if ( wcs_stripe_active() && $this->supports( 'subscriptions' ) ) {
840
+ if ( wcs_order_contains_subscription( $order ) ) {
841
+ return true;
842
+ }
843
+ if ( wcs_order_contains_renewal( $order ) ) {
844
+ return true;
845
+ }
846
+ }
847
+ if ( ! empty( $_POST[ $this->save_source_key ] ) ) {
848
+ return true;
849
+ }
850
+ }
851
+
852
+ return false;
853
+ }
854
+
855
+ /**
856
+ * Returns true if the save payment method checkbox can be displayed.
857
+ *
858
+ * @return boolean
859
+ */
860
+ public function show_save_source() {
861
+ $page = wc_stripe_get_current_page();
862
+
863
+ if ( 'checkout' === $page ) {
864
+ if ( wcs_stripe_active() ) {
865
+ if ( WC_Subscriptions_Cart::cart_contains_subscription() ) {
866
+ return false;
867
+ }
868
+ if ( wcs_cart_contains_renewal() ) {
869
+ return false;
870
+ }
871
+ }
872
+ // @since 3.1.5
873
+ if ( wc_stripe_pre_orders_active() && WC_Pre_Orders_Cart::cart_contains_pre_order() ) {
874
+ return ! WC_Pre_Orders_Product::product_is_charged_upon_release( WC_Pre_Orders_Cart::get_pre_order_product() );
875
+ }
876
+
877
+ return is_user_logged_in() && $this->is_active( 'save_card_enabled' );
878
+ } elseif ( in_array( $page, array( 'add_payment_method', 'change_payment_method' ) ) ) {
879
+ return false;
880
+ } elseif ( 'order_pay' === $page ) {
881
+ return is_user_logged_in() && $this->is_active( 'save_card_enabled' );
882
+ }
883
+ }
884
+
885
+ /**
886
+ * Returns a formatted array of items for display in the payment gateway's payment sheet.
887
+ *
888
+ * @param stirng $page
889
+ *
890
+ * @return []
891
+ */
892
+ public function get_display_items( $page = 'checkout', $order = null ) {
893
+ global $wp;
894
+ $items = array();
895
+ if ( in_array( $page, array( 'cart', 'checkout' ) ) ) {
896
+ $items = $this->get_display_items_for_cart( WC()->cart );
897
+ } elseif ( 'order_pay' === $page ) {
898
+ $order = ! is_null( $order ) ? $order : wc_get_order( absint( $wp->query_vars['order-pay'] ) );
899
+ $items = $this->get_display_items_for_order( $order );
900
+ } elseif ( 'product' === $page ) {
901
+ global $product;
902
+ $items = array( $this->get_display_item_for_product( $product ) );
903
+ }
904
+
905
+ /**
906
+ * @param array $items
907
+ * @param WC_Order|null $order
908
+ * @param string $page
909
+ */
910
+ return apply_filters( 'wc_stripe_get_display_items', $items, $order, $page );
911
+ }
912
+
913
+ /**
914
+ * Returns a formatted array of shipping methods for display in the payment gateway's
915
+ * payment sheet.
916
+ *
917
+ * @param bool $encode
918
+ *
919
+ * @return array
920
+ * @deprecated
921
+ */
922
+ public function get_shipping_methods() {
923
+ return $this->get_formatted_shipping_methods();
924
+ }
925
+
926
+ /**
927
+ * Return true if product page checkout is enabled for this gateway
928
+ *
929
+ * @return bool
930
+ */
931
+ public function product_checkout_enabled() {
932
+ return in_array( 'product', $this->get_option( 'payment_sections', array() ) );
933
+ }
934
+
935
+ /**
936
+ * Return true if cart page checkout is enabled for this gateway
937
+ *
938
+ * @return bool
939
+ */
940
+ public function cart_checkout_enabled() {
941
+ return in_array( 'cart', $this->get_option( 'payment_sections', array() ) );
942
+ }
943
+
944
+ /**
945
+ * Return true if mini-cart checkout is enabled for this gateway
946
+ *
947
+ * @return bool
948
+ * @since 3.1.8
949
+ */
950
+ public function mini_cart_enabled() {
951
+ return in_array( 'mini_cart', $this->get_option( 'payment_sections', array() ) );
952
+ }
953
+
954
+ /**
955
+ * Return true if checkout page banner is enabled for this gateway
956
+ *
957
+ * @return bool
958
+ */
959
+ public function banner_checkout_enabled() {
960
+ global $wp;
961
+
962
+ return empty( $wp->query_vars['order-pay'] ) && $this->supports( 'wc_stripe_banner_checkout' ) &&
963
+ in_array( 'checkout_banner', $this->get_option( 'payment_sections', array() ) );
964
+ }
965
+
966
+ /**
967
+ * Decorate the response with data specific to the gateway.
968
+ *
969
+ * @param [] $data
970
+ */
971
+ public function add_to_cart_response( $data ) {
972
+ return $data;
973
+ }
974
+
975
+ /**
976
+ * Decorate the update shipping method reponse with data.
977
+ *
978
+ * @param [] $data
979
+ */
980
+ public function get_update_shipping_method_response( $data ) {
981
+ return $data;
982
+ }
983
+
984
+ /**
985
+ * Decorate the update shipping address respond with data.
986
+ *
987
+ * @param [] $data
988
+ */
989
+ public function get_update_shipping_address_response( $data ) {
990
+ return apply_filters( 'wc_stripe_update_shipping_address_response', $data );
991
+ }
992
+
993
+ /**
994
+ * Save the customer's payment method.
995
+ * If the payment method has already been saved to the customer
996
+ * then simply return true.
997
+ *
998
+ * @param string $id
999
+ * @param WC_Order $order
1000
+ *
1001
+ * @return WP_Error|bool
1002
+ */
1003
+ public function save_payment_method( $id, $order ) {
1004
+ $token = $this->create_payment_method( $id, wc_stripe_get_customer_id( $order->get_user_id() ) );
1005
+ if ( is_wp_error( $token ) ) {
1006
+ $this->wp_error = $token;
1007
+ $order->add_order_note( sprintf( __( 'Attemp to save payment method failed. Reason: %s', 'woo-stripe-payment' ), $token->get_error_message() ) );
1008
+
1009
+ return $token;
1010
+ }
1011
+ $token->set_user_id( $order->get_user_id() );
1012
+ $token->save();
1013
+
1014
+ // set token value so it can be used for other processes.
1015
+ $this->payment_method_token = $token->get_token();
1016
+
1017
+ return true;
1018
+ }
1019
+
1020
+ /**
1021
+ * Set an error on the order.
1022
+ * This error is used on the frontend to alert customer's to a failed payment method save.
1023
+ *
1024
+ * @param WC_Order $order
1025
+ * @param WP_Error $error
1026
+ */
1027
+ public function set_payment_save_error( $order, $error ) {
1028
+ if ( wcs_stripe_active() && wcs_order_contains_subscription( $order ) ) {
1029
+ $message = __( 'We were not able to save your payment method. To prevent billing issues with your subscription, please add a payment method to the subscription.', 'woo-stripe-payment' );
1030
+ } else {
1031
+ $message = sprintf( __( 'We were not able to save your payment method. Reason: %s', 'woo-stripe-payment' ), $error->get_error_message() );
1032
+ }
1033
+ $order->update_meta_data( '_wc_stripe_order_error', $message );
1034
+ $order->save();
1035
+ }
1036
+
1037
+ /**
1038
+ *
1039
+ * @param string $token_id
1040
+ * @param int $user_id
1041
+ *
1042
+ * @return null|WC_Payment_Token_Stripe_CC
1043
+ */
1044
+ public function get_token( $token_id, $user_id ) {
1045
+ $tokens = WC_Payment_Tokens::get_tokens( array( 'user_id' => $user_id, 'gateway_id' => $this->id, 'limit' => 20 ) );
1046
+ foreach ( $tokens as $token ) {
1047
+ if ( $token_id === $token->get_token() ) {
1048
+ return $token;
1049
+ }
1050
+ }
1051
+
1052
+ return null;
1053
+ }
1054
+
1055
+ /**
1056
+ *
1057
+ * @param array $payment_meta
1058
+ * @param WC_Subscription $subscription
1059
+ */
1060
+ public function subscription_payment_meta( $payment_meta, $subscription ) {
1061
+ $payment_meta[ $this->id ] = array(
1062
+ 'post_meta' => array(
1063
+ WC_Stripe_Constants::PAYMENT_METHOD_TOKEN => array(
1064
+ 'value' => $this->get_order_meta_data( WC_Stripe_Constants::PAYMENT_METHOD_TOKEN, $subscription ),
1065
+ 'label' => __( 'Payment Method Token', 'woo-stripe-payment' ),
1066
+ ),
1067
+ ),
1068
+ );
1069
+
1070
+ return $payment_meta;
1071
+ }
1072
+
1073
+ /**
1074
+ *
1075
+ * @param float $amount
1076
+ * @param WC_Order $order
1077
+ */
1078
+ public function scheduled_subscription_payment( $amount, $order ) {
1079
+ $this->processing_payment = true;
1080
+
1081
+ $result = $this->payment_object->scheduled_subscription_payment( $amount, $order );
1082
+
1083
+ if ( is_wp_error( $result ) ) {
1084
+ $order->update_status( 'failed' );
1085
+ $order->add_order_note( sprintf( __( 'Recurring payment for order failed. Reason: %s', 'woo-stripe-payment' ), $result->get_error_message() ) );
1086
+
1087
+ return;
1088
+ }
1089
+
1090
+ $this->save_order_meta( $order, $result->charge );
1091
+
1092
+ // set the payment method token that was used to process the renewal order.
1093
+ $this->payment_method_token = $order->get_meta( WC_Stripe_Constants::PAYMENT_METHOD_TOKEN );
1094
+
1095
+ if ( $result->complete_payment ) {
1096
+ if ( $result->charge->captured ) {
1097
+ $order->payment_complete( $result->charge->id );
1098
+ $order->add_order_note( sprintf( __( 'Recurring payment captured in Stripe. Payment method: %s', 'woo-stripe-payment' ), $order->get_payment_method_title() ) );
1099
+ } else {
1100
+ $order->update_status( apply_filters( 'wc_stripe_authorized_renewal_order_status', 'on-hold', $order, $this ), sprintf( __( 'Recurring payment authorized in Stripe. Payment method: %s', 'woo-stripe-payment' ), $order->get_payment_method_title() ) );
1101
+ }
1102
+ } else {
1103
+ $order->update_status( 'pending', sprintf( __( 'Customer must manually complete payment for payment method %s', 'woo-stripe-payment' ), $order->get_payment_method_title() ) );
1104
+ }
1105
+ }
1106
+
1107
+ /**
1108
+ *
1109
+ * @param WC_Subscription $subscription
1110
+ * @param string $new_payment_method
1111
+ * @param string $old_payment_method
1112
+ */
1113
+ public function subscriptions_pre_update_payment_method( $subscription, $new_payment_method, $old_payment_method ) {
1114
+ if ( $new_payment_method === $this->id ) {
1115
+ // customer is using a new payment method so we need to save it.
1116
+ if ( ! $this->use_saved_source() ) {
1117
+ $result = $this->save_payment_method( $this->get_new_source_token(), $subscription );
1118
+ if ( is_wp_error( $result ) ) {
1119
+ wc_add_notice( sprintf( __( 'Error saving payment method for subscription. Reason: %s', 'woo-stripe-payment' ), $result->get_error_message() ), 'error' );
1120
+ // redirect to change payment method page.
1121
+ wp_safe_redirect( $subscription->get_view_order_url() );
1122
+ exit();
1123
+ }
1124
+ } else {
1125
+ if ( ! $this->payment_method_token ) {
1126
+ // set the payment method token so it can be used downstream.
1127
+ $this->payment_method_token = $this->get_payment_source();
1128
+ }
1129
+ }
1130
+ }
1131
+ }
1132
+
1133
+ /**
1134
+ * Update the subscription with the new meta data for the gateway.
1135
+ * Save any new method the customer is trying to use.
1136
+ *
1137
+ * @param WC_Subscription $subscription
1138
+ */
1139
+ public function subscription_payment_method_updated( $subscription ) {
1140
+ $token = $this->get_token( $this->payment_method_token, $subscription->get_user_id() );
1141
+
1142
+ // update the meta data needed by the gateway to process a subscription payment.
1143
+ $subscription->update_meta_data( WC_Stripe_Constants::PAYMENT_METHOD_TOKEN, $this->payment_method_token );
1144
+ if ( $token ) {
1145
+ $subscription->set_payment_method_title( $token->get_payment_method_title() );
1146
+ }
1147
+ $subscription->save();
1148
+ }
1149
+
1150
+ /**
1151
+ * Return true if this request is to change the payment method of a WC Subscription.
1152
+ *
1153
+ * @return bool
1154
+ */
1155
+ public function is_change_payment_method_request() {
1156
+ return wcs_stripe_active() && did_action( 'woocommerce_subscriptions_pre_update_payment_method' );
1157
+ }
1158
+
1159
+ /**
1160
+ * Sets the ID of a payment token.
1161
+ *
1162
+ * @param string $id
1163
+ */
1164
+ public function set_payment_method_token( $id ) {
1165
+ $this->payment_method_token = $id;
1166
+ }
1167
+
1168
+ public function set_new_source_token( $token ) {
1169
+ $this->new_source_token = $token;
1170
+ }
1171
+
1172
+ /**
1173
+ *
1174
+ * @param WC_Order $order
1175
+ *
1176
+ * @deprecated
1177
+ *
1178
+ */
1179
+ public function get_order_description( $order ) {
1180
+ return sprintf( __( 'Order %1$s from %2$s', 'woo-stripe-payment' ), $order->get_order_number(), get_bloginfo( 'name' ) );
1181
+ }
1182
+
1183
+ /**
1184
+ *
1185
+ * @param WC_Order $order
1186
+ */
1187
+ public function process_zero_total_order( $order ) {
1188
+ // save payment method if necessary
1189
+ if ( $this->should_save_payment_method( $order ) ) {
1190
+ $result = $this->save_payment_method( $this->get_new_source_token(), $order );
1191
+ if ( is_wp_error( $result ) ) {
1192
+ wc_add_notice( $result->get_error_message(), 'error' );
1193
+
1194
+ return $this->get_order_error();
1195
+ }
1196
+ } else {
1197
+ $this->payment_method_token = $this->get_saved_source_id();
1198
+ }
1199
+ $this->save_zero_total_meta( $order );
1200
+ $order_status = $this->get_option( 'order_status' );
1201
+ if ( 'capture' === $this->get_option( 'charge_type' ) ) {
1202
+ $order->payment_complete();
1203
+ } else {
1204
+ $order_status = $this->get_option( 'order_status' );
1205
+ $order->update_status( apply_filters( 'wc_stripe_authorized_order_status', 'default' === $order_status ? 'on-hold' : $order_status, $order, $this ) );
1206
+ }
1207
+ WC()->cart->empty_cart();
1208
+
1209
+ return array(
1210
+ 'result' => 'success',
1211
+ 'redirect' => $order->get_checkout_order_received_url(),
1212
+ );
1213
+ }
1214
+
1215
+ public function process_pre_order( $order ) {
1216
+ // maybe save payment method
1217
+ if ( ! $this->use_saved_source() ) {
1218
+ $result = $this->save_payment_method( $this->get_new_source_token(), $order );
1219
+ if ( is_wp_error( $result ) ) {
1220
+ wc_add_notice( $result->get_error_message(), 'error' );
1221
+
1222
+ return $this->get_order_error();
1223
+ }
1224
+ } else {
1225
+ $this->payment_method_token = $this->get_saved_source_id();
1226
+ }
1227
+ WC_Pre_Orders_Order::mark_order_as_pre_ordered( $order );
1228
+ $this->save_zero_total_meta( $order );
1229
+
1230
+ return array(
1231
+ 'result' => 'success',
1232
+ 'redirect' => $order->get_checkout_order_received_url(),
1233
+ );
1234
+ }
1235
+
1236
+ /**
1237
+ *
1238
+ * @param WC_Order $order
1239
+ */
1240
+ protected function save_zero_total_meta( $order ) {
1241
+ $token = $this->get_token( $this->payment_method_token, $order->get_user_id() );
1242
+ $order->set_payment_method_title( $token->get_payment_method_title() );
1243
+ $order->update_meta_data( WC_Stripe_Constants::MODE, wc_stripe_mode() );
1244
+ $order->update_meta_data( WC_Stripe_Constants::PAYMENT_METHOD_TOKEN, $token->get_token() );
1245
+ $order->update_meta_data( WC_Stripe_Constants::CUSTOMER_ID, wc_stripe_get_customer_id( $order->get_user_id() ) );
1246
+ $order->save();
1247
+
1248
+ if ( wcs_stripe_active() && wcs_order_contains_subscription( $order ) ) {
1249
+ foreach ( wcs_get_subscriptions_for_order( $order ) as $subscription ) {
1250
+ /**
1251
+ *
1252
+ * @var WC_Subscription $subscription
1253
+ */
1254
+ $subscription->set_payment_method_title( $token->get_payment_method_title() );
1255
+ $subscription->update_meta_data( WC_Stripe_Constants::MODE, wc_stripe_mode() );
1256
+ $subscription->update_meta_data( WC_Stripe_Constants::PAYMENT_METHOD_TOKEN, $token->get_token() );
1257
+ $subscription->update_meta_data( WC_Stripe_Constants::CUSTOMER_ID, wc_stripe_get_customer_id( $order->get_user_id() ) );
1258
+ $subscription->save();
1259
+ }
1260
+ }
1261
+ }
1262
+
1263
+ /**
1264
+ * Pre orders can't be mixed with regular products.
1265
+ *
1266
+ * @param WC_Order $order
1267
+ */
1268
+ protected function order_contains_pre_order( $order ) {
1269
+ return wc_stripe_pre_orders_active() && WC_Pre_Orders_Order::order_contains_pre_order( $order );
1270
+ }
1271
+
1272
+ /**
1273
+ *
1274
+ * @param WC_Order $order
1275
+ *
1276
+ * @return boolean
1277
+ */
1278
+ protected function pre_order_requires_tokenization( $order ) {
1279
+ return WC_Pre_Orders_Order::order_requires_payment_tokenization( $order );
1280
+ }
1281
+
1282
+ /**
1283
+ * Sets a lock on the order.
1284
+ * Default behavior is a 2 minute lock.
1285
+ *
1286
+ * @param WC_Order|int $order
1287
+ */
1288
+ public function set_order_lock( $order ) {
1289
+ $order_id = ( is_object( $order ) ? $order->get_id() : $order );
1290
+ set_transient( 'stripe_lock_order_' . $order_id, $order_id, apply_filters( 'wc_stripe_set_order_lock', 2 * MINUTE_IN_SECONDS ) );
1291
+ }
1292
+
1293
+ /**
1294
+ * Removes the lock on the order
1295
+ *
1296
+ * @param WC_Order|int $order
1297
+ */
1298
+ public function release_order_lock( $order ) {
1299
+ delete_transient( 'stripe_lock_order_' . ( is_object( $order ) ? $order->get_id() : $order ) );
1300
+ }
1301
+
1302
+ /**
1303
+ * Returns true of the order has been locked.
1304
+ * If the lock exists and is greater than current time
1305
+ * method returns true;
1306
+ *
1307
+ * @param WC_Order|int $order
1308
+ */
1309
+ public function has_order_lock( $order ) {
1310
+ $lock = get_transient( 'stripe_lock_order_' . ( is_object( $order ) ? $order->get_id() : $order ) );
1311
+
1312
+ return $lock !== false;
1313
+ }
1314
+
1315
+ public function set_post_payment_process( $callback ) {
1316
+ $this->post_payment_processes[] = $callback;
1317
+ }
1318
+
1319
+ /**
1320
+ *
1321
+ * @param WC_Order $order
1322
+ * @param WC_Payment_Gateway_Stripe $gateway
1323
+ */
1324
+ public function trigger_post_payment_processes( $order, $gateway ) {
1325
+ foreach ( $this->post_payment_processes as $callback ) {
1326
+ call_user_func_array( $callback, func_get_args() );
1327
+ }
1328
+ }
1329
+
1330
+ public function validate_payment_sections_field( $key, $value ) {
1331
+ if ( empty( $value ) ) {
1332
+ $value = array();
1333
+ }
1334
+
1335
+ return $value;
1336
+ }
1337
+
1338
+ /**
1339
+ *
1340
+ * @param WC_Order $order
1341
+ */
1342
+ public function process_pre_order_payment( $order ) {
1343
+ $this->processing_payment = true;
1344
+
1345
+ $result = $this->payment_object->process_pre_order_payment( $order );
1346
+
1347
+ if ( is_wp_error( $result ) ) {
1348
+ $order->update_status( 'failed' );
1349
+ $order->add_order_note( sprintf( __( 'Pre-order payment for order failed. Reason: %s', 'woo-stripe-payment' ), $result->get_error_message() ) );
1350
+ } else {
1351
+ if ( $result->complete_payment ) {
1352
+
1353
+ $this->save_order_meta( $order, $result->charge );
1354
+
1355
+ if ( $result->charge->captured ) {
1356
+ $order->payment_complete( $result->charge->id );
1357
+ $order->add_order_note( sprintf( __( 'Pre-order payment captured in Stripe. Payment method: %s', 'woo-stripe-payment' ), $order->get_payment_method_title() ) );
1358
+ } else {
1359
+ $order->update_status( apply_filters( 'wc_stripe_authorized_preorder_order_status', 'on-hold', $order, $this ), sprintf( __( 'Pre-order payment authorized in Stripe. Payment method: %s', 'woo-stripe-payment' ), $order->get_payment_method_title() ) );
1360
+ }
1361
+ } else {
1362
+ $order->update_status( 'pending', sprintf( __( 'Customer must manually complete payment for payment method %s', 'woo-stripe-payment' ), $order->get_payment_method_title() ) );
1363
+ }
1364
+ }
1365
+ }
1366
+
1367
+ /**
1368
+ * Given a meta key, see if there is a value for that key in another plugin.
1369
+ * This acts as a lazy conversion
1370
+ * method for merchants that have switched to our plugin from other plugins.
1371
+ *
1372
+ * @param string $meta_key
1373
+ * @param WC_Order $order
1374
+ * @param string $context
1375
+ *
1376
+ * @since 3.1.0
1377
+ */
1378
+ public function get_order_meta_data( $meta_key, $order, $context = 'view' ) {
1379
+ $value = $order->get_meta( $meta_key, true, $context );
1380
+ // value is empty so check metadata from other plugins
1381
+ if ( empty( $value ) ) {
1382
+ $keys = array();
1383
+ switch ( $meta_key ) {
1384
+ case WC_Stripe_Constants::PAYMENT_METHOD_TOKEN:
1385
+ $keys = array( WC_Stripe_Constants::SOURCE_ID );
1386
+ break;
1387
+ case WC_Stripe_Constants::CUSTOMER_ID:
1388
+ $keys = array( WC_Stripe_Constants::STRIPE_CUSTOMER_ID );
1389
+ break;
1390
+ case WC_Stripe_Constants::PAYMENT_INTENT_ID:
1391
+ $keys = array( WC_Stripe_Constants::STRIPE_INTENT_ID );
1392
+ }
1393
+ if ( $keys ) {
1394
+ $meta_data = $order->get_meta_data();
1395
+ if ( $meta_data ) {
1396
+ $keys = array_intersect( wp_list_pluck( $meta_data, 'key' ), $keys );
1397
+ $array_keys = array_keys( $keys );
1398
+ if ( ! empty( $array_keys ) ) {
1399
+ $value = $meta_data[ current( $array_keys ) ]->value;
1400
+ update_post_meta( $order->get_id(), $meta_key, $value );
1401
+ }
1402
+ }
1403
+ }
1404
+ }
1405
+
1406
+ return $value;
1407
+ }
1408
+
1409
+ /**
1410
+ * Gateways can override this method to add attributes to the Stripe object before it's
1411
+ * sent to Stripe.
1412
+ *
1413
+ * @param array $args
1414
+ * @param WC_Order $order
1415
+ */
1416
+ public function add_stripe_order_args( &$args, $order ) {
1417
+ }
1418
+
1419
+ /**
1420
+ *
1421
+ * @param WP_Error $result
1422
+ *
1423
+ * @since 3.1.1
1424
+ */
1425
+ public function get_generic_error( $result = null ) {
1426
+ $messages = wc_stripe_get_error_messages();
1427
+ if ( isset( $messages["{$this->id}_generic"] ) ) {
1428
+ return $messages["{$this->id}_generic"];
1429
+ }
1430
+
1431
+ return null != $result ? $result->get_error_message() : __( 'Cannot process payment', 'woo-stripe-payment' );
1432
+ }
1433
+
1434
+ /**
1435
+ *
1436
+ * @since 3.1.2
1437
+ */
1438
+ private function get_payment_section_description() {
1439
+ return sprintf( __( 'Increase your conversion rate by offering %1$s on your Product and Cart pages, or at the top of the checkout page. <br/><strong>Note:</strong> you can control which products display %s by going to the product edit page.', 'woo-stripe-payment' ), $this->get_method_title() );
1440
+ }
1441
+
1442
+ /**
1443
+ * Outputs fields required by Google Pay to render the payment wallet.
1444
+ *
1445
+ * @param string $page
1446
+ */
1447
+ public function output_display_items( $page = 'checkout' ) {
1448
+ global $wp;
1449
+ $order = null;
1450
+ $data = array(
1451
+ 'items' => $this->has_digital_wallet ? $this->get_display_items( $page ) : array(),
1452
+ 'shipping_options' => $this->has_digital_wallet ? $this->get_formatted_shipping_methods() : array(),
1453
+ 'total' => WC()->cart->total,
1454
+ 'total_cents' => wc_stripe_add_number_precision( WC()->cart->total, get_woocommerce_currency() ),
1455
+ 'currency' => get_woocommerce_currency()
1456
+ );
1457
+ if ( in_array( $page, array( 'checkout', 'cart' ) ) ) {
1458
+ if ( ! empty( $wp->query_vars['order-pay'] ) ) {
1459
+ $order = wc_get_order( absint( $wp->query_vars['order-pay'] ) );
1460
+ $page = 'order_pay';
1461
+ $data['needs_shipping'] = false;
1462
+ $data['items'] = $this->has_digital_wallet ? $this->get_display_items( $page, $order ) : array();
1463
+ $data['total'] = $order->get_total();
1464
+ $data['total_cents'] = wc_stripe_add_number_precision( $order->get_total(), $order->get_currency() );
1465
+ $data['currency'] = $order->get_currency();
1466
+ } else {
1467
+ $data['needs_shipping'] = WC()->cart->needs_shipping();
1468
+ if ( 'checkout' === $page && is_cart() ) {
1469
+ $page = 'cart';
1470
+ } elseif ( is_add_payment_method_page() ) {
1471
+ $page = 'add_payment_method';
1472
+ }
1473
+ }
1474
+ } elseif ( 'product' === $page ) {
1475
+ global $product;
1476
+ $data['needs_shipping'] = $product->needs_shipping();
1477
+ $data['product'] = array(
1478
+ 'id' => $product->get_id(),
1479
+ 'price' => $product->get_price(),
1480
+ 'variation' => false
1481
+ );
1482
+ }
1483
+ /**
1484
+ * @param array $data
1485
+ * @param string $page
1486
+ * @param WC_Payment_Gateway_Stripe $this
1487
+ *
1488
+ * @since 3.1.8
1489
+ */
1490
+ $data = apply_filters( 'wc_stripe_output_display_items', $data, $page, $this );
1491
+ printf( '<input type="hidden" class="%1$s" data-gateway="%2$s"/>', "woocommerce_{$this->id}_gateway_data {$page}-page", htmlspecialchars( wp_json_encode( $data ) ) );
1492
+ }
1493
+
1494
+ /**
1495
+ * @param array $deps
1496
+ * @param $scripts
1497
+ *
1498
+ * @since 3.1.8
1499
+ */
1500
+ public function get_mini_cart_dependencies( $deps, $scripts ) {
1501
+ return $deps;
1502
+ }
1503
+
1504
+ /**
1505
+ * @return array
1506
+ * @since 3.2.0
1507
+ */
1508
+ public function get_shipping_packages() {
1509
+ $packages = WC()->shipping()->get_packages();
1510
+ if ( empty( $packages ) && wcs_stripe_active() && WC_Subscriptions_Cart::cart_contains_free_trial() ) {
1511
+ // there is a subscription with a free trial in the cart. Shipping packages will be in the recurring cart.
1512
+ WC_Subscriptions_Cart::set_calculation_type( 'recurring_total' );
1513
+ $count = 0;
1514
+ if ( isset( WC()->cart->recurring_carts ) ) {
1515
+ foreach ( WC()->cart->recurring_carts as $recurring_cart_key => $recurring_cart ) {
1516
+ foreach ( $recurring_cart->get_shipping_packages() as $i => $base_package ) {
1517
+ $packages[ $recurring_cart_key . '_' . $count ] = WC_Subscriptions_Cart::get_calculated_shipping_for_package( $base_package );
1518
+ }
1519
+ $count ++;
1520
+ }
1521
+ }
1522
+ WC_Subscriptions_Cart::set_calculation_type( 'none' );
1523
+ }
1524
+
1525
+ return $packages;
1526
+ }
1527
+
1528
+ /**
1529
+ * @param WC_Cart $cart
1530
+ * @param array $items
1531
+ *
1532
+ * @return array
1533
+ * @since 3.2.1
1534
+ */
1535
+ protected function get_display_items_for_cart( $cart, $items = array() ) {
1536
+ $incl_tax = wc_stripe_display_prices_including_tax();
1537
+ foreach ( $cart->get_cart() as $cart_item ) {
1538
+ /**
1539
+ *
1540
+ * @var WC_Product $product
1541
+ */
1542
+ $product = $cart_item['data'];
1543
+ $qty = $cart_item['quantity'];
1544
+ $label = $qty > 1 ? sprintf( '%s X %s', $product->get_name(), $qty ) : $product->get_name();
1545
+ $price = $incl_tax ? wc_get_price_including_tax( $product, array( 'qty' => $qty ) ) : wc_get_price_excluding_tax( $product, array( 'qty' => $qty ) );
1546
+ $items[] = $this->get_display_item_for_cart( $price, $label, 'product', $cart_item, $cart );
1547
+ }
1548
+ if ( $cart->needs_shipping() ) {
1549
+ $price = $incl_tax ? $cart->shipping_total + $cart->shipping_tax_total : $cart->shipping_total;
1550
+ $items[] = $this->get_display_item_for_cart( $price, __( 'Shipping', 'woo-stripe-payment' ), 'shipping' );
1551
+ }
1552
+ foreach ( $cart->get_fees() as $fee ) {
1553
+ $price = $incl_tax ? $fee->total + $fee->tax : $fee->total;
1554
+ $items[] = $this->get_display_item_for_cart( $price, $fee->name, 'fee', $fee, $cart );
1555
+ }
1556
+ if ( 0 < $cart->discount_cart ) {
1557
+ $price = - 1 * abs( $incl_tax ? $cart->discount_cart + $cart->discount_cart_tax : $cart->discount_cart );
1558
+ $items[] = $this->get_display_item_for_cart( $price, __( 'Discount', 'woo-stripe-payment' ), 'discount', $cart );
1559
+ }
1560
+ if ( ! $incl_tax && wc_tax_enabled() ) {
1561
+ $items[] = $this->get_display_item_for_cart( $cart->get_taxes_total(), __( 'Tax', 'woo-stripe-payment' ), 'tax', $cart );
1562
+ }
1563
+
1564
+ return $items;
1565
+ }
1566
+
1567
+ /**
1568
+ * @param WC_Order $order
1569
+ * @param array $items
1570
+ *
1571
+ * @return array
1572
+ * @since 3.2.1
1573
+ */
1574
+ protected function get_display_items_for_order( $order, $items = array() ) {
1575
+ foreach ( $order->get_items() as $item ) {
1576
+ $qty = $item->get_quantity();
1577
+ $label = $qty > 1 ? sprintf( '%s X %s', $item->get_name(), $qty ) : $item->get_name();
1578
+ $items[] = $this->get_display_item_for_order( $item->get_subtotal(), $label, $order, 'item', $item );
1579
+ }
1580
+ if ( 0 < $order->get_shipping_total() ) {
1581
+ $items[] = $this->get_display_item_for_order( $order->get_shipping_total(), __( 'Shipping', 'woo-stripe-payment' ), $order, 'shipping' );
1582
+ }
1583
+ if ( 0 < $order->get_total_discount() ) {
1584
+ $items[] = $this->get_display_item_for_order( - 1 * $order->get_total_discount(), __( 'Discount', 'woo-stripe-payment' ), $order, 'discount' );
1585
+ }
1586
+ if ( 0 < $order->get_fees() ) {
1587
+ $fee_total = 0;
1588
+ foreach ( $order->get_fees() as $fee ) {
1589
+ $fee_total += $fee->get_total();
1590
+ }
1591
+ $items[] = $this->get_display_item_for_order( $fee_total, __( 'Fees', 'woo-stripe-payment' ), $order, 'fee' );
1592
+ }
1593
+ if ( 0 < $order->get_total_tax() ) {
1594
+ $items[] = $this->get_display_item_for_order( $order->get_total_tax(), __( 'Tax', 'woocommerce' ), $order, 'tax' );
1595
+ }
1596
+
1597
+ return $items;
1598
+ }
1599
+
1600
+ /**
1601
+ * @param float $price
1602
+ * @param string $label
1603
+ * @param string $type
1604
+ * @param mixed ...$args
1605
+ *
1606
+ * @return array
1607
+ * @since 3.2.1
1608
+ */
1609
+ protected function get_display_item_for_cart( $price, $label, $type, ...$args ) {
1610
+ return array(
1611
+ 'label' => $label,
1612
+ 'pending' => false,
1613
+ 'amount' => wc_stripe_add_number_precision( $price )
1614
+ );
1615
+ }
1616
+
1617
+ /**
1618
+ * @param float $price
1619
+ * @param string $label
1620
+ * @param WC_Order $order
1621
+ * @param string $type
1622
+ * @param mixed ...$args
1623
+ */
1624
+ protected function get_display_item_for_order( $price, $label, $order, $type, ...$args ) {
1625
+ return array(
1626
+ 'label' => $label,
1627
+ 'pending' => false,
1628
+ 'amount' => wc_stripe_add_number_precision( $price, $order->get_currency() )
1629
+ );
1630
+ }
1631
+
1632
+ /**
1633
+ * @param WC_Product $product
1634
+ *
1635
+ * @return array
1636
+ * @since 3.2.1
1637
+ *
1638
+ */
1639
+ protected function get_display_item_for_product( $product ) {
1640
+ return array(
1641
+ 'label' => esc_attr( $product->get_name() ),
1642
+ 'pending' => true,
1643
+ 'amount' => wc_stripe_add_number_precision( $product->get_price() )
1644
+ );
1645
+ }
1646
+
1647
+ /**
1648
+ * @param array $methods
1649
+ *
1650
+ * @return array
1651
+ * @since 3.2.1
1652
+ */
1653
+ public function get_formatted_shipping_methods( $methods = array() ) {
1654
+ if ( wcs_stripe_active() && WC_Subscriptions_Change_Payment_Gateway::$is_request_to_change_payment ) {
1655
+ return $methods;
1656
+ } else {
1657
+ $methods = array();
1658
+ $packages = $this->get_shipping_packages();
1659
+ $incl_tax = wc_stripe_display_prices_including_tax();
1660
+ foreach ( $packages as $i => $package ) {
1661
+ foreach ( $package['rates'] as $rate ) {
1662
+ $price = $incl_tax ? $rate->cost + $rate->get_shipping_tax() : $rate->cost;
1663
+ $methods[] = $this->get_formatted_shipping_method( $price, $rate, $i, $package, $incl_tax );
1664
+ }
1665
+ }
1666
+ }
1667
+
1668
+ return $methods;
1669
+ }
1670
+
1671
+ /**
1672
+ * @param float $price
1673
+ * @param WC_Shipping_Rate $rate
1674
+ * @param string $i
1675
+ * @param array $package
1676
+ * @param bool $incl_tax
1677
+ *
1678
+ * @return array
1679
+ * @since 3.2.1
1680
+ */
1681
+ public function get_formatted_shipping_method( $price, $rate, $i, $package, $incl_tax ) {
1682
+ $method = array(
1683
+ 'id' => $this->get_shipping_method_id( $rate->id, $i ),
1684
+ 'label' => $this->get_formatted_shipping_label( $price, $rate, $incl_tax ),
1685
+ 'detail' => '',
1686
+ 'amount' => wc_stripe_add_number_precision( $price )
1687
+ );
1688
+ if ( $incl_tax ) {
1689
+ if ( $rate->get_shipping_tax() > 0 && ! wc_prices_include_tax() ) {
1690
+ $method['detail'] = WC()->countries->inc_tax_or_vat();
1691
+ }
1692
+ } else {
1693
+ if ( $rate->get_shipping_tax() > 0 && wc_prices_include_tax() ) {
1694
+ $method['detail'] = WC()->countries->ex_tax_or_vat();
1695
+ }
1696
+ }
1697
+
1698
+ return $method;
1699
+ }
1700
+
1701
+ /**
1702
+ * @param string $id
1703
+ * @param string $index
1704
+ *
1705
+ * @return mixed
1706
+ */
1707
+ protected function get_shipping_method_id( $id, $index ) {
1708
+ return sprintf( '%s:%s', $index, $id );
1709
+ }
1710
+
1711
+ /**
1712
+ * @param float $price
1713
+ * @param WC_Shipping_Rate $rate
1714
+ * @param bool $incl_tax
1715
+ *
1716
+ * @since 3.2.1
1717
+ */
1718
+ protected function get_formatted_shipping_label( $price, $rate, $incl_tax ) {
1719
+ return sprintf( '%s', esc_attr( $rate->get_label() ) );
1720
+ }
1721
+
1722
+ /**
1723
+ * Returns true if a scheduled subscription payment is being processed.
1724
+ * @return bool
1725
+ * @since 3.2.3
1726
+ */
1727
+ protected function is_processing_scheduled_payment() {
1728
+ return doing_action( 'woocommerce_scheduled_subscription_payment_' . $this->id );
1729
+ }
1730
+ }
includes/admin/class-wc-stripe-admin-notices.php CHANGED
@@ -1,67 +1,67 @@
1
- <?php
2
-
3
- namespace PaymentPlugins;
4
-
5
- defined( 'ABSPATH' ) || exit();
6
-
7
- /**
8
- *
9
- * @since 3.1.0
10
- * @author PaymentPlugins
11
- *
12
- */
13
- class WC_Stripe_Admin_Notices {
14
-
15
- public static function init() {
16
- add_action( 'admin_notices', array( __CLASS__, 'notices' ) );
17
- }
18
-
19
- public static function notices() {
20
- $messages = array();
21
- foreach ( static::get_notices() as $key => $notice ) {
22
- if ( $notice['callback']() ) {
23
- $screen = get_current_screen();
24
- $screen_id = $screen ? $screen->id : '';
25
- ob_start();
26
- echo '<div class="notice notice-info woocommerce-message"><p>' . $notice['message']() . '</p></div>';
27
- $message = ob_get_clean();
28
- if ( strstr( $screen_id, 'wc-settings' ) ) {
29
- $messages[] = $message;
30
- } else {
31
- echo $message;
32
- }
33
- }
34
- }
35
- // in WC 4.0 admin notices don't show on the WC Settings pages so adding this workaround.
36
- if ( $messages ) {
37
- wp_localize_script( 'wc-stripe-admin-settings', 'wc_stripe_admin_notices', $messages );
38
- }
39
- }
40
-
41
- public static function get_notices() {
42
- return array(
43
- 'connect_notice' => array(
44
- 'callback' => function () {
45
- return ( ! isset( $_GET['_stripe_connect_nonce'] ) &&
46
- ( ! wc_stripe()->api_settings->get_option( 'account_id' ) && get_option( 'wc_stripe_connect_notice', 'no' ) == 'yes' ) );
47
- },
48
- 'message' => function () {
49
- wp_enqueue_style( 'wc-stripe-styles', wc_stripe()->assets_url( 'css/admin/admin.css' ), array(), wc_stripe()->version() );
50
- return sprintf(
51
- __(
52
- 'At Stripe\'s request we have updated how the Stripe for WooCommerce
53
- plugin integrates with Stripe. This new integration offers even more security and
54
- Stripe is requesting that all merchants switch. %1$sUpdate Integration%2$s',
55
- 'woo-stripe-payment'
56
- ),
57
- ' <a href = "' .
58
- wc_stripe()->api_settings->get_connect_url() . '" class = "stripe-connect light-blue do-stripe-connect" > < span > ',
59
- ' < / span > < / a > '
60
- );
61
- },
62
- ),
63
- );
64
- }
65
- }
66
- \PaymentPlugins\WC_Stripe_Admin_Notices::init();
67
-
1
+ <?php
2
+
3
+ namespace PaymentPlugins;
4
+
5
+ defined( 'ABSPATH' ) || exit();
6
+
7
+ /**
8
+ *
9
+ * @since 3.1.0
10
+ * @author PaymentPlugins
11
+ *
12
+ */
13
+ class WC_Stripe_Admin_Notices {
14
+
15
+ public static function init() {
16
+ add_action( 'admin_notices', array( __CLASS__, 'notices' ) );
17
+ }
18
+
19
+ public static function notices() {
20
+ $messages = array();
21
+ foreach ( static::get_notices() as $key => $notice ) {
22
+ if ( $notice['callback']() ) {
23
+ $screen = get_current_screen();
24
+ $screen_id = $screen ? $screen->id : '';
25
+ ob_start();
26
+ echo '<div class="notice notice-info woocommerce-message"><p>' . $notice['message']() . '</p></div>';
27
+ $message = ob_get_clean();
28
+ if ( strstr( $screen_id, 'wc-settings' ) ) {
29
+ $messages[] = $message;
30
+ } else {
31
+ echo $message;
32
+ }
33
+ }
34
+ }
35
+ // in WC 4.0 admin notices don't show on the WC Settings pages so adding this workaround.
36
+ if ( $messages ) {
37
+ wp_localize_script( 'wc-stripe-admin-settings', 'wc_stripe_admin_notices', $messages );
38
+ }
39
+ }
40
+
41
+ public static function get_notices() {
42
+ return array(
43
+ 'connect_notice' => array(
44
+ 'callback' => function () {
45
+ return ( ! isset( $_GET['_stripe_connect_nonce'] ) &&
46
+ ( ! wc_stripe()->api_settings->get_option( 'account_id' ) && get_option( 'wc_stripe_connect_notice', 'no' ) == 'yes' ) );
47
+ },
48
+ 'message' => function () {
49
+ wp_enqueue_style( 'wc-stripe-styles', wc_stripe()->assets_url( 'css/admin/admin.css' ), array(), wc_stripe()->version() );
50
+
51
+ return sprintf(
52
+ __(
53
+ 'At Stripe\'s request we have updated how the Stripe for WooCommerce
54
+ plugin integrates with Stripe. This new integration offers even more security and
55
+ Stripe is requesting that all merchants switch. %1$sUpdate Integration%2$s',
56
+ 'woo-stripe-payment'
57
+ ),
58
+ ' <a href = "' . wc_stripe()->api_settings->get_connect_url() . '" class = "stripe-connect light-blue do-stripe-connect"><span>', '</span></a>'
59
+ );
60
+ },
61
+ ),
62
+ );
63
+ }
64
+ }
65
+
66
+ \PaymentPlugins\WC_Stripe_Admin_Notices::init();
67
+
includes/class-stripe.php CHANGED
@@ -1,343 +1,343 @@
1
- <?php
2
- defined( 'ABSPATH' ) || exit();
3
-
4
- /**
5
- * Singleton class that handles plugin functionality like class loading.
6
- *
7
- * @since 3.0.0
8
- * @author PaymentPlugins
9
- * @package Stripe/Classes
10
- *
11
- */
12
- class WC_Stripe_Manager {
13
-
14
- public static $_instance;
15
-
16
- public static function instance() {
17
- if ( self::$_instance == null ) {
18
- self::$_instance = new self();
19
- }
20
-
21
- return self::$_instance;
22
- }
23
-
24
- /**
25
- *
26
- * @var string
27
- */
28
- public $version = '3.2.2';
29
-
30
- /**
31
- *
32
- * @var WC_Stripe_Settings_API
33
- */
34
- public $api_settings;
35
-
36
- /**
37
- * @var WC_Stripe_Settings_API
38
- * @since 3.1.7
39
- */
40
- public $account_settings;
41
-
42
- /**
43
- *
44
- * @var WC_Stripe_Rest_API
45
- */
46
- public $rest_api;
47
-
48
- /**
49
- *
50
- * @var string
51
- */
52
- public $client_id = 'ca_Gp4vLOJiqHJLZGxakHW7JdbBlcgWK8Up';
53
-
54
- /**
55
- * Test client id;
56
- *
57
- * @var string
58
- */
59
- //public $client_id = 'ca_Gp4vL3V6FpTguYoZIehD5COPeI80rLpV';
60
-
61
- /**
62
- *
63
- * @var WC_Stripe_Frontend_Scripts
64
- */
65
- private $scripts;
66
-
67
- /**
68
- *
69
- * @var array
70
- */
71
- private $payment_gateways;
72
-
73
- public function __construct() {
74
- add_action( 'plugins_loaded', array( $this, 'plugins_loaded' ), 10 );
75
- add_action( 'init', array( $this, 'init' ) );
76
- add_action( 'admin_init', array( $this, 'admin_init' ) );
77
- add_action( 'woocommerce_init', array( $this, 'woocommerce_dependencies' ) );
78
- $this->includes();
79
- }
80
-
81
- /**
82
- * Return the plugin version.
83
- *
84
- * @return string
85
- */
86
- public function version() {
87
- return $this->version;
88
- }
89
-
90
- /**
91
- * Return the url for the plugin assets.
92
- *
93
- * @return string
94
- */
95
- public function assets_url( $uri = '' ) {
96
- $url = WC_STRIPE_ASSETS . $uri;
97
- if ( ! preg_match( '/(\.js)|(\.css)|(\.svg)|(\.png)/', $uri ) ) {
98
- return trailingslashit( $url );
99
- }
100
-
101
- return $url;
102
- }
103
-
104
- /**
105
- * Return the dir path for the plugin.
106
- *
107
- * @return string
108
- */
109
- public function plugin_path() {
110
- return WC_STRIPE_PLUGIN_FILE_PATH;
111
- }
112
-
113
- public function plugins_loaded() {
114
- load_plugin_textdomain( 'woo-stripe-payment', false, dirname( WC_STRIPE_PLUGIN_NAME ) . '/i18n/languages' );
115
- }
116
-
117
- /**
118
- * Function that is hooked in to the WordPress init action.
119
- */
120
- public function init() {
121
- }
122
-
123
- public function includes() {
124
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-install.php';
125
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-update.php';
126
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-rest-api.php';
127
-
128
- if ( is_admin() ) {
129
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/admin/class-wc-stripe-admin-menus.php';
130
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/admin/class-wc-stripe-admin-assets.php';
131
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/admin/class-wc-stripe-admin-settings.php';
132
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/admin/meta-boxes/class-wc-stripe-admin-order-metaboxes.php';
133
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/admin/meta-boxes/class-wc-stripe-admin-meta-box-product-data.php';
134
- }
135
- }
136
-
137
- /**
138
- * Function that is hooked in to the WordPress admin_init action.
139
- */
140
- public function admin_init() {
141
- }
142
-
143
- public function woocommerce_dependencies() {
144
- // load functions
145
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/wc-stripe-functions.php';
146
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/wc-stripe-webhook-functions.php';
147
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/wc-stripe-hooks.php';
148
-
149
- // constants
150
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-constants.php';
151
-
152
- // traits
153
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/traits/wc-stripe-settings-trait.php';
154
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/traits/wc-stripe-controller-traits.php';
155
-
156
- // load factories
157
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-payment-factory.php';
158
-
159
- // load gateways
160
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/abstract/abstract-wc-payment-gateway-stripe.php';
161
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/abstract/abstract-wc-payment-gateway-stripe-local-payment.php';
162
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-cc.php';
163
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-applepay.php';
164
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-googlepay.php';
165
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-ach.php';
166
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-payment-request.php';
167
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-ideal.php';
168
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-p24.php';
169
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-klarna.php';
170
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-giropay.php';
171
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-eps.php';
172
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-multibanco.php';
173
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-sepa.php';
174
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-sofort.php';
175
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-wechat.php';
176
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-bancontact.php';
177
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-fpx.php';
178
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-alipay.php';
179
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-becs.php';
180
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-grabpay.php';
181
-
182
- // tokens
183
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/abstract/abstract-wc-payment-token-stripe.php';
184
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/tokens/class-wc-payment-token-stripe-cc.php';
185
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/tokens/class-wc-payment-token-stripe-applepay.php';
186
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/tokens/class-wc-payment-token-stripe-googlepay.php';
187
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/tokens/class-wc-payment-token-stripe-local-payment.php';
188
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/tokens/class-wc-payment-token-stripe-ach.php';
189
-
190
- // main classes
191
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-frontend-scripts.php';
192
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-field-manager.php';
193
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-rest-api.php';
194
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-gateway.php';
195
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-customer-manager.php';
196
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-gateway-conversions.php';
197
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-frontend-notices.php';
198
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-redirect-handler.php';
199
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-product-gateway-option.php';
200
-
201
- // settings
202
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/abstract/abstract-wc-stripe-settings.php';
203
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/admin/settings/class-wc-stripe-api-settings.php';
204
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/admin/settings/class-wc-stripe-account-settings.php';
205
-
206
- if ( is_admin() ) {
207
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/admin/class-wc-stripe-admin-notices.php';
208
- include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/admin/class-wc-stripe-admin-user-edit.php';
209
- }
210
-
211
- $this->payment_gateways = apply_filters(
212
- 'wc_stripe_payment_gateways',
213
- array(
214
- 'WC_Payment_Gateway_Stripe_CC',
215
- 'WC_Payment_Gateway_Stripe_ApplePay',
216
- 'WC_Payment_Gateway_Stripe_GooglePay',
217
- 'WC_Payment_Gateway_Stripe_Payment_Request',
218
- 'WC_Payment_Gateway_Stripe_ACH',
219
- 'WC_Payment_Gateway_Stripe_Ideal',
220
- 'WC_Payment_Gateway_Stripe_P24',
221
- 'WC_Payment_Gateway_Stripe_Klarna',
222
- 'WC_Payment_Gateway_Stripe_Bancontact',
223
- 'WC_Payment_Gateway_Stripe_Giropay',
224
- 'WC_Payment_Gateway_Stripe_EPS',
225
- 'WC_Payment_Gateway_Stripe_Multibanco',
226
- 'WC_Payment_Gateway_Stripe_Sepa',
227
- 'WC_Payment_Gateway_Stripe_Sofort',
228
- 'WC_Payment_Gateway_Stripe_WeChat',
229
- 'WC_Payment_Gateway_Stripe_FPX',
230
- 'WC_Payment_Gateway_Stripe_BECS',
231
- 'WC_Payment_Gateway_Stripe_Alipay',
232
- //'WC_Payment_Gateway_Stripe_GrabPay'
233
- )
234
- );
235
-
236
- $api_class = apply_filters( 'wc_stripe_rest_api_class', 'WC_Stripe_Rest_API' );
237
- $this->rest_api = new $api_class();
238
-
239
- if ( $this->is_request( 'frontend' ) ) {
240
- $this->scripts = new WC_Stripe_Frontend_Scripts();
241
- }
242
-
243
- // allow other plugins to provide their own settings classes.
244
- $setting_classes = apply_filters( 'wc_stripe_setting_classes', array(
245
- 'api_settings' => 'WC_Stripe_API_Settings',
246
- 'account_settings' => 'WC_Stripe_Account_Settings'
247
- ) );
248
- foreach ( $setting_classes as $id => $class_name ) {
249
- if ( class_exists( $class_name ) ) {
250
- $this->{$id} = new $class_name();
251
- }
252
- }
253
- }
254
-
255
- /**
256
- * Return the plugin template path.
257
- */
258
- public function template_path() {
259
- return 'woo-stripe-payment';
260
- }
261
-
262
- /**
263
- * Return the plguins default directory path for template files.
264
- */
265
- public function default_template_path() {
266
- return WC_STRIPE_PLUGIN_FILE_PATH . 'templates/';
267
- }
268
-
269
- /**
270
- *
271
- * @return string
272
- */
273
- public function rest_uri() {
274
- return 'wc-stripe/v1/';
275
- }
276
-
277
- /**
278
- *
279
- * @return string
280
- */
281
- public function rest_url() {
282
- return get_rest_url( null, $this->rest_uri() );
283
- }
284
-
285
- /**
286
- *
287
- * @return WC_Stripe_Frontend_Scripts
288
- */
289
- public function scripts() {
290
- if ( is_null( $this->scripts ) ) {
291
- $this->scripts = new WC_Stripe_Frontend_Scripts();
292
- }
293
-
294
- return $this->scripts;
295
- }
296
-
297
- public function payment_gateways() {
298
- return $this->payment_gateways;
299
- }
300
-
301
- /**
302
- * Schedule actions required by the plugin
303
- * @since 3.1.6
304
- */
305
- public function scheduled_actions() {
306
- if ( function_exists( 'WC' ) ) {
307
- if ( ! WC()->queue()->get_next( 'wc_stripe_remove_order_locks' ) ) {
308
- WC()->queue()->schedule_recurring( strtotime( 'today midnight' ), DAY_IN_SECONDS, 'wc_stripe_remove_order_locks' );
309
- }
310
- }
311
- }
312
-
313
- /**
314
- * @param string $type
315
- *
316
- * @return bool
317
- * @since 3.1.9
318
- */
319
- public function is_request( $type ) {
320
- if ( ! did_action( 'before_woocommerce_init' ) ) {
321
- return false;
322
- }
323
- switch ( $type ) {
324
- case 'frontend':
325
- return ( ! is_admin() || defined( 'DOING_AJAX' ) ) && ! defined( 'DOING_CRON' ) && ! WC()->is_rest_api_request();
326
- default:
327
- return true;
328
- }
329
- }
330
- }
331
-
332
- /**
333
- * Returns the global instance of the WC_Stripe_Manager.
334
- *
335
- * @return WC_Stripe_Manager
336
- * @package Stripe/Functions
337
- */
338
- function wc_stripe() {
339
- return WC_Stripe_Manager::instance();
340
- }
341
-
342
- // load singleton
343
- wc_stripe();
1
+ <?php
2
+ defined( 'ABSPATH' ) || exit();
3
+
4
+ /**
5
+ * Singleton class that handles plugin functionality like class loading.
6
+ *
7
+ * @since 3.0.0
8
+ * @author PaymentPlugins
9
+ * @package Stripe/Classes
10
+ *
11
+ */
12
+ class WC_Stripe_Manager {
13
+
14
+ public static $_instance;
15
+
16
+ public static function instance() {
17
+ if ( self::$_instance == null ) {
18
+ self::$_instance = new self();
19
+ }
20
+
21
+ return self::$_instance;
22
+ }
23
+
24
+ /**
25
+ *
26
+ * @var string
27
+ */
28
+ public $version = '3.2.3';
29
+
30
+ /**
31
+ *
32
+ * @var WC_Stripe_Settings_API
33
+ */
34
+ public $api_settings;
35
+
36
+ /**
37
+ * @var WC_Stripe_Settings_API
38
+ * @since 3.1.7
39
+ */
40
+ public $account_settings;
41
+
42
+ /**
43
+ *
44
+ * @var WC_Stripe_Rest_API
45
+ */
46
+ public $rest_api;
47
+
48
+ /**
49
+ *
50
+ * @var string
51
+ */
52
+ public $client_id = 'ca_Gp4vLOJiqHJLZGxakHW7JdbBlcgWK8Up';
53
+
54
+ /**
55
+ * Test client id;
56
+ *
57
+ * @var string
58
+ */
59
+ //public $client_id = 'ca_Gp4vL3V6FpTguYoZIehD5COPeI80rLpV';
60
+
61
+ /**
62
+ *
63
+ * @var WC_Stripe_Frontend_Scripts
64
+ */
65
+ private $scripts;
66
+
67
+ /**
68
+ *
69
+ * @var array
70
+ */
71
+ private $payment_gateways;
72
+
73
+ public function __construct() {
74
+ add_action( 'plugins_loaded', array( $this, 'plugins_loaded' ), 10 );
75
+ add_action( 'init', array( $this, 'init' ) );
76
+ add_action( 'admin_init', array( $this, 'admin_init' ) );
77
+ add_action( 'woocommerce_init', array( $this, 'woocommerce_dependencies' ) );
78
+ $this->includes();
79
+ }
80
+
81
+ /**
82
+ * Return the plugin version.
83
+ *
84
+ * @return string
85
+ */
86
+ public function version() {
87
+ return $this->version;
88
+ }
89
+
90
+ /**
91
+ * Return the url for the plugin assets.
92
+ *
93
+ * @return string
94
+ */
95
+ public function assets_url( $uri = '' ) {
96
+ $url = WC_STRIPE_ASSETS . $uri;
97
+ if ( ! preg_match( '/(\.js)|(\.css)|(\.svg)|(\.png)/', $uri ) ) {
98
+ return trailingslashit( $url );
99
+ }
100
+
101
+ return $url;
102
+ }
103
+
104
+ /**
105
+ * Return the dir path for the plugin.
106
+ *
107
+ * @return string
108
+ */
109
+ public function plugin_path() {
110
+ return WC_STRIPE_PLUGIN_FILE_PATH;
111
+ }
112
+
113
+ public function plugins_loaded() {
114
+ load_plugin_textdomain( 'woo-stripe-payment', false, dirname( WC_STRIPE_PLUGIN_NAME ) . '/i18n/languages' );
115
+ }
116
+
117
+ /**
118
+ * Function that is hooked in to the WordPress init action.
119
+ */
120
+ public function init() {
121
+ }
122
+
123
+ public function includes() {
124
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-install.php';
125
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-update.php';
126
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-rest-api.php';
127
+
128
+ if ( is_admin() ) {
129
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/admin/class-wc-stripe-admin-menus.php';
130
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/admin/class-wc-stripe-admin-assets.php';
131
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/admin/class-wc-stripe-admin-settings.php';
132
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/admin/meta-boxes/class-wc-stripe-admin-order-metaboxes.php';
133
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/admin/meta-boxes/class-wc-stripe-admin-meta-box-product-data.php';
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Function that is hooked in to the WordPress admin_init action.
139
+ */
140
+ public function admin_init() {
141
+ }
142
+
143
+ public function woocommerce_dependencies() {
144
+ // load functions
145
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/wc-stripe-functions.php';
146
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/wc-stripe-webhook-functions.php';
147
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/wc-stripe-hooks.php';
148
+
149
+ // constants
150
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-constants.php';
151
+
152
+ // traits
153
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/traits/wc-stripe-settings-trait.php';
154
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/traits/wc-stripe-controller-traits.php';
155
+
156
+ // load factories
157
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-payment-factory.php';
158
+
159
+ // load gateways
160
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/abstract/abstract-wc-payment-gateway-stripe.php';
161
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/abstract/abstract-wc-payment-gateway-stripe-local-payment.php';
162
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-cc.php';
163
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-applepay.php';
164
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-googlepay.php';
165
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-ach.php';
166
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-payment-request.php';
167
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-ideal.php';
168
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-p24.php';
169
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-klarna.php';
170
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-giropay.php';
171
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-eps.php';
172
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-multibanco.php';
173
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-sepa.php';
174
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-sofort.php';
175
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-wechat.php';
176
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-bancontact.php';
177
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-fpx.php';
178
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-alipay.php';
179
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-becs.php';
180
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/gateways/class-wc-payment-gateway-stripe-grabpay.php';
181
+
182
+ // tokens
183
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/abstract/abstract-wc-payment-token-stripe.php';
184
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/tokens/class-wc-payment-token-stripe-cc.php';
185
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/tokens/class-wc-payment-token-stripe-applepay.php';
186
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/tokens/class-wc-payment-token-stripe-googlepay.php';
187
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/tokens/class-wc-payment-token-stripe-local-payment.php';
188
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/tokens/class-wc-payment-token-stripe-ach.php';
189
+
190
+ // main classes
191
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-frontend-scripts.php';
192
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-field-manager.php';
193
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-rest-api.php';
194
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-gateway.php';
195
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-customer-manager.php';
196
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-gateway-conversions.php';
197
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-frontend-notices.php';
198
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-redirect-handler.php';
199
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/class-wc-stripe-product-gateway-option.php';
200
+
201
+ // settings
202
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/abstract/abstract-wc-stripe-settings.php';
203
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/admin/settings/class-wc-stripe-api-settings.php';
204
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/admin/settings/class-wc-stripe-account-settings.php';
205
+
206
+ if ( is_admin() ) {
207
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/admin/class-wc-stripe-admin-notices.php';
208
+ include_once WC_STRIPE_PLUGIN_FILE_PATH . 'includes/admin/class-wc-stripe-admin-user-edit.php';
209
+ }
210
+
211
+ $this->payment_gateways = apply_filters(
212
+ 'wc_stripe_payment_gateways',
213
+ array(
214
+ 'WC_Payment_Gateway_Stripe_CC',
215
+ 'WC_Payment_Gateway_Stripe_ApplePay',
216
+ 'WC_Payment_Gateway_Stripe_GooglePay',
217
+ 'WC_Payment_Gateway_Stripe_Payment_Request',
218
+ 'WC_Payment_Gateway_Stripe_ACH',
219
+ 'WC_Payment_Gateway_Stripe_Ideal',
220
+ 'WC_Payment_Gateway_Stripe_P24',
221
+ 'WC_Payment_Gateway_Stripe_Klarna',
222
+ 'WC_Payment_Gateway_Stripe_Bancontact',
223
+ 'WC_Payment_Gateway_Stripe_Giropay',
224
+ 'WC_Payment_Gateway_Stripe_EPS',
225
+ 'WC_Payment_Gateway_Stripe_Multibanco',
226
+ 'WC_Payment_Gateway_Stripe_Sepa',
227
+ 'WC_Payment_Gateway_Stripe_Sofort',
228
+ 'WC_Payment_Gateway_Stripe_WeChat',
229
+ 'WC_Payment_Gateway_Stripe_FPX',
230
+ 'WC_Payment_Gateway_Stripe_BECS',
231
+ 'WC_Payment_Gateway_Stripe_Alipay',
232
+ //'WC_Payment_Gateway_Stripe_GrabPay'
233
+ )
234
+ );
235
+
236
+ $api_class = apply_filters( 'wc_stripe_rest_api_class', 'WC_Stripe_Rest_API' );
237
+ $this->rest_api = new $api_class();
238
+
239
+ if ( $this->is_request( 'frontend' ) ) {
240
+ $this->scripts = new WC_Stripe_Frontend_Scripts();
241
+ }
242
+
243
+ // allow other plugins to provide their own settings classes.
244
+ $setting_classes = apply_filters( 'wc_stripe_setting_classes', array(
245
+ 'api_settings' => 'WC_Stripe_API_Settings',
246
+ 'account_settings' => 'WC_Stripe_Account_Settings'
247
+ ) );
248
+ foreach ( $setting_classes as $id => $class_name ) {
249
+ if ( class_exists( $class_name ) ) {
250
+ $this->{$id} = new $class_name();
251
+ }
252
+ }
253
+ }
254
+
255
+ /**
256
+ * Return the plugin template path.
257
+ */
258
+ public function template_path() {
259
+ return 'woo-stripe-payment';
260
+ }
261
+
262
+ /**
263
+ * Return the plguins default directory path for template files.
264
+ */
265
+ public function default_template_path() {
266
+ return WC_STRIPE_PLUGIN_FILE_PATH . 'templates/';
267
+ }
268
+
269
+ /**
270
+ *
271
+ * @return string
272
+ */
273
+ public function rest_uri() {
274
+ return 'wc-stripe/v1/';
275
+ }
276
+
277
+ /**
278
+ *
279
+ * @return string
280
+ */
281
+ public function rest_url() {
282
+ return get_rest_url( null, $this->rest_uri() );
283
+ }
284
+
285
+ /**
286
+ *
287
+ * @return WC_Stripe_Frontend_Scripts
288
+ */
289
+ public function scripts() {
290
+ if ( is_null( $this->scripts ) ) {
291
+ $this->scripts = new WC_Stripe_Frontend_Scripts();
292
+ }
293
+
294
+ return $this->scripts;
295
+ }
296
+
297
+ public function payment_gateways() {
298
+ return $this->payment_gateways;
299
+ }
300
+
301
+ /**
302
+ * Schedule actions required by the plugin
303
+ * @since 3.1.6
304
+ */
305
+ public function scheduled_actions() {
306
+ if ( function_exists( 'WC' ) ) {
307
+ if ( ! WC()->queue()->get_next( 'wc_stripe_remove_order_locks' ) ) {
308
+ WC()->queue()->schedule_recurring( strtotime( 'today midnight' ), DAY_IN_SECONDS, 'wc_stripe_remove_order_locks' );
309
+ }
310
+ }
311
+ }
312
+
313
+ /**
314
+ * @param string $type
315
+ *
316
+ * @return bool
317
+ * @since 3.1.9
318
+ */
319
+ public function is_request( $type ) {
320
+ if ( ! did_action( 'before_woocommerce_init' ) ) {
321
+ return false;
322
+ }
323
+ switch ( $type ) {
324
+ case 'frontend':
325
+ return ( ! is_admin() || defined( 'DOING_AJAX' ) ) && ! defined( 'DOING_CRON' ) && ! WC()->is_rest_api_request();
326
+ default:
327
+ return true;
328
+ }
329
+ }
330
+ }
331
+
332
+ /**
333
+ * Returns the global instance of the WC_Stripe_Manager.
334
+ *
335
+ * @return WC_Stripe_Manager
336
+ * @package Stripe/Functions
337
+ */
338
+ function wc_stripe() {
339
+ return WC_Stripe_Manager::instance();
340
+ }
341
+
342
+ // load singleton
343
+ wc_stripe();
includes/controllers/class-wc-stripe-controller-checkout.php CHANGED
@@ -1,309 +1,353 @@
1
- <?php
2
- defined( 'ABSPATH' ) || exit();
3
-
4
- if ( ! class_exists( 'WC_Stripe_Rest_Controller' ) ) {
5
- return;
6
- }
7
-
8
- /**
9
- *
10
- * @author PaymentPlugins
11
- * @since 3.0.0
12
- * @package Stripe/Controllers
13
- */
14
- class WC_Stripe_Controller_Checkout extends WC_Stripe_Rest_Controller {
15
-
16
- use WC_Stripe_Controller_Frontend_Trait;
17
-
18
- protected $namespace = '';
19
-
20
- private $order_review = false;
21
-
22
- /**
23
- *
24
- * @var WC_Payment_Gateway_Stripe
25
- */
26
- private $gateway = null;
27
-
28
- public function register_routes() {
29
- register_rest_route(
30
- $this->rest_uri(),
31
- 'checkout',
32
- array(
33
- 'methods' => WP_REST_Server::CREATABLE,
34
- 'callback' => array( $this, 'process_checkout' ),
35
- 'permission_callback' => '__return_true',
36
- )
37
- );
38
- register_rest_route(
39
- $this->rest_uri(),
40
- 'order-pay',
41
- array(
42
- 'methods' => WP_REST_Server::CREATABLE,
43
- 'callback' => array( $this, 'process_order_pay' ),
44
- 'permission_callback' => '__return_true',
45
- )
46
- );
47
- register_rest_route(
48
- $this->rest_uri(),
49
- 'source',
50
- array(
51
- 'methods' => WP_REST_Server::DELETABLE,
52
- 'callback' => array( $this, 'delete_source' ),
53
- 'permission_callback' => '__return_true',
54
- )
55
- );
56
- }
57
-
58
- /**
59
- * Process the WC Order
60
- *
61
- * @param WP_REST_Request $request
62
- *
63
- * @return WP_REST_Response
64
- */
65
- public function process_checkout( $request ) {
66
- $this->frontend_includes();
67
- wc_maybe_define_constant( 'DOING_AJAX', true );
68
- $this->actions();
69
- $checkout = WC()->checkout();
70
- $payment_method = $request->get_param( 'payment_method' );
71
- /**
72
- *
73
- * @var WC_Payment_Gateway_Stripe $gateway
74
- */
75
- $this->gateway = $gateway = WC()->payment_gateways()->payment_gateways()[ $payment_method ];
76
-
77
- try {
78
- do_action( 'wc_stripe_rest_process_checkout', $request, $gateway );
79
- if ( ! is_user_logged_in() ) {
80
- $this->create_customer( $request );
81
- }
82
- // set the checkout nonce so no exceptions are thrown.
83
- $_REQUEST['_wpnonce'] = $_POST['_wpnonce'] = wp_create_nonce( 'woocommerce-process_checkout' );
84
-
85
- if ( 'product' == $request->get_param( 'page_id' ) ) {
86
- wc_stripe_stash_cart( WC()->cart );
87
- $gateway->set_post_payment_process( array( $this, 'post_payment_processes' ) );
88
- add_filter( 'woocommerce_get_checkout_order_received_url', function ( $url, $order ) {
89
- return add_query_arg( 'wc_stripe_product_checkout', $order->get_payment_method(), $url );
90
- }, 10, 2 );
91
-
92
- $option = new WC_Stripe_Product_Gateway_Option( current( WC()->cart->get_cart() )['data'], $gateway );
93
- $gateway->settings['charge_type'] = $option->get_option( 'charge_type' );
94
- }
95
- $this->required_post_data();
96
- $checkout->process_checkout();
97
- } catch ( Exception $e ) {
98
- wc_add_notice( $e->getMessage(), 'error' );
99
- }
100
- if ( wc_notice_count( 'error' ) > 0 ) {
101
- return $this->send_response( false );
102
- }
103
-
104
- return $this->send_response( true );
105
- }
106
-
107
- /**
108
- *
109
- * @param WP_REST_Request $request
110
- *
111
- * @return WP_REST_Response
112
- * @since 3.1.8
113
- */
114
- public function process_order_pay( $request ) {
115
- $this->frontend_includes();
116
-
117
- global $wp;
118
-
119
- $wp->query_vars['order-pay'] = $request->get_param( 'order_id' );
120
-
121
- wc_maybe_define_constant( WC_Stripe_Constants::WOOCOMMERCE_STRIPE_ORDER_PAY, true );
122
-
123
- WC_Form_Handler::pay_action();
124
-
125
- if ( wc_notice_count( 'error' ) > 0 ) {
126
- return rest_ensure_response(
127
- array(
128
- 'success' => false,
129
- 'message' => $this->get_messages( 'error' ),
130
- )
131
- );
132
- }
133
- }
134
-
135
- /**
136
- * Deletes a source from an order if the order exists.
137
- *
138
- * @param WP_REST_Request $request
139
- *
140
- * @return WP_REST_Response
141
- * @since 3.1.7
142
- */
143
- public function delete_source( $request ) {
144
- $this->frontend_includes();
145
- $order_id = WC()->session->get( 'order_awaiting_payment', null );
146
- if ( $order_id ) {
147
- $order = wc_get_order( $order_id );
148
- $order->delete_meta_data( WC_Stripe_Constants::SOURCE_ID );
149
- $order->save();
150
- }
151
-
152
- return rest_ensure_response( array( 'success' => true ) );
153
- }
154
-
155
-
156
- /**
157
- *
158
- * @param WP_REST_Request $request
159
- */
160
- private function create_customer( $request ) {
161
- $create = WC()->checkout()->is_registration_required();
162
- // create an account for the user if it's required for things like subscriptions.
163
- if ( wcs_stripe_active() && WC_Subscriptions_Cart::cart_contains_subscription() ) {
164
- $create = true;
165
- }
166
- if ( $create ) {
167
- $password = wp_generate_password();
168
- $username = $email = $request->get_param( 'billing_email' );
169
- $result = wc_create_new_customer( $email, $username, $password );
170
- if ( $result instanceof WP_Error ) {
171
- // for email exists errors you want customer to either login or use a different email address.
172
- throw new Exception( $result->get_error_message() );
173
- }
174
- $this->customer_id = $result;
175
-
176
- // log the customer in
177
- wp_set_current_user( $this->customer_id );
178
- wc_set_customer_auth_cookie( $this->customer_id );
179
-
180
- // As we are now logged in, cart will need to refresh to receive updated nonces
181
- WC()->session->set( 'reload_checkout', true );
182
- }
183
- }
184
-
185
- private function send_response( $success ) {
186
- $reload = WC()->session->get( 'reload_checkout', false );
187
- $data = array(
188
- 'result' => $success ? 'success' : 'failure',
189
- 'messages' => $reload ? null : $this->get_error_messages(),
190
- 'reload' => $reload,
191
- );
192
- unset( WC()->session->reload_checkout );
193
-
194
- return rest_ensure_response( $data );
195
- }
196
-
197
- public function validate_payment_method( $payment_method ) {
198
- $gateways = WC()->payment_gateways()->payment_gateways();
199
-
200
- return isset( $gateways[ $payment_method ] ) ? true : new WP_Error( 'validation-error', 'Please choose a valid payment method.' );
201
- }
202
-
203
- private function actions() {
204
- add_action( 'woocommerce_after_checkout_validation', array( $this, 'after_checkout_validation' ), 10, 2 );
205
- add_action( 'woocommerce_checkout_order_processed', array( $this, 'checkout_order_processed' ), 10, 3 );
206
- add_action( 'woocommerce_checkout_posted_data', array( $this, 'filter_posted_data' ) );
207
- }
208
-
209
- /**
210
- *
211
- * @param WC_Order $order
212
- * @param WC_Payment_Gateway_Stripe $gateway
213
- */
214
- public function set_stashed_cart( $order, $gateway ) {
215
- wc_stripe_restore_cart( WC()->cart );
216
- }
217
-
218
- /**
219
- *
220
- * @param array $data
221
- * @param WP_Error $errors
222
- */
223
- public function after_checkout_validation( $data, $errors ) {
224
- if ( $errors->get_error_message( 'required-field' ) ) {
225
- wc_add_notice(
226
- apply_filters(
227
- 'wc_stripe_after_checkout_validation_notice',
228
- sprintf(
229
- __( 'Some required fields were missing. Please click %1$shere%2$s to complete your payment.', 'woo-stripe-payment' ),
230
- '<a href="' .
231
- $this->get_order_review_url() . '">',
232
- '</a>'
233
- ),
234
- $data,
235
- $errors
236
- ),
237
- 'notice'
238
- );
239
- wp_send_json(
240
- array(
241
- 'result' => 'failure',
242
- 'messages' => $this->get_messages( 'notice' ),
243
- 'reload' => false,
244
- ),
245
- 200
246
- );
247
- }
248
- }
249
-
250
- private function required_post_data() {
251
- if ( WC()->cart->needs_shipping() ) {
252
- $_POST['ship_to_different_address'] = true;
253
- }
254
- if ( wc_get_page_id( 'terms' ) > 0 ) {
255
- $_POST['terms'] = 1;
256
- }
257
- }
258
-
259
- private function get_order_review_url() {
260
- return add_query_arg(
261
- array(
262
- 'order_review' => 'true',
263
- 'payment_method' => $this->gateway->id,
264
- 'payment_nonce' => $this->gateway->get_payment_source(),
265
- ),
266
- wc_get_checkout_url()
267
- );
268
- }
269
-
270
- /**
271
- *
272
- * @param int $order_id
273
- * @param array $posted_data
274
- * @param WC_Order $order
275
- */
276
- public function checkout_order_processed( $order_id, $posted_data, $order ) {
277
- if ( $this->order_review ) {
278
- wc_add_notice( __( 'Please review your order details then click Place Order.', 'woo-stripe-payment' ), 'notice' );
279
- wp_send_json(
280
- array(
281
- 'result' => 'success',
282
- 'redirect' => $this->get_order_review_url(),
283
- ),
284
- 200
285
- );
286
- }
287
- }
288
-
289
- public function post_payment_processes( $order, $gateway ) {
290
- wc_stripe_restore_cart( WC()->cart );
291
- $data = WC()->session->get( 'wc_stripe_cart', array() );
292
- unset( $data['product_cart'] );
293
- WC()->session->set( 'wc_stripe_cart', $data );
294
- }
295
-
296
- /**
297
- * @param $data
298
- *
299
- * @return mixed
300
- * @since 3.2.1
301
- */
302
- public function filter_posted_data( $data ) {
303
- if ( isset( $data['shipping_method'], $data['shipping_country'], $data['shipping_state'] ) ) {
304
- $data['shipping_state'] = wc_stripe_filter_address_state( $data['shipping_state'], $data['shipping_country'] );
305
- }
306
-
307
- return $data;
308
- }
309
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ defined( 'ABSPATH' ) || exit();
3
+
4
+ if ( ! class_exists( 'WC_Stripe_Rest_Controller' ) ) {
5
+ return;
6
+ }
7
+
8
+ /**
9
+ *
10
+ * @author PaymentPlugins
11
+ * @since 3.0.0
12
+ * @package Stripe/Controllers
13
+ */
14
+ class WC_Stripe_Controller_Checkout extends WC_Stripe_Rest_Controller {
15
+
16
+ use WC_Stripe_Controller_Frontend_Trait;
17
+
18
+ protected $namespace = '';
19
+
20
+ private $order_review = false;
21
+
22
+ /**
23
+ *
24
+ * @var WC_Payment_Gateway_Stripe
25
+ */
26
+ private $gateway = null;
27
+
28
+ public function register_routes() {
29
+ register_rest_route(
30
+ $this->rest_uri(),
31
+ 'checkout',
32
+ array(
33
+ 'methods' => WP_REST_Server::CREATABLE,
34
+ 'callback' => array( $this, 'process_checkout' ),
35
+ 'permission_callback' => '__return_true',
36
+ )
37
+ );
38
+ register_rest_route(
39
+ $this->rest_uri(),
40
+ 'checkout/payment',
41
+ array(
42
+ 'methods' => WP_REST_Server::CREATABLE,
43
+ 'callback' => array( $this, 'process_payment' ),
44
+ 'permission_callback' => '__return_true',
45
+ )
46
+ );
47
+ register_rest_route(
48
+ $this->rest_uri(),
49
+ 'order-pay',
50
+ array(
51
+ 'methods' => WP_REST_Server::CREATABLE,
52
+ 'callback' => array( $this, 'process_order_pay' ),
53
+ 'permission_callback' => '__return_true',
54
+ )
55
+ );
56
+ register_rest_route(
57
+ $this->rest_uri(),
58
+ 'source',
59
+ array(
60
+ 'methods' => WP_REST_Server::DELETABLE,
61
+ 'callback' => array( $this, 'delete_source' ),
62
+ 'permission_callback' => '__return_true',
63
+ )
64
+ );
65
+ }
66
+
67
+ /**
68
+ * Process the WC Order
69
+ *
70
+ * @param WP_REST_Request $request
71
+ *
72
+ * @return WP_REST_Response
73
+ */
74
+ public function process_checkout( $request ) {
75
+ $this->frontend_includes();
76
+ wc_maybe_define_constant( 'DOING_AJAX', true );
77
+ $this->actions();
78
+ $checkout = WC()->checkout();
79
+ $payment_method = $request->get_param( 'payment_method' );
80
+ /**
81
+ *
82
+ * @var WC_Payment_Gateway_Stripe $gateway
83
+ */
84
+ $this->gateway = $gateway = WC()->payment_gateways()->payment_gateways()[ $payment_method ];
85
+
86
+ try {
87
+ do_action( 'wc_stripe_rest_process_checkout', $request, $gateway );
88
+ if ( ! is_user_logged_in() ) {
89
+ $this->create_customer( $request );
90
+ }
91
+ // set the checkout nonce so no exceptions are thrown.
92
+ $_REQUEST['_wpnonce'] = $_POST['_wpnonce'] = wp_create_nonce( 'woocommerce-process_checkout' );
93
+
94
+ if ( 'product' == $request->get_param( 'page_id' ) ) {
95
+ wc_stripe_stash_cart( WC()->cart );
96
+ $gateway->set_post_payment_process( array( $this, 'post_payment_processes' ) );
97
+ add_filter( 'woocommerce_get_checkout_order_received_url', function ( $url, $order ) {
98
+ return add_query_arg( 'wc_stripe_product_checkout', $order->get_payment_method(), $url );
99
+ }, 10, 2 );
100
+
101
+ $option = new WC_Stripe_Product_Gateway_Option( current( WC()->cart->get_cart() )['data'], $gateway );
102
+ $gateway->settings['charge_type'] = $option->get_option( 'charge_type' );
103
+ }
104
+ $this->required_post_data();
105
+ $checkout->process_checkout();
106
+ } catch ( Exception $e ) {
107
+ wc_add_notice( $e->getMessage(), 'error' );
108
+ }
109
+ if ( wc_notice_count( 'error' ) > 0 ) {
110
+ return $this->send_response( false );
111
+ }
112
+
113
+ return $this->send_response( true );
114
+ }
115
+
116
+ /**
117
+ * @param WP_REST_Request $request
118
+ *
119
+ * @since 3.2.3
120
+ */
121
+ public function process_payment( $request ) {
122
+ wc_maybe_define_constant( 'DOING_AJAX', true );
123
+ wc_maybe_define_constant( 'WOOCOMMERCE_CHECKOUT', true );
124
+ $this->frontend_includes();;
125
+ try {
126
+ if ( ! isset( $request['wp_rest_nonce'] ) || ! wp_verify_nonce( $request['wp_rest_nonce'], 'wp_rest' ) ) {
127
+ throw new Exception( 'You are not authorized.' );
128
+ }
129
+ $order_id = absint( WC()->session->get( 'order_awaiting_payment' ) );
130
+ $order = wc_get_order( $order_id );
131
+
132
+ /**
133
+ * @var WC_Payment_Gateway_Stripe $payment_method
134
+ */
135
+ $payment_method = WC()->payment_gateways()->payment_gateways()[ $order->get_payment_method() ];
136
+
137
+ $result = $payment_method->process_payment( $order_id );
138
+
139
+ if ( isset( $result['result'] ) && 'success' === $result['result'] ) {
140
+ return $this->send_response( true, $result );
141
+ }
142
+
143
+ return $this->send_response( false, $result );
144
+ } catch ( Exception $e ) {
145
+ wc_add_notice( $e->getMessage(), 'error' );
146
+
147
+ return $this->send_response( false );
148
+ }
149
+ }
150
+
151
+ /**
152
+ *
153
+ * @param WP_REST_Request $request
154
+ *
155
+ * @return WP_REST_Response
156
+ * @since 3.1.8
157
+ */
158
+ public function process_order_pay( $request ) {
159
+ $this->frontend_includes();
160
+
161
+ global $wp;
162
+
163
+ $wp->query_vars['order-pay'] = $request->get_param( 'order_id' );
164
+
165
+ wc_maybe_define_constant( WC_Stripe_Constants::WOOCOMMERCE_STRIPE_ORDER_PAY, true );
166
+
167
+ WC_Form_Handler::pay_action();
168
+
169
+ if ( wc_notice_count( 'error' ) > 0 ) {
170
+ return rest_ensure_response(
171
+ array(
172
+ 'success' => false,
173
+ 'message' => $this->get_messages( 'error' ),
174
+ )
175
+ );
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Deletes a source from an order if the order exists.
181
+ *
182
+ * @param WP_REST_Request $request
183
+ *
184
+ * @return WP_REST_Response
185
+ * @since 3.1.7
186
+ */
187
+ public function delete_source( $request ) {
188
+ $this->frontend_includes();
189
+ $order_id = WC()->session->get( 'order_awaiting_payment', null );
190
+ if ( $order_id ) {
191
+ $order = wc_get_order( $order_id );
192
+ $order->delete_meta_data( WC_Stripe_Constants::SOURCE_ID );
193
+ $order->save();
194
+ }
195
+
196
+ return rest_ensure_response( array( 'success' => true ) );
197
+ }
198
+
199
+
200
+ /**
201
+ *
202
+ * @param WP_REST_Request $request
203
+ */
204
+ private function create_customer( $request ) {
205
+ $create = WC()->checkout()->is_registration_required();
206
+ // create an account for the user if it's required for things like subscriptions.
207
+ if ( wcs_stripe_active() && WC_Subscriptions_Cart::cart_contains_subscription() ) {
208
+ $create = true;
209
+ }
210
+ if ( $create ) {
211
+ $password = wp_generate_password();
212
+ $username = $email = $request->get_param( 'billing_email' );
213
+ $result = wc_create_new_customer( $email, $username, $password );
214
+ if ( $result instanceof WP_Error ) {
215
+ // for email exists errors you want customer to either login or use a different email address.
216
+ throw new Exception( $result->get_error_message() );
217
+ }
218
+ $this->customer_id = $result;
219
+
220
+ // log the customer in
221
+ wp_set_current_user( $this->customer_id );
222
+ wc_set_customer_auth_cookie( $this->customer_id );
223
+
224
+ // As we are now logged in, cart will need to refresh to receive updated nonces
225
+ WC()->session->set( 'reload_checkout', true );
226
+ }
227
+ }
228
+
229
+ private function send_response( $success, $defaults = array() ) {
230
+ $reload = WC()->session->get( 'reload_checkout', false );
231
+ $data = wp_parse_args( $defaults, array(
232
+ 'result' => $success ? 'success' : 'failure',
233
+ 'messages' => $reload ? null : $this->get_error_messages(),
234
+ 'reload' => $reload,
235
+ ) );
236
+ unset( WC()->session->reload_checkout );
237
+
238
+ return rest_ensure_response( $data );
239
+ }
240
+
241
+ public function validate_payment_method( $payment_method ) {
242
+ $gateways = WC()->payment_gateways()->payment_gateways();
243
+
244
+ return isset( $gateways[ $payment_method ] ) ? true : new WP_Error( 'validation-error', 'Please choose a valid payment method.' );
245
+ }
246
+
247
+ private function actions() {
248
+ add_action( 'woocommerce_after_checkout_validation', array( $this, 'after_checkout_validation' ), 10, 2 );
249
+ add_action( 'woocommerce_checkout_order_processed', array( $this, 'checkout_order_processed' ), 10, 3 );
250
+ add_action( 'woocommerce_checkout_posted_data', array( $this, 'filter_posted_data' ) );
251
+ }
252
+
253
+ /**
254
+ *
255
+ * @param WC_Order $order
256
+ * @param WC_Payment_Gateway_Stripe $gateway
257
+ */
258
+ public function set_stashed_cart( $order, $gateway ) {
259
+ wc_stripe_restore_cart( WC()->cart );
260
+ }
261
+
262
+ /**
263
+ *
264
+ * @param array $data
265
+ * @param WP_Error $errors
266
+ */
267
+ public function after_checkout_validation( $data, $errors ) {
268
+ if ( $errors->get_error_message( 'required-field' ) ) {
269
+ wc_add_notice(
270
+ apply_filters(
271
+ 'wc_stripe_after_checkout_validation_notice',
272
+ sprintf(
273
+ __( 'Some required fields were missing. Please click %1$shere%2$s to complete your payment.', 'woo-stripe-payment' ),
274
+ '<a href="' .
275
+ $this->get_order_review_url() . '">',
276
+ '</a>'
277
+ ),
278
+ $data,
279
+ $errors
280
+ ),
281
+ 'notice'
282
+ );
283
+ wp_send_json(
284
+ array(
285
+ 'result' => 'failure',
286
+ 'messages' => $this->get_messages( 'notice' ),
287
+ 'reload' => false,
288
+ ),
289
+ 200
290
+ );
291
+ }
292
+ }
293
+
294
+ private function required_post_data() {
295
+ if ( WC()->cart->needs_shipping() ) {
296
+ $_POST['ship_to_different_address'] = true;
297
+ }
298
+ if ( wc_get_page_id( 'terms' ) > 0 ) {
299
+ $_POST['terms'] = 1;
300
+ }
301
+ }
302
+
303
+ private function get_order_review_url() {
304
+ return add_query_arg(
305
+ array(
306
+ 'order_review' => 'true',
307
+ 'payment_method' => $this->gateway->id,
308
+ 'payment_nonce' => $this->gateway->get_payment_source(),
309
+ ),
310
+ wc_get_checkout_url()
311
+ );
312
+ }
313
+
314
+ /**
315
+ *
316
+ * @param int $order_id
317
+ * @param array $posted_data
318
+ * @param WC_Order $order
319
+ */
320
+ public function checkout_order_processed( $order_id, $posted_data, $order ) {
321
+ if ( $this->order_review ) {
322
+ wc_add_notice( __( 'Please review your order details then click Place Order.', 'woo-stripe-payment' ), 'notice' );
323
+ wp_send_json(
324
+ array(
325
+ 'result' => 'success',
326
+ 'redirect' => $this->get_order_review_url(),
327
+ ),
328
+ 200
329
+ );
330
+ }
331
+ }
332
+
333
+ public function post_payment_processes( $order, $gateway ) {
334
+ wc_stripe_restore_cart( WC()->cart );
335
+ $data = WC()->session->get( 'wc_stripe_cart', array() );
336
+ unset( $data['product_cart'] );
337
+ WC()->session->set( 'wc_stripe_cart', $data );
338
+ }
339
+
340
+ /**
341
+ * @param $data
342
+ *
343
+ * @return mixed
344
+ * @since 3.2.1
345
+ */
346
+ public function filter_posted_data( $data ) {
347
+ if ( isset( $data['shipping_method'], $data['shipping_country'], $data['shipping_state'] ) ) {
348
+ $data['shipping_state'] = wc_stripe_filter_address_state( $data['shipping_state'], $data['shipping_country'] );
349
+ }
350
+
351
+ return $data;
352
+ }
353
+ }
includes/controllers/class-wc-stripe-controller-gateway-settings.php CHANGED
@@ -1,228 +1,234 @@
1
- <?php
2
- defined( 'ABSPATH' ) || exit();
3
-
4
- /**
5
- *
6
- * @package Stripe/Controllers
7
- * @author PaymentPlugins
8
- *
9
- */
10
- class WC_Stripe_Controller_Gateway_Settings extends WC_Stripe_Rest_Controller {
11
-
12
- protected $namespace = 'gateway-settings';
13
-
14
- public function register_routes() {
15
- register_rest_route(
16
- $this->rest_uri(),
17
- 'apple-domain',
18
- array(
19
- 'methods' => WP_REST_Server::CREATABLE,
20
- 'callback' => array( $this, 'register_apple_domain' ),
21
- 'permission_callback' => array( $this, 'admin_permission_check' )
22
- )
23
- );
24
- register_rest_route(
25
- $this->rest_uri(),
26
- 'create-webook',
27
- array(
28
- 'methods' => WP_REST_Server::CREATABLE,
29
- 'callback' => array( $this, 'create_webhook' ),
30
- 'permission_callback' => array( $this, 'admin_permission_check' )
31
- )
32
- );
33
- register_rest_route(
34
- $this->rest_uri(),
35
- 'connection-test',
36
- array(
37
- 'methods' => WP_REST_Server::CREATABLE,
38
- 'callback' => array( $this, 'connection_test' ),
39
- 'permission_callback' => array( $this, 'admin_permission_check' )
40
- )
41
- );
42
- }
43
-
44
- /**
45
- * Register the site domain with Stripe for Apple Pay.
46
- *
47
- * @param WP_REST_Request $request
48
- */
49
- public function register_apple_domain( $request ) {
50
- $gateway = WC_Stripe_Gateway::load();
51
-
52
- // try to add domain association file.
53
- if ( isset( $_SERVER['DOCUMENT_ROOT'] ) ) {
54
- $path = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . '.well-known';
55
- $file = $path . DIRECTORY_SEPARATOR . 'apple-developer-merchantid-domain-association';
56
- if ( ! file_exists( $file ) ) {
57
- require_once( ABSPATH . '/wp-admin/includes/file.php' );
58
- if ( function_exists( 'WP_Filesystem' ) && ( WP_Filesystem() ) ) {
59
- /**
60
- *
61
- * @var WP_Filesystem_Base $wp_filesystem
62
- */
63
- global $wp_filesystem;
64
- if ( ! $wp_filesystem->is_dir( $path ) ) {
65
- $wp_filesystem->mkdir( $path );
66
- }
67
- $contents = $wp_filesystem->get_contents( WC_STRIPE_PLUGIN_FILE_PATH . 'apple-developer-merchantid-domain-association' );
68
- $wp_filesystem->put_contents( $file, $contents, 0755 );
69
- }
70
- }
71
- }
72
- $server_name = $_SERVER['SERVER_NAME'];
73
- if ( strstr( $server_name, 'www.' ) ) {
74
- $server_name_2 = str_replace( 'www.', '', $server_name );
75
- } else {
76
- $server_name_2 = 'www.' . $server_name;
77
- }
78
- $domains = array( $server_name, $server_name_2 );
79
- try {
80
- $api_key = wc_stripe_get_secret_key( 'live' );
81
- if ( empty( $api_key ) ) {
82
- throw new Exception( __( 'You cannot register your domain until you have configured your Live API keys.', 'woo-stripe-payment' ) );
83
- }
84
- // fetch the Apple domains
85
- $registered_domains = $gateway->applePayDomains->mode( 'live' )->all( array( 'limit' => 50 ) );
86
- if ( ! is_wp_error( $registered_domains ) && $registered_domains ) {
87
- // loop through domains and delete if they match domain of site.
88
- foreach ( $registered_domains->data as $domain ) {
89
- if ( in_array( $domain->domain_name, $domains ) ) {
90
- $gateway->applePayDomains->mode( 'live' )->delete( $domain->id );
91
- }
92
- }
93
- }
94
- $failures = 0;
95
- foreach ( $domains as $domain ) {
96
- $result = $gateway->applePayDomains->mode( 'live' )->create( array( 'domain_name' => $domain ) );
97
- if ( is_wp_error( $result ) ) {
98
- $failures ++;
99
- if ( $failures > 1 ) {
100
- throw new Exception( $result->get_error_message() );
101
- }
102
- }
103
- }
104
- } catch ( Exception $e ) {
105
- return new WP_Error( 'domain-error', $e->getMessage(), array( 'status' => 200 ) );
106
- }
107
-
108
- return rest_ensure_response(
109
- array(
110
- 'message' => sprintf(
111
- __(
112
- 'Domain registered successfully. You can confirm in your Stripe Dashboard at https://dashboard.stripe.com/account/apple_pay.',
113
- 'woo-stripe-payment'
114
- )
115
- ),
116
- )
117
- );
118
- }
119
-
120
- /**
121
- * Create a Stripe webhook for the site.
122
- *
123
- * @param WP_REST_Request $request
124
- */
125
- public function create_webhook( $request ) {
126
- $url = wc_stripe()->rest_api->webhook->rest_url( 'webhook' );
127
- $api_settings = wc_stripe()->api_settings;
128
- $env = $request->get_param( 'environment' );
129
- $gateway = new WC_Stripe_Gateway( $env );
130
- // first fetch all webhooks
131
- $private_key = wc_stripe_get_secret_key( $env );
132
- if ( empty( $private_key ) ) {
133
- return new WP_Error(
134
- 'webhook-error',
135
- __( 'You must configure your secret key before creating webhooks.', 'woo-stripe-payment' ),
136
- array(
137
- 'status' => 200,
138
- )
139
- );
140
- }
141
- $webhooks = $gateway->webhookEndpoints->all( array( 'limit' => 100 ) );
142
- if ( ! is_wp_error( $webhooks ) ) {
143
- // validate that the webhook hasn't already been created.
144
- foreach ( $webhooks->data as $webhook ) {
145
- if ( $webhook['url'] === $url ) {
146
- return new WP_Error(
147
- 'webhook-error',
148
- __( 'There is already a webhook configured for this site. If you want to delete the webhook, login to your Stripe Dashboard.', 'woo-stripe-payment' ),
149
- array(
150
- 'status' => 200,
151
- )
152
- );
153
- }
154
- }
155
- }
156
-
157
- // create the webhooks and save it to the api settings.
158
- $webhook = $gateway->webhookEndpoints->create(
159
- array(
160
- 'url' => $url,
161
- 'enabled_events' => apply_filters(
162
- 'wc_stripe_webhook_events',
163
- array(
164
- 'charge.failed',
165
- 'charge.succeeded',
166
- 'source.chargeable',
167
- 'payment_intent.succeeded',
168
- )
169
- ),
170
- )
171
- );
172
- if ( is_wp_error( $webhook ) ) {
173
- return new WP_Error( $webhook->get_error_code(), $webhook->get_error_message(), array( 'status' => 200 ) );
174
- } else {
175
- $api_settings->update_option( "webhook_url_{$env}", $webhook['url'] );
176
- $api_settings->update_option( "webhook_secret_{$env}", $webhook['secret'] );
177
- $api_settings->update_option( "webhook_id_{$env}", $webhook['id'] );
178
-
179
- return rest_ensure_response(
180
- array(
181
- 'message' => sprintf(
182
- __( 'Webhook created in Stripe for %s environment. You can test your webhook by logging in to the Stripe dashboard', 'woo-stripe-payment' ),
183
- 'live' ==
184
- $env ? __( 'Live', 'woo-stripe-payment' ) : __( 'Test', 'woo-stripe-payment' )
185
- ),
186
- 'secret' => $webhook['secret'],
187
- )
188
- );
189
- }
190
- }
191
-
192
- /**
193
- * Perform a connection test
194
- *
195
- * @param WP_REST_Request $request
196
- */
197
- public function connection_test( $request ) {
198
- $mode = $request->get_param( 'mode' );
199
-
200
- try {
201
- // test the secret key
202
- $response = WC_Stripe_Gateway::load()->customers->mode( $mode )->all( array( 'limit' => 1 ) );
203
-
204
- if ( is_wp_error( $response ) ) {
205
- throw new Exception( sprintf( __( 'Mode: %s. Invalid secret key. Please check your entry.', 'woo-stripe-payment' ), $mode ) );
206
- }
207
-
208
- // test the publishable key
209
- $response = wp_remote_post(
210
- 'https://api.stripe.com/v1/payment_methods',
211
- array(
212
- 'headers' => array( 'Content-Type' => 'application/x-www-form-urlencoded' ),
213
- 'body' => array( 'key' => wc_stripe_get_publishable_key( $mode ) ),
214
- )
215
- );
216
- if ( is_wp_error( $response ) ) {
217
- throw new Exception( sprintf( __( 'Mode: %s. Invalid publishable key. Please check your entry.', 'woo-stripe-payment' ), $mode ) );
218
- }
219
- if ( $response['response']['code'] == 401 ) {
220
- throw new Exception( sprintf( __( 'Mode: %s. Invalid publishable key. Please check your entry.', 'woo-stripe-payment' ), $mode ) );
221
- }
222
- } catch ( Exception $e ) {
223
- return new WP_Error( 'connection-failure', $e->getMessage(), array( 'status' => 200 ) );
224
- }
225
-
226
- return rest_ensure_response( array( 'message' => sprintf( __( 'Connection test to Stripe was successful. Mode: %s.', 'woo-stripe-payment' ), $mode ) ) );
227
- }
228
- }
 
 
 
 
 
 
1
+ <?php
2
+ defined( 'ABSPATH' ) || exit();
3
+
4
+ /**
5
+ *
6
+ * @package Stripe/Controllers
7
+ * @author PaymentPlugins
8
+ *
9
+ */
10
+ class WC_Stripe_Controller_Gateway_Settings extends WC_Stripe_Rest_Controller {
11
+
12
+ protected $namespace = 'gateway-settings';
13
+
14
+ public function register_routes() {
15
+ register_rest_route(
16
+ $this->rest_uri(),
17
+ 'apple-domain',
18
+ array(
19
+ 'methods' => WP_REST_Server::CREATABLE,
20
+ 'callback' => array( $this, 'register_apple_domain' ),
21
+ 'permission_callback' => function () {
22
+ if ( current_user_can( 'manage_woocommerce' ) ) {
23
+ return true;
24
+ }
25
+
26
+ return new WP_Error( 'permission-error', __( 'You do not have permissions to access this resource.', 'woo-stripe-payment' ), array( 'status' => 403 ) );
27
+ }
28
+ )
29
+ );
30
+ register_rest_route(
31
+ $this->rest_uri(),
32
+ 'create-webook',
33
+ array(
34
+ 'methods' => WP_REST_Server::CREATABLE,
35
+ 'callback' => array( $this, 'create_webhook' ),
36
+ 'permission_callback' => array( $this, 'admin_permission_check' )
37
+ )
38
+ );
39
+ register_rest_route(
40
+ $this->rest_uri(),
41
+ 'connection-test',
42
+ array(
43
+ 'methods' => WP_REST_Server::CREATABLE,
44
+ 'callback' => array( $this, 'connection_test' ),
45
+ 'permission_callback' => array( $this, 'admin_permission_check' )
46
+ )
47
+ );
48
+ }
49
+
50
+ /**
51
+ * Register the site domain with Stripe for Apple Pay.
52
+ *
53
+ * @param WP_REST_Request $request
54
+ */
55
+ public function register_apple_domain( $request ) {
56
+ $gateway = WC_Stripe_Gateway::load();
57
+
58
+ // try to add domain association file.
59
+ if ( isset( $_SERVER['DOCUMENT_ROOT'] ) ) {
60
+ $path = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . '.well-known';
61
+ $file = $path . DIRECTORY_SEPARATOR . 'apple-developer-merchantid-domain-association';
62
+ if ( ! file_exists( $file ) ) {
63
+ require_once( ABSPATH . '/wp-admin/includes/file.php' );
64
+ if ( function_exists( 'WP_Filesystem' ) && ( WP_Filesystem() ) ) {
65
+ /**
66
+ *
67
+ * @var WP_Filesystem_Base $wp_filesystem
68
+ */
69
+ global $wp_filesystem;
70
+ if ( ! $wp_filesystem->is_dir( $path ) ) {
71
+ $wp_filesystem->mkdir( $path );
72
+ }
73
+ $contents = $wp_filesystem->get_contents( WC_STRIPE_PLUGIN_FILE_PATH . 'apple-developer-merchantid-domain-association' );
74
+ $wp_filesystem->put_contents( $file, $contents, 0755 );
75
+ }
76
+ }
77
+ }
78
+ $server_name = $_SERVER['SERVER_NAME'];
79
+ if ( strstr( $server_name, 'www.' ) ) {
80
+ $server_name_2 = str_replace( 'www.', '', $server_name );
81
+ } else {
82
+ $server_name_2 = 'www.' . $server_name;
83
+ }
84
+ $domains = array( $server_name, $server_name_2 );
85
+ try {
86
+ $api_key = wc_stripe_get_secret_key( 'live' );
87
+ if ( empty( $api_key ) ) {
88
+ throw new Exception( __( 'You cannot register your domain until you have configured your Live API keys.', 'woo-stripe-payment' ) );
89
+ }
90
+ // fetch the Apple domains
91
+ $registered_domains = $gateway->applePayDomains->mode( 'live' )->all( array( 'limit' => 50 ) );
92
+ if ( ! is_wp_error( $registered_domains ) && $registered_domains ) {
93
+ // loop through domains and delete if they match domain of site.
94
+ foreach ( $registered_domains->data as $domain ) {
95
+ if ( in_array( $domain->domain_name, $domains ) ) {
96
+ $gateway->applePayDomains->mode( 'live' )->delete( $domain->id );
97
+ }
98
+ }
99
+ }
100
+ $failures = 0;
101
+ foreach ( $domains as $domain ) {
102
+ $result = $gateway->applePayDomains->mode( 'live' )->create( array( 'domain_name' => $domain ) );
103
+ if ( is_wp_error( $result ) ) {
104
+ $failures ++;
105
+ if ( $failures > 1 ) {
106
+ throw new Exception( $result->get_error_message() );
107
+ }
108
+ }
109
+ }
110
+ } catch ( Exception $e ) {
111
+ return new WP_Error( 'domain-error', $e->getMessage(), array( 'status' => 200 ) );
112
+ }
113
+
114
+ return rest_ensure_response(
115
+ array(
116
+ 'message' => sprintf(
117
+ __(
118
+ 'Domain registered successfully. You can confirm in your Stripe Dashboard at https://dashboard.stripe.com/account/apple_pay.',
119
+ 'woo-stripe-payment'
120
+ )
121
+ ),
122
+ )
123
+ );
124
+ }
125
+
126
+ /**
127
+ * Create a Stripe webhook for the site.
128
+ *
129
+ * @param WP_REST_Request $request
130
+ */
131
+ public function create_webhook( $request ) {
132
+ $url = wc_stripe()->rest_api->webhook->rest_url( 'webhook' );
133
+ $api_settings = wc_stripe()->api_settings;
134
+ $env = $request->get_param( 'environment' );
135
+ $gateway = new WC_Stripe_Gateway( $env );
136
+ // first fetch all webhooks
137
+ $private_key = wc_stripe_get_secret_key( $env );
138
+ if ( empty( $private_key ) ) {
139
+ return new WP_Error(
140
+ 'webhook-error',
141
+ __( 'You must configure your secret key before creating webhooks.', 'woo-stripe-payment' ),
142
+ array(
143
+ 'status' => 200,
144
+ )
145
+ );
146
+ }
147
+ $webhooks = $gateway->webhookEndpoints->all( array( 'limit' => 100 ) );
148
+ if ( ! is_wp_error( $webhooks ) ) {
149
+ // validate that the webhook hasn't already been created.
150
+ foreach ( $webhooks->data as $webhook ) {
151
+ if ( $webhook['url'] === $url ) {
152
+ return new WP_Error(
153
+ 'webhook-error',
154
+ __( 'There is already a webhook configured for this site. If you want to delete the webhook, login to your Stripe Dashboard.', 'woo-stripe-payment' ),
155
+ array(
156
+ 'status' => 200,
157
+ )
158
+ );
159
+ }
160
+ }
161
+ }
162
+
163
+ // create the webhooks and save it to the api settings.
164
+ $webhook = $gateway->webhookEndpoints->create(
165
+ array(
166
+ 'url' => $url,
167
+ 'enabled_events' => apply_filters(
168
+ 'wc_stripe_webhook_events',
169
+ array(
170
+ 'charge.failed',
171
+ 'charge.succeeded',
172
+ 'source.chargeable',
173
+ 'payment_intent.succeeded',
174
+ )
175
+ ),
176
+ )
177
+ );
178
+ if ( is_wp_error( $webhook ) ) {
179
+ return new WP_Error( $webhook->get_error_code(), $webhook->get_error_message(), array( 'status' => 200 ) );
180
+ } else {
181
+ $api_settings->update_option( "webhook_url_{$env}", $webhook['url'] );
182
+ $api_settings->update_option( "webhook_secret_{$env}", $webhook['secret'] );
183
+ $api_settings->update_option( "webhook_id_{$env}", $webhook['id'] );
184
+
185
+ return rest_ensure_response(
186
+ array(
187
+ 'message' => sprintf(
188
+ __( 'Webhook created in Stripe for %s environment. You can test your webhook by logging in to the Stripe dashboard', 'woo-stripe-payment' ),
189
+ 'live' ==
190
+ $env ? __( 'Live', 'woo-stripe-payment' ) : __( 'Test', 'woo-stripe-payment' )
191
+ ),
192
+ 'secret' => $webhook['secret'],
193
+ )
194
+ );
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Perform a connection test
200
+ *
201
+ * @param WP_REST_Request $request
202
+ */
203
+ public function connection_test( $request ) {
204
+ $mode = $request->get_param( 'mode' );
205
+
206
+ try {
207
+ // test the secret key
208
+ $response = WC_Stripe_Gateway::load()->customers->mode( $mode )->all( array( 'limit' => 1 ) );
209
+
210
+ if ( is_wp_error( $response ) ) {
211
+ throw new Exception( sprintf( __( 'Mode: %s. Invalid secret key. Please check your entry.', 'woo-stripe-payment' ), $mode ) );
212
+ }
213
+
214
+ // test the publishable key
215
+ $response = wp_remote_post(
216
+ 'https://api.stripe.com/v1/payment_methods',
217
+ array(
218
+ 'headers' => array( 'Content-Type' => 'application/x-www-form-urlencoded' ),
219
+ 'body' => array( 'key' => wc_stripe_get_publishable_key( $mode ) ),
220
+ )
221
+ );
222
+ if ( is_wp_error( $response ) ) {
223
+ throw new Exception( sprintf( __( 'Mode: %s. Invalid publishable key. Please check your entry.', 'woo-stripe-payment' ), $mode ) );
224
+ }
225
+ if ( $response['response']['code'] == 401 ) {
226
+ throw new Exception( sprintf( __( 'Mode: %s. Invalid publishable key. Please check your entry.', 'woo-stripe-payment' ), $mode ) );
227
+ }
228
+ } catch ( Exception $e ) {
229
+ return new WP_Error( 'connection-failure', $e->getMessage(), array( 'status' => 200 ) );
230
+ }
231
+
232
+ return rest_ensure_response( array( 'message' => sprintf( __( 'Connection test to Stripe was successful. Mode: %s.', 'woo-stripe-payment' ), $mode ) ) );
233
+ }
234
+ }
includes/gateways/class-wc-payment-gateway-stripe-cc.php CHANGED
@@ -1,173 +1,176 @@
1
- <?php
2
- defined( 'ABSPATH' ) || exit();
3
-
4
- /**
5
- *
6
- * @since 3.0.0
7
- * @package Stripe/Gateways
8
- * @author User
9
- *
10
- */
11
- class WC_Payment_Gateway_Stripe_CC extends WC_Payment_Gateway_Stripe {
12
-
13
- use WC_Stripe_Payment_Intent_Trait;
14
-
15
- protected $payment_method_type = 'card';
16
-
17
- public function __construct() {
18
- $this->id = 'stripe_cc';
19
- $this->tab_title = __( 'Credit Cards', 'woo-stripe-payment' );
20
- $this->template_name = 'credit-card.php';
21
- $this->token_type = 'Stripe_CC';
22
- $this->method_title = __( 'Stripe Credit Cards', 'woo-stripe-payment' );
23
- $this->method_description = __( 'Credit card gateway that integrates with your Stripe account.', 'woo-stripe-payment' );
24
- parent::__construct();
25
- }
26
-
27
- public function get_icon() {
28
- return wc_stripe_get_template(
29
- 'card-icons.php',
30
- array(
31
- 'cards' => $this->get_option( 'cards' ),
32
- 'style' => $this->get_option( 'icon_style' ),
33
- )
34
- );
35
- }
36
-
37
- public function enqueue_checkout_scripts( $scripts ) {
38
- $scripts->enqueue_script(
39
- 'credit-card',
40
- $scripts->assets_url( 'js/frontend/credit-card.js' ),
41
- array(
42
- $scripts->prefix . 'external',
43
- $scripts->prefix . 'wc-stripe',
44
- )
45
- );
46
- $scripts->localize_script( 'credit-card', $this->get_localized_params() );
47
- }
48
-
49
- public function get_localized_params() {
50
- $data = parent::get_localized_params();
51
- return array_merge(
52
- $data,
53
- array(
54
- 'style' => $this->get_form_style(),
55
- 'elementOptions' => $this->get_element_options(),
56
- 'custom_form' => $this->is_custom_form_active(),
57
- 'html' => array( 'card_brand' => sprintf( '<img id="wc-stripe-card" src="%s" />', $this->get_custom_form()['cardBrand'] ) ),
58
- 'cards' => array(
59
- 'visa' => wc_stripe()->assets_url( 'img/cards/visa.svg' ),
60
- 'amex' => wc_stripe()->assets_url( 'img/cards/amex.svg' ),
61
- 'mastercard' => wc_stripe()->assets_url( 'img/cards/mastercard.svg' ),
62
- 'discover' => wc_stripe()->assets_url( 'img/cards/discover.svg' ),
63
- 'diners' => wc_stripe()->assets_url( 'img/cards/diners.svg' ),
64
- 'jcb' => wc_stripe()->assets_url( 'img/cards/jcb.svg' ),
65
- 'unionpay' => wc_stripe()->assets_url( 'img/cards/china_union_pay.svg' ),
66
- 'unknown' => $this->get_custom_form()['cardBrand'],
67
- ),
68
- 'postal_regex' => $this->get_postal_code_regex(),
69
- )
70
- );
71
- }
72
-
73
- private function get_form_style() {
74
- if ( $this->is_custom_form_active() ) {
75
- $style = $this->get_custom_form()['elementStyles'];
76
- } else {
77
- $style = array(
78
- 'base' => array(
79
- 'color' => '#32325d',
80
- 'fontFamily' => '"Helvetica Neue", Helvetica, sans-serif',
81
- 'fontSmoothing' => 'antialiased',
82
- 'fontSize' => '18px',
83
- '::placeholder' => array( 'color' => '#aab7c4' ),
84
- ':focus' => array(),
85
- ),
86
- 'invalid' => array(
87
- 'color' => '#fa755a',
88
- 'iconColor' => '#fa755a',
89
- ),
90
- );
91
- }
92
- return apply_filters( 'wc_stripe_cc_element_style', $style );
93
- }
94
-
95
- private function get_custom_form() {
96
- return wc_stripe_get_custom_forms()[ $this->get_option( 'custom_form' ) ];
97
- }
98
-
99
- private function get_element_options() {
100
- return $this->get_custom_form()['elementOptions'];
101
- }
102
-
103
- /**
104
- * Returns true if custom forms are enabled.
105
- *
106
- * @return bool
107
- */
108
- public function is_custom_form_active() {
109
- return $this->get_option( 'form_type' ) === 'custom';
110
- }
111
-
112
- public function get_custom_form_template() {
113
- $form = $this->get_option( 'custom_form' );
114
- return wc_stripe_get_custom_forms()[ $form ]['template'];
115
- }
116
-
117
- /**
118
- * Returns true if the postal code field is enabled.
119
- *
120
- * @return bool
121
- */
122
- public function postal_enabled() {
123
- if ( is_checkout() ) {
124
- return $this->is_active( 'postal_enabled' );
125
- }
126
- if ( is_add_payment_method_page() ) {
127
- return true;
128
- }
129
- }
130
-
131
- /**
132
- * Returns true if the cvv field is enabled.
133
- *
134
- * @return bool
135
- */
136
- public function cvv_enabled() {
137
- return $this->is_active( 'cvv_enabled' );
138
- }
139
-
140
- public function get_postal_code_regex() {
141
- return array(
142
- 'AT' => '^([0-9]{4})$',
143
- 'BR' => '^([0-9]{5})([-])?([0-9]{3})$',
144
- 'CH' => '^([0-9]{4})$',
145
- 'DE' => '^([0]{1}[1-9]{1}|[1-9]{1}[0-9]{1})[0-9]{3}$',
146
- 'ES' => '^([0-9]{5})$',
147
- 'FR' => '^([0-9]{5})$',
148
- 'IT' => '^([0-9]{5})$/i',
149
- 'IE' => '([AC-FHKNPRTV-Y]\d{2}|D6W)[0-9AC-FHKNPRTV-Y]{4}',
150
- 'JP' => '^([0-9]{3})([-])([0-9]{4})$',
151
- 'PT' => '^([0-9]{4})([-])([0-9]{3})$',
152
- 'US' => '^([0-9]{5})(-[0-9]{4})?$',
153
- 'CA' => '^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])([\ ])?(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$',
154
- 'PL' => '^([0-9]{2})([-])([0-9]{3})',
155
- 'CZ' => '^([0-9]{3})(\s?)([0-9]{2})$',
156
- 'SK' => '^([0-9]{3})(\s?)([0-9]{2})$',
157
- 'NL' => '^([1-9][0-9]{3})(\s?)(?!SA|SD|SS)[A-Z]{2}$',
158
- );
159
- }
160
-
161
- /**
162
- *
163
- * {@inheritDoc}
164
- *
165
- * @see WC_Payment_Gateway_Stripe::add_stripe_order_args()
166
- */
167
- public function add_stripe_order_args( &$args, $order ) {
168
- // if the merchant is forcing 3D secure for all intents then add the required args.
169
- if ( $this->is_active( 'force_3d_secure' ) && is_checkout() && ! doing_action( 'woocommerce_scheduled_subscription_payment_' . $this->id ) ) {
170
- $args['payment_method_options']['card']['request_three_d_secure'] = 'any';
171
- }
172
- }
173
- }
 
 
 
1
+ <?php
2
+ defined( 'ABSPATH' ) || exit();
3
+
4
+ /**
5
+ *
6
+ * @since 3.0.0
7
+ * @package Stripe/Gateways
8
+ * @author User
9
+ *
10
+ */
11
+ class WC_Payment_Gateway_Stripe_CC extends WC_Payment_Gateway_Stripe {
12
+
13
+ use WC_Stripe_Payment_Intent_Trait;
14
+
15
+ protected $payment_method_type = 'card';
16
+
17
+ public function __construct() {
18
+ $this->id = 'stripe_cc';
19
+ $this->tab_title = __( 'Credit Cards', 'woo-stripe-payment' );
20
+ $this->template_name = 'credit-card.php';
21
+ $this->token_type = 'Stripe_CC';
22
+ $this->method_title = __( 'Stripe Credit Cards', 'woo-stripe-payment' );
23
+ $this->method_description = __( 'Credit card gateway that integrates with your Stripe account.', 'woo-stripe-payment' );
24
+ parent::__construct();
25
+ }
26
+
27
+ public function get_icon() {
28
+ return wc_stripe_get_template_html(
29
+ 'card-icons.php',
30
+ array(
31
+ 'cards' => $this->get_option( 'cards' ),
32
+ 'style' => $this->get_option( 'icon_style' ),
33
+ )
34
+ );
35
+ }
36
+
37
+ public function enqueue_checkout_scripts( $scripts ) {
38
+ $scripts->enqueue_script(
39
+ 'credit-card',
40
+ $scripts->assets_url( 'js/frontend/credit-card.js' ),
41
+ array(
42
+ $scripts->prefix . 'external',
43
+ $scripts->prefix . 'wc-stripe',
44
+ )
45
+ );
46
+ $scripts->localize_script( 'credit-card', $this->get_localized_params() );
47
+ }
48
+
49
+ public function get_localized_params() {
50
+ $data = parent::get_localized_params();
51
+
52
+ return array_merge(
53
+ $data,
54
+ array(
55
+ 'style' => $this->get_form_style(),
56
+ 'elementOptions' => $this->get_element_options(),
57
+ 'custom_form' => $this->is_custom_form_active(),
58
+ 'html' => array( 'card_brand' => sprintf( '<img id="wc-stripe-card" src="%s" />', $this->get_custom_form()['cardBrand'] ) ),
59
+ 'cards' => array(
60
+ 'visa' => wc_stripe()->assets_url( 'img/cards/visa.svg' ),
61
+ 'amex' => wc_stripe()->assets_url( 'img/cards/amex.svg' ),
62
+ 'mastercard' => wc_stripe()->assets_url( 'img/cards/mastercard.svg' ),
63
+ 'discover' => wc_stripe()->assets_url( 'img/cards/discover.svg' ),
64
+ 'diners' => wc_stripe()->assets_url( 'img/cards/diners.svg' ),
65
+ 'jcb' => wc_stripe()->assets_url( 'img/cards/jcb.svg' ),
66
+ 'unionpay' => wc_stripe()->assets_url( 'img/cards/china_union_pay.svg' ),
67
+ 'unknown' => $this->get_custom_form()['cardBrand'],
68
+ ),
69
+ 'postal_regex' => $this->get_postal_code_regex(),
70
+ )
71
+ );
72
+ }
73
+
74
+ private function get_form_style() {
75
+ if ( $this->is_custom_form_active() ) {
76
+ $style = $this->get_custom_form()['elementStyles'];
77
+ } else {
78
+ $style = array(
79
+ 'base' => array(
80
+ 'color' => '#32325d',
81
+ 'fontFamily' => '"Helvetica Neue", Helvetica, sans-serif',
82
+ 'fontSmoothing' => 'antialiased',
83
+ 'fontSize' => '18px',
84
+ '::placeholder' => array( 'color' => '#aab7c4' ),
85
+ ':focus' => array(),
86
+ ),
87
+ 'invalid' => array(
88
+ 'color' => '#fa755a',
89
+ 'iconColor' => '#fa755a',
90
+ ),
91
+ );
92
+ }
93
+
94
+ return apply_filters( 'wc_stripe_cc_element_style', $style );
95
+ }
96
+
97
+ private function get_custom_form() {
98
+ return wc_stripe_get_custom_forms()[ $this->get_option( 'custom_form' ) ];
99
+ }
100
+
101
+ private function get_element_options() {
102
+ return $this->get_custom_form()['elementOptions'];
103
+ }
104
+
105
+ /**
106
+ * Returns true if custom forms are enabled.
107
+ *
108
+ * @return bool
109
+ */
110
+ public function is_custom_form_active() {
111
+ return $this->get_option( 'form_type' ) === 'custom';
112
+ }
113
+
114
+ public function get_custom_form_template() {
115
+ $form = $this->get_option( 'custom_form' );
116
+
117
+ return wc_stripe_get_custom_forms()[ $form ]['template'];
118
+ }
119
+
120
+ /**
121
+ * Returns true if the postal code field is enabled.
122
+ *
123
+ * @return bool
124
+ */
125
+ public function postal_enabled() {
126
+ if ( is_checkout() ) {
127
+ return $this->is_active( 'postal_enabled' );
128
+ }
129
+ if ( is_add_payment_method_page() ) {
130
+ return true;
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Returns true if the cvv field is enabled.
136
+ *
137
+ * @return bool
138
+ */
139
+ public function cvv_enabled() {
140
+ return $this->is_active( 'cvv_enabled' );
141
+ }
142
+
143
+ public function get_postal_code_regex() {
144
+ return array(
145
+ 'AT' => '^([0-9]{4})$',
146
+ 'BR' => '^([0-9]{5})([-])?([0-9]{3})$',
147
+ 'CH' => '^([0-9]{4})$',
148
+ 'DE' => '^([0]{1}[1-9]{1}|[1-9]{1}[0-9]{1})[0-9]{3}$',
149
+ 'ES' => '^([0-9]{5})$',
150
+ 'FR' => '^([0-9]{5})$',
151
+ 'IT' => '^([0-9]{5})$/i',
152
+ 'IE' => '([AC-FHKNPRTV-Y]\d{2}|D6W)[0-9AC-FHKNPRTV-Y]{4}',
153
+ 'JP' => '^([0-9]{3})([-])([0-9]{4})$',
154
+ 'PT' => '^([0-9]{4})([-])([0-9]{3})$',
155
+ 'US' => '^([0-9]{5})(-[0-9]{4})?$',
156
+ 'CA' => '^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])([\ ])?(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$',
157
+ 'PL' => '^([0-9]{2})([-])([0-9]{3})',
158
+ 'CZ' => '^([0-9]{3})(\s?)([0-9]{2})$',
159
+ 'SK' => '^([0-9]{3})(\s?)([0-9]{2})$',
160
+ 'NL' => '^([1-9][0-9]{3})(\s?)(?!SA|SD|SS)[A-Z]{2}$',
161
+ );
162
+ }
163
+
164
+ /**
165
+ *
166
+ * {@inheritDoc}
167
+ *
168
+ * @see WC_Payment_Gateway_Stripe::add_stripe_order_args()
169
+ */
170
+ public function add_stripe_order_args( &$args, $order ) {
171
+ // if the merchant is forcing 3D secure for all intents then add the required args.
172
+ if ( $this->is_active( 'force_3d_secure' ) && is_checkout() && ! doing_action( 'woocommerce_scheduled_subscription_payment_' . $this->id ) ) {
173
+ $args['payment_method_options']['card']['request_three_d_secure'] = 'any';
174
+ }
175
+ }
176
+ }
includes/wc-stripe-functions.php CHANGED
@@ -1,1314 +1,1344 @@
1
- <?php
2
- defined( 'ABSPATH' ) || exit();
3
-
4
- /**
5
- *
6
- * @param string $template_name
7
- * @param array $args
8
- *
9
- * @since 3.0.0
10
- * @package Stripe/Functions
11
- * Wrapper for wc_get_template that returns Stripe specfic templates.
12
- */
13
- function wc_stripe_get_template( $template_name, $args = array() ) {
14
- wc_get_template( $template_name, $args, wc_stripe()->template_path(), wc_stripe()->default_template_path() );
15
- }
16
-
17
- /**
18
- *
19
- *
20
- * Wrapper for wc_get_template_html that returns Stripe specififc templates in an html string.
21
- *
22
- * @param string $template_name
23
- * @param array $args
24
- *
25
- * @return string
26
- * @since 3.0.0
27
- * @package Stripe/Functions
28
- */
29
- function wc_stripe_get_template_html( $template_name, $args = array() ) {
30
- return wc_get_template_html( $template_name, $args, wc_stripe()->template_path(), wc_stripe()->default_template_path() );
31
- }
32
-
33
- /**
34
- * Return true if WCS is active.
35
- *
36
- * @return boolean
37
- * @package Stripe/Functions
38
- */
39
- function wcs_stripe_active() {
40
- return function_exists( 'wcs_is_subscription' );
41
- }
42
-
43
- /**
44
- *
45
- * @param WC_Payment_Gateway_Stripe $gateway
46
- *
47
- * @package Stripe/Functions
48
- */
49
- function wc_stripe_token_field( $gateway ) {
50
- wc_stripe_hidden_field( $gateway->token_key, 'wc-stripe-token-field' );
51
- }
52
-
53
- /**
54
- *
55
- * @param WC_Payment_Gateway_Stripe $gateway
56
- *
57
- * @package Stripe/Functions
58
- */
59
- function wc_stripe_payment_intent_field( $gateway ) {
60
- wc_stripe_hidden_field( $gateway->payment_intent_key, 'wc-stripe-payment-intent-field' );
61
- }
62
-
63
- /**
64
- *
65
- * @param string $id
66
- * @param string $class
67
- * @param string $value
68
- *
69
- * @package Stripe/Functions
70
- */
71
- function wc_stripe_hidden_field( $id, $class = '', $value = '' ) {
72
- printf( '<input type="hidden" class="%1$s" id="%2$s" name="%2$s" value="%3$s"/>', $class, $id, $value );
73
- }
74
-
75
- /**
76
- * Return the mode for the plugin.
77
- *
78
- * @return string
79
- * @package Stripe/Functions
80
- */
81
- function wc_stripe_mode() {
82
- return apply_filters( 'wc_stripe_mode', wc_stripe()->api_settings->get_option( 'mode' ) );
83
- }
84
-
85
- /**
86
- * Return the secret key for the provided mode.
87
- * If no mode given, the key for the active mode is returned.
88
- *
89
- * @param string $mode
90
- *
91
- * @since 3.0.0
92
- * @package Stripe/Functions
93
- */
94
- function wc_stripe_get_secret_key( $mode = '' ) {
95
- $mode = empty( $mode ) ? wc_stripe_mode() : $mode;
96
-
97
- return apply_filters( 'wc_stripe_get_secret_key', wc_stripe()->api_settings->get_option( "secret_key_{$mode}" ), $mode );
98
- }
99
-
100
- /**
101
- * Return the publishable key for the provided mode.
102
- * If no mode given, the key for the active mode is returned.
103
- *
104
- * @param string $mode
105
- *
106
- * @since 3.0.0
107
- * @package Stripe/Functions
108
- */
109
- function wc_stripe_get_publishable_key( $mode = '' ) {
110
- $mode = empty( $mode ) ? wc_stripe_mode() : $mode;
111
-
112
- return apply_filters( 'wc_stripe_get_publishable_key', wc_stripe()->api_settings->get_option( "publishable_key_{$mode}" ), $mode );
113
- }
114
-
115
- /**
116
- * Return the merchant's Stripe account.
117
- *
118
- * @return string
119
- * @since 3.1.4
120
- * @package Stripe/Functions
121
- */
122
- function wc_stripe_get_account_id() {
123
- return apply_filters( 'wc_stripe_get_account_id', wc_stripe()->api_settings->get_option( 'account_id' ) );
124
- }
125
-
126
- /**
127
- * Return the stripe customer ID
128
- *
129
- * @param int $user_id
130
- * @param string $mode
131
- *
132
- * @package Stripe/Functions
133
- * @since 3.0.0
134
- */
135
- function wc_stripe_get_customer_id( $user_id = '', $mode = '' ) {
136
- $mode = empty( $mode ) ? wc_stripe_mode() : $mode;
137
- if ( $user_id === 0 ) {
138
- return '';
139
- }
140
- if ( empty( $user_id ) ) {
141
- $user_id = get_current_user_id();
142
- }
143
-
144
- return get_user_meta( $user_id, "wc_stripe_customer_{$mode}", true );
145
- }
146
-
147
- /**
148
- *
149
- * @param string $customer_id
150
- * @param int $user_id
151
- * @param string $mode
152
- *
153
- * @package Stripe/Functions
154
- */
155
- function wc_stripe_save_customer( $customer_id, $user_id, $mode = '' ) {
156
- $mode = empty( $mode ) ? wc_stripe_mode() : $mode;
157
- $key = "wc_stripe_customer_{$mode}";
158
- update_user_meta( $user_id, $key, $customer_id );
159
- }
160
-
161
- /**
162
- *
163
- * @param int $token_id
164
- * @param WC_Payment_Token $token
165
- *
166
- * @since 3.0.0
167
- * @package Stripe/Functions
168
- */
169
- function wc_stripe_woocommerce_payment_token_deleted( $token_id, $token ) {
170
- if ( ! did_action( 'woocommerce_payment_gateways' ) ) {
171
- WC_Payment_Gateways::instance();
172
- }
173
- do_action( 'wc_stripe_payment_token_deleted_' . $token->get_gateway_id(), $token_id, $token );
174
- }
175
-
176
- /**
177
- * Log the provided message in the WC logs directory.
178
- *
179
- * @param int $level
180
- * @param string $message
181
- *
182
- * @since 3.0.0
183
- * @package Stripe/Functions
184
- */
185
- function wc_stripe_log( $level, $message ) {
186
- if ( wc_stripe()->api_settings->is_active( 'debug_log' ) ) {
187
- $log = wc_get_logger();
188
- $log->log( $level, $message, array( 'source' => 'wc-stripe' ) );
189
- }
190
- }
191
-
192
- /**
193
- *
194
- * @param string $message
195
- *
196
- * @package Stripe/Functions
197
- * @since 3.0.0
198
- */
199
- function wc_stripe_log_error( $message ) {
200
- wc_stripe_log( WC_Log_Levels::ERROR, $message );
201
- }
202
-
203
- /**
204
- *
205
- * @param string $message
206
- *
207
- * @package Stripe/Functions
208
- * @since 3.0.0
209
- */
210
- function wc_stripe_log_info( $message ) {
211
- wc_stripe_log( WC_Log_Levels::INFO, $message );
212
- }
213
-
214
- /**
215
- * Return the mode that the order was created in.
216
- * Values can be <strong>live</strong> or <strong>test</strong>
217
- *
218
- * @param WC_Order|int $order
219
- *
220
- * @package Stripe/Functions
221
- * @since 3.0.0
222
- */
223
- function wc_stripe_order_mode( $order ) {
224
- if ( is_object( $order ) ) {
225
- return $order->get_meta( WC_Stripe_Constants::MODE, true );
226
- }
227
-
228
- return get_post_meta( $order, WC_Stripe_Constants::MODE, true );
229
- }
230
-
231
- /**
232
- *
233
- * @param array $gateways
234
- *
235
- * @package Stripe\Functions
236
- * @since 3.0.0
237
- */
238
- function wc_stripe_payment_gateways( $gateways ) {
239
- return array_merge( $gateways, wc_stripe()->payment_gateways() );
240
- }
241
-
242
- /**
243
- * Cancel the Stripe charge
244
- *
245
- * @param int $order_id
246
- * @param WC_Order $order
247
- *
248
- * @package Stripe/Functions
249
- */
250
- function wc_stripe_order_cancelled( $order_id, $order ) {
251
- $gateways = WC()->payment_gateways()->payment_gateways();
252
- /**
253
- *
254
- * @var WC_Payment_Gateway_Stripe $gateway
255
- */
256
- $gateway = isset( $gateways[ $order->get_payment_method() ] ) ? $gateways[ $order->get_payment_method() ] : null;
257
-
258
- if ( $gateway && $gateway instanceof WC_Payment_Gateway_Stripe ) {
259
- $gateway->void_charge( $order );
260
- }
261
- }
262
-
263
- /**
264
- *
265
- * @param int $order_id
266
- * @param WC_Order $order
267
- *
268
- * @since 3.0.0
269
- * @package Stripe/Functions
270
- */
271
- function wc_stripe_order_status_completed( $order_id, $order ) {
272
- $gateways = WC()->payment_gateways()->payment_gateways();
273
- /**
274
- *
275
- * @var WC_Payment_Gateway_Stripe $gateway
276
- */
277
- $gateway = isset( $gateways[ $order->get_payment_method() ] ) ? $gateways[ $order->get_payment_method() ] : null;
278
- // @since 3.0.3 check added to ensure this is a Stripe gateway.
279
- if ( $gateway && $gateway instanceof WC_Payment_Gateway_Stripe && ! $gateway->processing_payment ) {
280
- $gateway->capture_charge( $order->get_total(), $order );
281
- }
282
- }
283
-
284
- /**
285
- *
286
- * @param [] $address
287
- *
288
- * @throws Exception
289
- * @since 3.0.0
290
- * @package Stripe/Functions
291
- */
292
- function wc_stripe_update_customer_location( $address ) {
293
- // address validation for countries other than US is problematic when using responses from payment sources like
294
- // Apple Pay.
295
- if ( $address['postcode'] && $address['country'] === 'US' && ! WC_Validation::is_postcode( $address['postcode'], $address['country'] ) ) {
296
- throw new Exception( __( 'Please enter a valid postcode / ZIP.', 'woocommerce' ) );
297
- } elseif ( $address['postcode'] ) {
298
- $address['postcode'] = wc_format_postcode( $address['postcode'], $address['country'] );
299
- }
300
-
301
- if ( $address['country'] ) {
302
- WC()->customer->set_billing_location( $address['country'], $address['state'], $address['postcode'], $address['city'] );
303
- WC()->customer->set_shipping_location( $address['country'], $address['state'], $address['postcode'], $address['city'] );
304
- // set the customer's address if it's in the $address array
305
- if ( ! empty( $address['address_1'] ) ) {
306
- WC()->customer->set_shipping_address_1( wc_clean( $address['address_1'] ) );
307
- }
308
- if ( ! empty( $address['address_2'] ) ) {
309
- WC()->customer->set_shipping_address_2( wc_clean( $address['address_2'] ) );
310
- }
311
- if ( ! empty( $address['first_name'] ) ) {
312
- WC()->customer->set_shipping_first_name( $address['first_name'] );
313
- }
314
- if ( ! empty( $address['last_name'] ) ) {
315
- WC()->customer->set_shipping_last_name( $address['last_name'] );
316
- }
317
- } else {
318
- WC()->customer->set_billing_address_to_base();
319
- WC()->customer->set_shipping_address_to_base();
320
- }
321
-
322
- WC()->customer->set_calculated_shipping( true );
323
- WC()->customer->save();
324
-
325
- do_action( 'woocommerce_calculated_shipping' );
326
- }
327
-
328
- /**
329
- *
330
- * @param [] $methods
331
- *
332
- * @package Stripe/Functions
333
- * @since 3.0.0
334
- */
335
- function wc_stripe_update_shipping_methods( $methods ) {
336
- $chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods', array() );
337
-
338
- foreach ( $methods as $i => $method ) {
339
- $chosen_shipping_methods[ $i ] = $method;
340
- }
341
-
342
- WC()->session->set( 'chosen_shipping_methods', $chosen_shipping_methods );
343
- }
344
-
345
- /**
346
- * Return true if there are shipping packages that contain rates.
347
- *
348
- * @param array $packages
349
- *
350
- * @return boolean
351
- * @package Stripe/Functions
352
- * @since 3.0.0
353
- */
354
- function wc_stripe_shipping_address_serviceable( $packages = array() ) {
355
- if ( $packages ) {
356
- foreach ( $packages as $package ) {
357
- if ( count( $package['rates'] ) > 0 ) {
358
- return true;
359
- }
360
- }
361
- }
362
-
363
- return false;
364
- }
365
-
366
- /**
367
- *
368
- * @param string $page
369
- * @param WC_Order $order
370
- *
371
- * @package Stripe/Functions
372
- * @since 3.0.0
373
- * @deprecated
374
- */
375
- function wc_stripe_get_display_items( $page = 'cart', $order = null ) {
376
- // first argument used to be $encode param so make sure it's a string now
377
- $page = false === $page ? 'cart' : $page;
378
- $items = array();
379
- if ( in_array( $page, array( 'cart', 'checkout' ) ) ) {
380
- $cart = WC()->cart;
381
- $incl_tax = wc_stripe_display_prices_including_tax();
382
-
383
- foreach ( $cart->get_cart() as $cart_item ) {
384
- /**
385
- *
386
- * @var WC_Product $product
387
- */
388
- $product = $cart_item['data'];
389
- $qty = $cart_item['quantity'];
390
- $items[] = array(
391
- 'label' => $qty > 1 ? sprintf( '%s X %s', $product->get_name(), $qty ) : $product->get_name(),
392
- 'pending' => false,
393
- 'amount' => wc_stripe_add_number_precision(
394
- $incl_tax ? wc_get_price_including_tax( $product, array( 'qty' => $qty ) ) : wc_get_price_excluding_tax(
395
- $product,
396
- array(
397
- 'qty' => $qty,
398
- )
399
- )
400
- ),
401
- );
402
- }
403
- if ( $cart->needs_shipping() ) {
404
- $items[] = array(
405
- 'label' => __( 'Shipping', 'woo-stripe-payment' ),
406
- 'pending' => false,
407
- 'amount' => wc_stripe_add_number_precision( $incl_tax ? $cart->shipping_total + $cart->shipping_tax_total : $cart->shipping_total ),
408
- );
409
- }
410
-
411
- // fees
412
- foreach ( $cart->get_fees() as $fee ) {
413
- $items[] = array(
414
- 'label' => $fee->name,
415
- 'pending' => false,
416
- 'amount' => wc_stripe_add_number_precision( $incl_tax ? $fee->total + $fee->tax : $fee->total ),
417
- );
418
- }
419
- // coupons
420
- if ( 0 < $cart->discount_cart ) {
421
- $items[] = array(
422
- 'label' => __( 'Discount', 'woo-stripe-payment' ),
423
- 'pending' => false,
424
- 'amount' => wc_stripe_add_number_precision( - 1 * abs( $incl_tax ? $cart->discount_cart + $cart->discount_cart_tax : $cart->discount_cart ) ),
425
- );
426
- }
427
-
428
- if ( ! $incl_tax && wc_tax_enabled() ) {
429
- $item = array(
430
- 'label' => __( 'Tax', 'woo-stripe-payment' ),
431
- 'pending' => false,
432
- 'amount' => wc_stripe_add_number_precision( $cart->get_taxes_total() ),
433
- );
434
- if ( 'itemized' === get_option( 'woocommerce_tax_total_display' ) ) {
435
- if ( 0 < WC()->cart->get_taxes_total() ) {
436
- $items[] = $item;
437
- }
438
- } else {
439
- $items[] = $item;
440
- }
441
- }
442
- } elseif ( 'product' === $page ) {
443
- global $product;
444
- $items[] = array(
445
- 'amount' => wc_stripe_add_number_precision( $product->get_price() ),
446
- 'label' => esc_attr( $product->get_name() ),
447
- 'pending' => true,
448
- );
449
- } elseif ( 'order_pay' === $page ) {
450
- global $wp;
451
- $order = ! $order ? wc_get_order( absint( $wp->query_vars['order-pay'] ) ) : $order;
452
- $currency = $order->get_currency();
453
- // add all order items
454
- foreach ( $order->get_items() as $item ) {
455
- /**
456
- *
457
- * @var WC_Order_Item_Product $item
458
- */
459
- $qty = $item->get_quantity();
460
-
461
- $items[] = array(
462
- 'label' => $qty > 1 ? sprintf( '%s X %s', $item->get_name(), $qty ) : $item->get_name(),
463
- 'pending' => false,
464
- 'amount' => wc_stripe_add_number_precision( $item->get_subtotal(), $currency ),
465
- );
466
- }
467
- // shipping total
468
- if ( 0 < $order->get_shipping_total() ) {
469
- $items[] = array(
470
- 'label' => __( 'Shipping', 'woo-stripe-payment' ),
471
- 'pending' => false,
472
- 'amount' => wc_stripe_add_number_precision( $order->get_shipping_total(), $currency ),
473
- );
474
- }
475
- // discount total
476
- if ( 0 < $order->get_total_discount() ) {
477
- $items[] = array(
478
- 'label' => __( 'Discount', 'woo-stripe-payment' ),
479
- 'pending' => false,
480
- 'amount' => wc_stripe_add_number_precision( - 1 * $order->get_total_discount(), $currency ),
481
- );
482
- }
483
- if ( 0 < $order->get_fees() ) {
484
- $fee_total = 0;
485
- foreach ( $order->get_fees() as $fee ) {
486
- $fee_total += $fee->get_total();
487
- }
488
- $items[] = array(
489
- 'label' => __( 'Fees', 'woo-stripe-payment' ),
490
- 'pending' => false,
491
- 'amount' => wc_stripe_add_number_precision( $fee_total, $currency ),
492
- );
493
- }
494
- // tax total
495
- if ( 0 < $order->get_total_tax() ) {
496
- $items[] = array(
497
- 'label' => __( 'Tax', 'woocommerce' ),
498
- 'pending' => false,
499
- 'amount' => wc_stripe_add_number_precision( $order->get_total_tax(), $currency ),
500
- );
501
- }
502
- }
503
-
504
- /**
505
- * @param array $items
506
- * @param WC_Order $order
507
- */
508
- return apply_filters( 'wc_stripe_get_display_items', $items, $order );
509
- }
510
-
511
- /**
512
- *
513
- * @param WC_Order $order
514
- * @param array $packages
515
- *
516
- * @return mixed
517
- * @package Stripe/Functions
518
- * @since 3.0.0
519
- * @deprecated
520
- */
521
- function wc_stripe_get_shipping_options( $order = null, $packages = array() ) {
522
- $methods = array();
523
- $incl_tax = wc_stripe_display_prices_including_tax();
524
- $ids = array();
525
- $chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods', array() );
526
- $packages = empty( $packages ) ? WC()->shipping()->get_packages() : $packages;
527
- foreach ( $packages as $i => $package ) {
528
- foreach ( $package['rates'] as $rate ) {
529
- /**
530
- *
531
- * @var WC_Shipping_Rate $rate
532
- */
533
- $method = array(
534
- 'id' => sprintf( '%s:%s', $i, $rate->id ),
535
- 'label' => sprintf( '%s', esc_attr( $rate->get_label() ) ),
536
- 'detail' => '',
537
- 'amount' => wc_stripe_add_number_precision( $incl_tax ? $rate->cost + $rate->get_shipping_tax() : $rate->cost ),
538
- );
539
- if ( $incl_tax ) {
540
- if ( $rate->get_shipping_tax() > 0 && ! wc_prices_include_tax() ) {
541
- $method['detail'] = WC()->countries->inc_tax_or_vat();
542
- }
543
- } else {
544
- if ( $rate->get_shipping_tax() > 0 && wc_prices_include_tax() ) {
545
- $method['detail'] = WC()->countries->ex_tax_or_vat();
546
- }
547
- }
548
- $methods[] = $method;
549
- if ( isset( $chosen_shipping_methods[ $i ] ) && $chosen_shipping_methods[ $i ] === $rate->id ) {
550
- $ids[] = $method['id'];
551
- }
552
- }
553
- /**
554
- * Sort the shipping methods so that the selected method is always first
555
- * in the array.
556
- */
557
- usort( $methods, function ( $a, $b ) use ( $ids ) {
558
- return in_array( $a['id'], $ids ) ? - 1 : 1;
559
- } );
560
- }
561
-
562
- /**
563
- *
564
- * @param array $methods
565
- * @param WC_Order $orer
566
- */
567
- return apply_filters( 'wc_stripe_get_shipping_options', $methods, $order );
568
- }
569
-
570
- /**
571
- *
572
- * @since 3.0.0
573
- * @package Stripe/Functions
574
- */
575
- function wc_stripe_set_checkout_error() {
576
- add_action( 'woocommerce_after_template_part', 'wc_stripe_output_checkout_error' );
577
- }
578
-
579
- /**
580
- *
581
- * @param string $template_name
582
- *
583
- * @package Stripe/Functions
584
- * @since 3.0.0
585
- */
586
- function wc_stripe_output_checkout_error( $template_name ) {
587
- if ( $template_name === 'notices/error.php' && is_ajax() ) {
588
- echo '<input type="hidden" id="wc_stripe_checkout_error" value="true"/>';
589
- remove_action( 'woocommerce_after_template_part', 'wc_stripe_output_checkout_error' );
590
- add_filter( 'wp_kses_allowed_html', 'wc_stripe_add_allowed_html', 10, 2 );
591
- }
592
- }
593
-
594
- /**
595
- *
596
- * @since 3.0.0
597
- * @package Stripe/Functions
598
- */
599
- function wc_stripe_add_allowed_html( $tags, $context ) {
600
- if ( $context === 'post' ) {
601
- $tags['input'] = array(
602
- 'id' => true,
603
- 'type' => true,
604
- 'value' => true,
605
- );
606
- }
607
-
608
- return $tags;
609
- }
610
-
611
- /**
612
- * Save WCS meta data when it's changed in the admin section.
613
- * By default WCS saves the
614
- * payment method title as the gateway title. This method saves the payment method title in
615
- * a human readable format suitable for the frontend.
616
- *
617
- * @param int $post_id
618
- * @param WP_Post $post
619
- *
620
- * @package Stripe/Functions
621
- */
622
- function wc_stripe_process_shop_subscription_meta( $post_id, $post ) {
623
- $subscription = wcs_get_subscription( $post_id );
624
- $gateway_id = $subscription->get_payment_method();
625
- $gateways = WC()->payment_gateways()->payment_gateways();
626
- if ( isset( $gateways[ $gateway_id ] ) ) {
627
- $gateway = $gateways[ $gateway_id ];
628
- if ( $gateway instanceof WC_Payment_Gateway_Stripe ) {
629
- $token = $gateway->get_token( $subscription->get_meta( WC_Stripe_Constants::PAYMENT_METHOD_TOKEN ), $subscription->get_customer_id() );
630
- if ( $token ) {
631
- $subscription->set_payment_method_title( $token->get_payment_method_title() );
632
- $subscription->save();
633
- }
634
- }
635
- }
636
- }
637
-
638
- /**
639
- * Filter the WC payment gateways based on criteria specific to Stripe functionality.
640
- *
641
- * <strong>Example:</strong> on add payment method page, only show the CC gateway for Stripe.
642
- *
643
- * @param WC_Payment_Gateway[] $gateways
644
- *
645
- * @package Stripe/Functions
646
- * @since 3.0.0
647
- */
648
- function wc_stripe_available_payment_gateways( $gateways ) {
649
- global $wp;
650
- if ( is_add_payment_method_page() && ! isset( $wp->query_vars['payment-methods'] ) ) {
651
- foreach ( $gateways as $gateway ) {
652
- if ( $gateway instanceof WC_Payment_Gateway_Stripe ) {
653
- if ( 'stripe_cc' !== $gateway->id ) {
654
- unset( $gateways[ $gateway->id ] );
655
- }
656
- }
657
- }
658
- }
659
-
660
- return $gateways;
661
- }
662
-
663
- /**
664
- *
665
- * @return array
666
- * @package Stripe/Functions
667
- * @since 3.0.0
668
- */
669
- function wc_stripe_get_local_payment_params() {
670
- global $wp;
671
- $data = array();
672
- $gateways = WC()->payment_gateways()->payment_gateways();
673
- foreach ( $gateways as $gateway ) {
674
- if ( $gateway instanceof WC_Payment_Gateway_Stripe_Local_Payment && $gateway->is_available() ) {
675
- $data['gateways'][ $gateway->id ] = $gateway->get_localized_params();
676
- if ( isset( $wp->query_vars['order-pay'] ) ) {
677
- $data['gateways'][ $gateway->id ]['order_id'] = $wp->query_vars['order-pay'];
678
- }
679
- }
680
- }
681
- $data['api_key'] = wc_stripe_get_publishable_key();
682
-
683
- return $data;
684
- }
685
-
686
- /**
687
- *
688
- * @param array $gateways
689
- *
690
- * @return WC_Payment_Gateway[]
691
- * @package Stripe/Functions
692
- * @since 3.0.0
693
- */
694
- function wc_stripe_get_available_local_gateways( $gateways ) {
695
- foreach ( $gateways as $gateway ) {
696
- if ( $gateway instanceof WC_Payment_Gateway_Stripe_Local_Payment ) {
697
- if ( ! $gateway->is_local_payment_available() ) {
698
- unset( $gateways[ $gateway->id ] );
699
- }
700
- }
701
- }
702
-
703
- return $gateways;
704
- }
705
-
706
- /**
707
- *
708
- * @param string|int $key
709
- *
710
- * @package Stripe/Functions
711
- * @since 3.0.0
712
- */
713
- function wc_stripe_set_idempotency_key( $key ) {
714
- global $wc_stripe_idempotency_key;
715
- $wc_stripe_idempotency_key = $key;
716
- }
717
-
718
- /**
719
- *
720
- * @return mixed
721
- * @package Stripe/Functions
722
- * @since 3.0.0
723
- */
724
- function wc_stripe_get_idempotency_key() {
725
- global $wc_stripe_idempotency_key;
726
-
727
- return $wc_stripe_idempotency_key;
728
- }
729
-
730
- /**
731
- *
732
- * @param array $options
733
- *
734
- * @return array
735
- * @since 3.0.0
736
- * @package Stripe/Functions
737
- */
738
- function wc_stripe_api_options( $options ) {
739
- $key = wc_stripe_get_idempotency_key();
740
- if ( $key ) {
741
- $options['idempotency_key'] = $key;
742
- }
743
-
744
- return $options;
745
- }
746
-
747
- /**
748
- *
749
- * @param string $order_status
750
- * @param int $order_id
751
- * @param WC_Order $order
752
- *
753
- * @package Stripe/Functions
754
- * @since 3.0.0
755
- * <br/><strong>3.1.7</strong> - default $order argument of null added to prevent errors when 3rd party plugins trigger
756
- * action woocommerce_payment_complete_order_status and don't pass three arguments.
757
- */
758
- function wc_stripe_payment_complete_order_status( $order_status, $order_id, $order = null ) {
759
- if ( is_checkout() && $order && $order->get_payment_method() ) {
760
- $gateway = WC()->payment_gateways()->payment_gateways()[ $order->get_payment_method() ];
761
- if ( $gateway instanceof WC_Payment_Gateway_Stripe && 'default' !== $gateway->get_option( 'order_status' ) ) {
762
- $order_status = $gateway->get_option( 'order_status' );
763
- }
764
- }
765
-
766
- return $order_status;
767
- }
768
-
769
- /**
770
- * Converts the amount to cents.
771
- * Stripe processes all requests in cents.
772
- *
773
- * @param float $value
774
- * @param string $currency
775
- * @param string $round
776
- *
777
- * @return number
778
- * @package Stripe/Functions
779
- * @since 3.0.0
780
- */
781
- function wc_stripe_add_number_precision( $value, $currency = '', $round = true ) {
782
- if ( ! is_numeric( $value ) ) {
783
- $value = 0;
784
- }
785
- $currency = empty( $currency ) ? get_woocommerce_currency() : $currency;
786
- $currencies = wc_stripe_get_currencies();
787
- $exp = isset( $currencies[ $currency ] ) ? $currencies[ $currency ] : 2;
788
- $cent_precision = pow( 10, $exp );
789
- $value = $value * $cent_precision;
790
- $value = $round ? round( $value, wc_get_rounding_precision() - wc_get_price_decimals() ) : $value;
791
-
792
- if ( is_numeric( $value ) && floor( $value ) != $value ) {
793
- // there are some decimal points that need to be removed.
794
- $value = round( $value );
795
- }
796
-
797
- return $value;
798
- }
799
-
800
- /**
801
- * Return an array of credit card forms.
802
- *
803
- * @return mixed
804
- * @package Stripe/Functions
805
- * @since 3.0.0
806
- */
807
- function wc_stripe_get_custom_forms() {
808
- return apply_filters(
809
- 'wc_stripe_get_custom_forms',
810
- array(
811
- 'bootstrap' => array(
812
- 'template' => 'cc-forms/bootstrap.php',
813
- 'label' => __( 'Bootstrap form', 'woo-stripe-payment' ),
814
- 'cardBrand' => wc_stripe()->assets_url( 'img/card_brand2.svg' ),
815
- 'elementStyles' => array(
816
- 'base' => array(
817
- 'color' => '#495057',
818
- 'fontWeight' => 300,
819
- 'fontFamily' => 'Roboto, sans-serif, Source Code Pro, Consolas, Menlo, monospace',
820
- 'fontSize' => '16px',
821
- 'fontSmoothing' => 'antialiased',
822
- '::placeholder' => array(
823
- 'color' => '#fff',
824
- 'fontSize' => '0px',
825
- ),
826
- ':-webkit-autofill' => array( 'color' => '#495057' ),
827
- ),
828
- 'invalid' => array(
829
- 'color' => '#E25950',
830
- '::placeholder' => array( 'color' => '#757575' ),
831
- ),
832
- ),
833
- 'elementOptions' => array(
834
- 'fonts' => array( array( 'cssSrc' => 'https://fonts.googleapis.com/css?family=Source+Code+Pro' ) ),
835
- ),
836
- ),
837
- 'simple' => array(
838
- 'template' => 'cc-forms/simple.php',
839
- 'label' => __( 'Simple form', 'woo-stripe-payment' ),
840
- 'cardBrand' => wc_stripe()->assets_url( 'img/card_brand2.svg' ),
841
- 'elementStyles' => array(
842
- 'base' => array(
843
- 'color' => '#32325D',
844
- 'fontWeight' => 500,
845
- 'fontFamily' => 'Source Code Pro, Consolas, Menlo, monospace',
846
- 'fontSize' => '16px',
847
- 'fontSmoothing' => 'antialiased',
848
- '::placeholder' => array( 'color' => '#CFD7DF' ),
849
- ':-webkit-autofill' => array( 'color' => '#32325D' ),
850
- ),
851
- 'invalid' => array(
852
- 'color' => '#E25950',
853
- '::placeholder' => array( 'color' => '#FFCCA5' ),
854
- ),
855
- ),
856
- 'elementOptions' => array(
857
- 'fonts' => array( array( 'cssSrc' => 'https://fonts.googleapis.com/css?family=Source+Code+Pro' ) ),
858
- ),
859
- ),
860
- 'minimalist' => array(
861
- 'template' => 'cc-forms/minimalist.php',
862
- 'label' => __( 'Minimalist form', 'woo-stripe-payment' ),
863
- 'cardBrand' => wc_stripe()->assets_url( 'img/card_brand2.svg' ),
864
- 'elementStyles' => array(
865
- 'base' => array(
866
- 'color' => '#495057',
867
- 'fontWeight' => 300,
868
- 'fontFamily' => 'Roboto, sans-serif, Source Code Pro, Consolas, Menlo, monospace',
869
- 'fontSize' => '30px',
870
- 'fontSmoothing' => 'antialiased',
871
- '::placeholder' => array(
872
- 'color' => '#fff',
873
- 'fontSize' => '0px',
874
- ),
875
- ':-webkit-autofill' => array( 'color' => '#495057' ),
876
- ),
877
- 'invalid' => array(
878
- 'color' => '#495057',
879
- '::placeholder' => array( 'color' => '#495057' ),
880
- ),
881
- ),
882
- 'elementOptions' => array(
883
- 'fonts' => array( array( 'cssSrc' => 'https://fonts.googleapis.com/css?family=Source+Code+Pro' ) ),
884
- ),
885
- ),
886
- 'inline' => array(
887
- 'template' => 'cc-forms/inline.php',
888
- 'label' => __( 'Inline Form', 'woo-stripe-payment' ),
889
- 'cardBrand' => wc_stripe()->assets_url( 'img/card_brand.svg' ),
890
- 'elementStyles' => array(
891
- 'base' => array(
892
- 'color' => '#819efc',
893
- 'fontWeight' => 600,
894
- 'fontFamily' => 'Roboto, Open Sans, Segoe UI, sans-serif',
895
- 'fontSize' => '16px',
896
- 'fontSmoothing' => 'antialiased',
897
- ':focus' => array( 'color' => '#819efc' ),
898
- '::placeholder' => array( 'color' => '#87BBFD' ),
899
- ':focus::placeholder' => array( 'color' => '#CFD7DF' ),
900
- ':-webkit-autofill' => array( 'color' => '#819efc' ),
901
- ),
902
- 'invalid' => array( 'color' => '#f99393' ),
903
- ),
904
- 'elementOptions' => array(
905
- 'fonts' => array( array( 'cssSrc' => 'https://fonts.googleapis.com/css?family=Roboto' ) ),
906
- ),
907
- ),
908
- 'rounded' => array(
909
- 'template' => 'cc-forms/round.php',
910
- 'label' => __( 'Rounded Form', 'woo-stripe-payment' ),
911
- 'cardBrand' => wc_stripe()->assets_url( 'img/card_brand.svg' ),
912
- 'elementStyles' => array(
913
- 'base' => array(
914
- 'color' => '#fff',
915
- 'fontWeight' => 600,
916
- 'fontFamily' => 'Quicksand, Open Sans, Segoe UI, sans-serif',
917
- 'fontSize' => '16px',
918
- 'fontSmoothing' => 'antialiased',
919
- ':focus' => array( 'color' => '#424770' ),
920
- '::placeholder' => array( 'color' => '#9BACC8' ),
921
- ':focus::placeholder' => array( 'color' => '#CFD7DF' ),
922
- ':-webkit-autofill' => array( 'color' => '#fff' ),
923
- ),
924
- 'invalid' => array(
925
- 'color' => '#fff',
926
- ':focus' => array( 'color' => '#FA755A' ),
927
- '::placeholder' => array( 'color' => '#FFCCA5' ),
928
- ),
929
- ),
930
- 'elementOptions' => array(
931
- 'fonts' => array( array( 'cssSrc' => 'https://fonts.googleapis.com/css?family=Quicksand' ) ),
932
- ),
933
- ),
934
- )
935
- );
936
- }
937
-
938
- /**
939
- *
940
- * @param WC_Order $order
941
- *
942
- * @since 3.0.0
943
- * @package Stripe/Functions
944
- */
945
- function wc_stripe_order_has_shipping_address( $order ) {
946
- if ( method_exists( $order, 'has_shipping_address' ) ) {
947
- return $order->has_shipping_address();
948
- } else {
949
- return $order->get_shipping_address_1() || $order->get_shipping_address_2();
950
- }
951
- }
952
-
953
- /**
954
- *
955
- * @since 3.0.0
956
- * @package Stripe/Functions
957
- */
958
- function wc_stripe_display_prices_including_tax() {
959
- $cart = WC()->cart;
960
- if ( method_exists( $cart, 'display_prices_including_tax' ) ) {
961
- return $cart->display_prices_including_tax();
962
- }
963
- if ( is_callable( array( $cart, 'get_tax_price_display_mode' ) ) ) {
964
- return 'incl' == $cart->get_tax_price_display_mode() && ( WC()->customer && ! WC()->customer->is_vat_exempt() );
965
- }
966
-
967
- return 'incl' == $cart->tax_display_cart && ( WC()->customer && ! WC()->customer->is_vat_exempt() );
968
- }
969
-
970
- /**
971
- * Return true if the WC pre-orders plugin is active
972
- *
973
- * @since 3.0.1
974
- * @package Stripe/Functions
975
- */
976
- function wc_stripe_pre_orders_active() {
977
- return class_exists( 'WC_Pre_Orders' );
978
- }
979
-
980
- /**
981
- *
982
- * @param string $source_id
983
- *
984
- * @package Stripe/Functions
985
- * @since 3.0.5
986
- */
987
- function wc_stripe_get_order_from_source_id( $source_id ) {
988
- global $wpdb;
989
- $order_id = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} AS posts LEFT JOIN {$wpdb->postmeta} AS meta ON posts.ID = meta.post_id WHERE meta.meta_key = %s AND meta.meta_value = %s LIMIT 1", '_stripe_source_id', $source_id ) );
990
-
991
- return wc_get_order( $order_id );
992
- }
993
-
994
- /**
995
- *
996
- * @param string $transaction_id
997
- *
998
- * @return WC_Order|WC_Refund|boolean|WC_Order_Refund
999
- * @since 3.0.5
1000
- * @package Stripe/Functions
1001
- */
1002
- function wc_stripe_get_order_from_transaction( $transaction_id ) {
1003
- global $wpdb;
1004
- $order_id = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} AS posts LEFT JOIN {$wpdb->postmeta} AS meta ON posts.ID = meta.post_id WHERE meta.meta_key = %s AND meta.meta_value = %s LIMIT 1", '_transaction_id', $transaction_id ) );
1005
-
1006
- return wc_get_order( $order_id );
1007
- }
1008
-
1009
- /**
1010
- * Stash the WC cart contents in the session and empty it's contents.
1011
- * If $product_cart is true, add the stashed product(s)
1012
- * to the cart.
1013
- *
1014
- * @param WC_Cart $cart
1015
- *
1016
- * @package Stripe/Functions
1017
- * @todo Maybe empty cart silently so actions are not triggered that cause session data to be removed
1018
- * from 3rd party plugins.
1019
- *
1020
- * @since 3.0.6
1021
- */
1022
- function wc_stripe_stash_cart( $cart, $product_cart = true ) {
1023
- $data = WC()->session->get( 'wc_stripe_cart', array() );
1024
- $data['cart'] = $cart->get_cart_for_session();
1025
- WC()->session->set( 'wc_stripe_cart', $data );
1026
- $cart->empty_cart( false );
1027
- if ( $product_cart && isset( $data['product_cart'] ) ) {
1028
- foreach ( $data['product_cart'] as $cart_item ) {
1029
- $cart->add_to_cart( $cart_item['product_id'], $cart_item['quantity'], $cart_item['variation_id'] );
1030
- }
1031
- }
1032
- }
1033
-
1034
- /**
1035
- *
1036
- * @param number $product_id
1037
- * @param number $qty
1038
- * @param number $variation_id
1039
- *
1040
- * @package Stripe/Functions
1041
- * @since 3.0.6
1042
- */
1043
- function wc_stripe_stash_product_cart( $cart ) {
1044
- $data = WC()->session->get( 'wc_stripe_cart', array() );
1045
- $data['product_cart'] = $cart->get_cart_for_session();
1046
- WC()->session->set( 'wc_stripe_cart', $data );
1047
- WC()->cart->set_session();
1048
- }
1049
-
1050
- /**
1051
- *
1052
- * @param WC_Cart $cart
1053
- *
1054
- * @package Stripe/Functions
1055
- * @since 3.0.6
1056
- */
1057
- function wc_stripe_restore_cart( $cart ) {
1058
- $data = WC()->session->get( 'wc_stripe_cart', array( 'cart' => array() ) );
1059
- $cart->cart_contents = $data['cart'];
1060
- $cart->set_session();
1061
- }
1062
-
1063
- /**
1064
- *
1065
- * @since 3.0.6
1066
- * @package Stripe/Functions
1067
- */
1068
- function wc_stripe_restore_cart_after_product_checkout() {
1069
- wc_stripe_restore_cart( WC()->cart );
1070
- $cart_contents = array();
1071
- foreach ( WC()->cart->get_cart() as $key => $cart_item ) {
1072
- $cart_item['data'] = wc_get_product( $cart_item['variation_id'] ? $cart_item['variation_id'] : $cart_item['product_id'] );
1073
- $cart_contents[ $key ] = $cart_item;
1074
- }
1075
- WC()->cart->cart_contents = $cart_contents;
1076
- WC()->cart->calculate_totals();
1077
- }
1078
-
1079
- /**
1080
- *
1081
- * @param WC_Payment_Token[] $tokens
1082
- * @param int $user_id
1083
- * @param string $gateway_id
1084
- *
1085
- * @return WC_Payment_Token[]
1086
- * @since 3.1.0
1087
- * @package Stripe/Functions
1088
- */
1089
- function wc_stripe_get_customer_payment_tokens( $tokens, $user_id, $gateway_id ) {
1090
- foreach ( $tokens as $idx => $token ) {
1091
- if ( $token instanceof WC_Payment_Token_Stripe ) {
1092
- $mode = wc_stripe_mode();
1093
- if ( $token->get_environment() != $mode ) {
1094
- unset( $tokens[ $idx ] );
1095
- }
1096
- }
1097
- }
1098
-
1099
- return $tokens;
1100
- }
1101
-
1102
- /**
1103
- *
1104
- * @param array $labels
1105
- *
1106
- * @return string
1107
- * @since 3.1.0
1108
- * @package Stripe/Functions
1109
- */
1110
- function wc_stripe_credit_card_labels( $labels ) {
1111
- if ( ! isset( $labels['amex'] ) ) {
1112
- $labels['amex'] = __( 'Amex', 'woocommerce' );
1113
- }
1114
-
1115
- return $labels;
1116
- }
1117
-
1118
- /**
1119
- * Return an array of Stripe error messages.
1120
- *
1121
- * @since 3.1.1
1122
- * @package Stripe/Functions
1123
- */
1124
- function wc_stripe_get_error_messages() {
1125
- return apply_filters(
1126
- 'wc_stripe_get_error_messages',
1127
- array(
1128
- 'stripe_cc_generic' => __( 'There was an error processing your credit card.', 'woo-stripe-payment' ),
1129
- 'incomplete_number' => __( 'Your card number is incomplete.', 'woo-stripe-payment' ),
1130
- 'incorrect_number' => __( 'The card number is incorrect. Check the card\'s number or use a different card.', 'woo-stripe-payment' ),
1131
- 'incorrect_cvc' => __( 'The card\'s security code is incorrect. Check the card\'s security code or use a different card.', 'woo-stripe-payment' ),
1132
- 'incorrect_zip' => __( 'The card\'s ZIP code is incorrect. Check the card\'s ZIP code or use a different card.', 'woo-stripe-payment' ),
1133
- 'invalid_number' => __( 'The card number is invalid. Check the card details or use a different card.', 'woo-stripe-payment' ),
1134
- 'invalid_characters' => __( 'This value provided to the field contains characters that are unsupported by the field.', 'woo-stripe-payment' ),
1135
- 'invalid_cvc' => __( 'The card\'s security code is invalid. Check the card\'s security code or use a different card.', 'woo-stripe-payment' ),
1136
- 'invalid_expiry_month' => __( 'The card\'s expiration month is incorrect. Check the expiration date or use a different card.', 'woo-stripe-payment' ),
1137
- 'invalid_expiry_year' => __( 'The card\'s expiration year is incorrect. Check the expiration date or use a different card.', 'woo-stripe-payment' ),
1138
- 'invalid_number' => __( 'The card number is invalid. Check the card details or use a different card.', 'woo-stripe-payment' ),
1139
- 'incorrect_address' => __( 'The card\'s address is incorrect. Check the card\'s address or use a different card.', 'woo-stripe-payment' ),
1140
- 'expired_card' => __( 'The card has expired. Check the expiration date or use a different card.', 'woo-stripe-payment' ),
1141
- 'card_declined' => __( 'The card has been declined.', 'woo-stripe-payment' ),
1142
- 'invalid_expiry_year_past' => __( 'Your card\'s expiration year is in the past.', 'woo-stripe-payment' ),
1143
- 'account_number_invalid' => __( 'The bank account number provided is invalid (e.g., missing digits). Bank account information varies from country to country. We recommend creating validations in your entry forms based on the bank account formats we provide.', 'woo-stripe-payment' ),
1144
- 'amount_too_large' => __( 'The specified amount is greater than the maximum amount allowed. Use a lower amount and try again.', 'woo-stripe-payment' ),
1145
- 'amount_too_small' => __( 'The specified amount is less than the minimum amount allowed. Use a higher amount and try again.', 'woo-stripe-payment' ),
1146
- 'authentication_required' => __( 'The payment requires authentication to proceed. If your customer is off session, notify your customer to return to your application and complete the payment. If you provided the error_on_requires_action parameter, then your customer should try another card that does not require authentication.', 'woo-stripe-payment' ),
1147
- 'balance_insufficient' => __( 'The transfer or payout could not be completed because the associated account does not have a sufficient balance available. Create a new transfer or payout using an amount less than or equal to the account\'s available balance.', 'woo-stripe-payment' ),
1148
- 'bank_account_declined' => __( 'The bank account provided can not be used to charge, either because it is not verified yet or it is not supported.', 'woo-stripe-payment' ),
1149
- 'bank_account_exists' => __( 'The bank account provided already exists on the specified Customer object. If the bank account should also be attached to a different customer, include the correct customer ID when making the request again.', 'woo-stripe-payment' ),
1150
- 'bank_account_unusable' => __( 'The bank account provided cannot be used for payouts. A different bank account must be used.', 'woo-stripe-payment' ),
1151
- 'bank_account_unverified' => __( 'Your Connect platform is attempting to share an unverified bank account with a connected account.', 'woo-stripe-payment' ),
1152
- 'bank_account_verification_failed' => __( 'The bank account cannot be verified, either because the microdeposit amounts provided do not match the actual amounts, or because verification has failed too many times.', 'woo-stripe-payment' ),
1153
- 'card_decline_rate_limit_exceeded' => __( 'This card has been declined too many times. You can try to charge this card again after 24 hours. We suggest reaching out to your customer to make sure they have entered all of their information correctly and that there are no issues with their card.', 'woo-stripe-payment' ),
1154
- 'charge_already_captured' => __( 'The charge you\'re attempting to capture has already been captured. Update the request with an uncaptured charge ID.', 'woo-stripe-payment' ),
1155
- 'charge_already_refunded' => __( 'The charge you\'re attempting to refund has already been refunded. Update the request to use the ID of a charge that has not been refunded.', 'woo-stripe-payment' ),
1156
- 'charge_disputed' => __( 'The charge you\'re attempting to refund has been charged back. Check the disputes documentation to learn how to respond to the dispute.', 'woo-stripe-payment' ),
1157
- 'charge_exceeds_source_limit' => __( 'This charge would cause you to exceed your rolling-window processing limit for this source type. Please retry the charge later, or contact us to request a higher processing limit.', 'woo-stripe-payment' ),
1158
- 'charge_expired_for_capture' => __( 'The charge cannot be captured as the authorization has expired. Auth and capture charges must be captured within seven days.', 'woo-stripe-payment' ),
1159
- 'charge_invalid_parameter' => __( 'One or more provided parameters was not allowed for the given operation on the Charge. Check our API reference or the returned error message to see which values were not correct for that Charge.', 'woo-stripe-payment' ),
1160
- 'email_invalid' => __( 'The email address is invalid (e.g., not properly formatted). Check that the email address is properly formatted and only includes allowed characters.', 'woo-stripe-payment' ),
1161
- 'idempotency_key_in_use' => __( 'The idempotency key provided is currently being used in another request. This occurs if your integration is making duplicate requests simultaneously.', 'woo-stripe-payment' ),
1162
- 'invalid_charge_amount' => __( 'The specified amount is invalid. The charge amount must be a positive integer in the smallest currency unit, and not exceed the minimum or maximum amount.', 'woo-stripe-payment' ),
1163
- 'invalid_source_usage' => __( 'The source cannot be used because it is not in the correct state (e.g., a charge request is trying to use a source with a pending, failed, or consumed source). Check the status of the source you are attempting to use.', 'woo-stripe-payment' ),
1164
- 'missing' => __( 'Both a customer and source ID have been provided, but the source has not been saved to the customer. To create a charge for a customer with a specified source, you must first save the card details.', 'woo-stripe-payment' ),
1165
- 'postal_code_invalid' => __( 'The ZIP code provided was incorrect.', 'woo-stripe-payment' ),
1166
- 'processing_error' => __( 'An error occurred while processing the card. Try again later or with a different payment method.', 'woo-stripe-payment' ),
1167
- 'card_not_supported' => __( 'The card does not support this type of purchase.', 'woo-stripe-payment' ),
1168
- 'call_issuer' => __( 'The card has been declined for an unknown reason.', 'woo-stripe-payment' ),
1169
- 'card_velocity_exceeded' => __( 'The customer has exceeded the balance or credit limit available on their card.', 'woo-stripe-payment' ),
1170
- 'currency_not_supported' => __( 'The card does not support the specified currency.', 'woo-stripe-payment' ),
1171
- 'do_not_honor' => __( 'The card has been declined for an unknown reason.', 'woo-stripe-payment' ),
1172
- 'fraudulent' => __( 'The payment has been declined as Stripe suspects it is fraudulent.', 'woo-stripe-payment' ),
1173
- 'generic_decline' => __( 'The card has been declined for an unknown reason.', 'woo-stripe-payment' ),
1174
- 'incorrect_pin' => __( 'The PIN entered is incorrect. ', 'woo-stripe-payment' ),
1175
- 'insufficient_funds' => __( 'The card has insufficient funds to complete the purchase.', 'woo-stripe-payment' ),
1176
- 'empty_element' => __( 'Please select a payment method before proceeding.', 'woo-stripe-payment' ),
1177
- 'empty_element_sepa_debit' => __( 'Please enter your IBAN before proceeding.', 'woo-stripe-payment' ),
1178
- 'empty_element_ideal' => __(
1179
- 'Please select a bank before proceeding',
1180
- 'woo-stripe-payment'
1181
- ),
1182
- )
1183
- );
1184
- }
1185
-
1186
- /**
1187
- * Return an array of Stripe currencies where the value of each
1188
- * currency is the curency multiplier.
1189
- *
1190
- * @return mixed
1191
- * @package Stripe/Functions
1192
- * @since 3.1.2
1193
- */
1194
- function wc_stripe_get_currencies() {
1195
- return apply_filters(
1196
- 'wc_stripe_get_currencies',
1197
- array(
1198
- 'BIF' => 0,
1199
- 'CLP' => 0,
1200
- 'DJF' => 0,
1201
- 'GNF' => 0,
1202
- 'JPY' => 0,
1203
- 'KMF' => 0,
1204
- 'KRW' => 0,
1205
- 'MGA' => 0,
1206
- 'PYG' => 0,
1207
- 'RWF' => 0,
1208
- 'UGX' => 0,
1209
- 'VND' => 0,
1210
- 'VUV' => 0,
1211
- 'XAF' => 0,
1212
- 'XOF' => 0,
1213
- 'XPF' => 0,
1214
- )
1215
- );
1216
- }
1217
-
1218
- /**
1219
- * Function that triggers a filter on the order id.
1220
- * Allows 3rd parties to
1221
- * convert the order_id from the metadata of the Stripe object.
1222
- *
1223
- * @param int $order_id
1224
- * @param \Stripe\ApiResource $object
1225
- *
1226
- * @since 3.1.3
1227
- * @package Stripe/Functions
1228
- */
1229
- function wc_stripe_filter_order_id( $order_id, $object ) {
1230
- return apply_filters( 'wc_stripe_filter_order_id', $order_id, $object );
1231
- }
1232
-
1233
- /**
1234
- * Removes order locks that have expired so the options table does not get cluttered with transients.
1235
- * @since 3.1.6
1236
- * @package Stripe/Functions
1237
- */
1238
- function wc_stripe_remove_order_locks() {
1239
- global $wpdb;
1240
-
1241
- // this operation could take some time, ensure it completes.
1242
- wc_set_time_limit();
1243
-
1244
- $results = $wpdb->get_results( $wpdb->prepare( "SELECT option_name FROM $wpdb->options WHERE option_name LIKE %s AND option_value < %d", '_transient_timeout_stripe_lock_order_%', time() ) );
1245
- if ( $results ) {
1246
- foreach ( $results as $result ) {
1247
- // call delete_transient so Wordpress can fire all it's transient actions.
1248
- delete_transient( substr( $result->option_name, strlen( '_transient_timeout_' ) ) );
1249
- }
1250
- }
1251
- }
1252
-
1253
- /**
1254
- * Returns an array of checkout fields needed to complete an order.
1255
- * @return array
1256
- * @since 3.1.8
1257
- */
1258
- function wc_stripe_get_checkout_fields() {
1259
- global $wp;
1260
- $fields = array();
1261
- $order = false;
1262
- if ( ! empty( $wp->query_vars['order-pay'] ) ) {
1263
- $order = wc_get_order( absint( ( $wp->query_vars['order-pay'] ) ) );
1264
- }
1265
- foreach ( array( 'billing', 'shipping' ) as $key ) {
1266
- if ( ( $field_set = WC()->checkout()->get_checkout_fields( $key ) ) ) {
1267
- $fields = array_merge( $fields, $field_set );
1268
- }
1269
- }
1270
- // loop through fields and assign their value to the field.
1271
- array_walk( $fields, function ( &$field, $key ) use ( $order ) {
1272
- if ( $order ) {
1273
- if ( is_callable( array( $order, "get_{$key}" ) ) ) {
1274
- $field['value'] = $order->{"get_{$key}"}();
1275
- } else {
1276
- $field['value'] = WC()->checkout()->get_value( $key );
1277
- }
1278
- } else {
1279
- $field['value'] = WC()->checkout()->get_value( $key );
1280
- }
1281
- /**
1282
- * Some 3rd party plugins hook in to WC filters and alter the expected
1283
- * type for required. This ensures it's converted back to a boolean.
1284
- */
1285
- if ( isset( $field['required'] ) && ! is_bool( $field['required'] ) ) {
1286
- $field['required'] = (bool) $field['required'];
1287
- }
1288
- } );
1289
-
1290
- return $fields;
1291
- }
1292
-
1293
- /**
1294
- * Filters a state value, making sure the abbreviated state value recognized by WC is returned.
1295
- * Example: Texas = TX
1296
- *
1297
- * @param string $state
1298
- * @param string $country
1299
- *
1300
- * @return string
1301
- *
1302
- * @since 3.2.1
1303
- */
1304
- function wc_stripe_filter_address_state( $state, $country ) {
1305
- $states = WC()->countries ? WC()->countries->get_states( $country ) : array();
1306
- if ( ! empty( $states ) && is_array( $states ) && ! isset( $states[ $state ] ) ) {
1307
- $state_keys = array_flip( array_map( 'strtoupper', $states ) );
1308
- if ( isset( $state_keys[ strtoupper( $state ) ] ) ) {
1309
- $state = $state_keys[ strtoupper( $state ) ];
1310
- }
1311
- }
1312
-
1313
- return $state;
1314
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ defined( 'ABSPATH' ) || exit();
3
+
4
+ /**
5
+ *
6
+ * @param string $template_name
7
+ * @param array $args
8
+ *
9
+ * @since 3.0.0
10
+ * @package Stripe/Functions
11
+ * Wrapper for wc_get_template that returns Stripe specfic templates.
12
+ */
13
+ function wc_stripe_get_template( $template_name, $args = array() ) {
14
+ wc_get_template( $template_name, $args, wc_stripe()->template_path(), wc_stripe()->default_template_path() );
15
+ }
16
+
17
+ /**
18
+ *
19
+ *
20
+ * Wrapper for wc_get_template_html that returns Stripe specififc templates in an html string.
21
+ *
22
+ * @param string $template_name
23
+ * @param array $args
24
+ *
25
+ * @return string
26
+ * @since 3.0.0
27
+ * @package Stripe/Functions
28
+ */
29
+ function wc_stripe_get_template_html( $template_name, $args = array() ) {
30
+ return wc_get_template_html( $template_name, $args, wc_stripe()->template_path(), wc_stripe()->default_template_path() );
31
+ }
32
+
33
+ /**
34
+ * Return true if WCS is active.
35
+ *
36
+ * @return boolean
37
+ * @package Stripe/Functions
38
+ */
39
+ function wcs_stripe_active() {
40
+ return function_exists( 'wcs_is_subscription' );
41
+ }
42
+
43
+ /**
44
+ *
45
+ * @param WC_Payment_Gateway_Stripe $gateway
46
+ *
47
+ * @package Stripe/Functions
48
+ */
49
+ function wc_stripe_token_field( $gateway ) {
50
+ wc_stripe_hidden_field( $gateway->token_key, 'wc-stripe-token-field' );
51
+ }
52
+
53
+ /**
54
+ *
55
+ * @param WC_Payment_Gateway_Stripe $gateway
56
+ *
57
+ * @package Stripe/Functions
58
+ */
59
+ function wc_stripe_payment_intent_field( $gateway ) {
60
+ wc_stripe_hidden_field( $gateway->payment_intent_key, 'wc-stripe-payment-intent-field' );
61
+ }
62
+
63
+ /**
64
+ *
65
+ * @param string $id
66
+ * @param string $class
67
+ * @param string $value
68
+ *
69
+ * @package Stripe/Functions
70
+ */
71
+ function wc_stripe_hidden_field( $id, $class = '', $value = '' ) {
72
+ printf( '<input type="hidden" class="%1$s" id="%2$s" name="%2$s" value="%3$s"/>', $class, $id, $value );
73
+ }
74
+
75
+ /**
76
+ * Return the mode for the plugin.
77
+ *
78
+ * @return string
79
+ * @package Stripe/Functions
80
+ */
81
+ function wc_stripe_mode() {
82
+ return apply_filters( 'wc_stripe_mode', wc_stripe()->api_settings->get_option( 'mode' ) );
83
+ }
84
+
85
+ /**
86
+ * Return the secret key for the provided mode.
87
+ * If no mode given, the key for the active mode is returned.
88
+ *
89
+ * @param string $mode
90
+ *
91
+ * @since 3.0.0
92
+ * @package Stripe/Functions
93
+ */
94
+ function wc_stripe_get_secret_key( $mode = '' ) {
95
+ $mode = empty( $mode ) ? wc_stripe_mode() : $mode;
96
+
97
+ return apply_filters( 'wc_stripe_get_secret_key', wc_stripe()->api_settings->get_option( "secret_key_{$mode}" ), $mode );
98
+ }
99
+
100
+ /**
101
+ * Return the publishable key for the provided mode.
102
+ * If no mode given, the key for the active mode is returned.
103
+ *
104
+ * @param string $mode
105
+ *
106
+ * @since 3.0.0
107
+ * @package Stripe/Functions
108
+ */
109
+ function wc_stripe_get_publishable_key( $mode = '' ) {
110
+ $mode = empty( $mode ) ? wc_stripe_mode() : $mode;
111
+
112
+ return apply_filters( 'wc_stripe_get_publishable_key', wc_stripe()->api_settings->get_option( "publishable_key_{$mode}" ), $mode );
113
+ }
114
+
115
+ /**
116
+ * Return the merchant's Stripe account.
117
+ *
118
+ * @return string
119
+ * @since 3.1.4
120
+ * @package Stripe/Functions
121
+ */
122
+ function wc_stripe_get_account_id() {
123
+ return apply_filters( 'wc_stripe_get_account_id', wc_stripe()->api_settings->get_option( 'account_id' ) );
124
+ }
125
+
126
+ /**
127
+ * Return the stripe customer ID
128
+ *
129
+ * @param int $user_id
130
+ * @param string $mode
131
+ *
132
+ * @package Stripe/Functions
133
+ * @since 3.0.0
134
+ */
135
+ function wc_stripe_get_customer_id( $user_id = '', $mode = '' ) {
136
+ $mode = empty( $mode ) ? wc_stripe_mode() : $mode;
137
+ if ( $user_id === 0 ) {
138
+ return '';
139
+ }
140
+ if ( empty( $user_id ) ) {
141
+ $user_id = get_current_user_id();
142
+ }
143
+
144
+ return get_user_meta( $user_id, "wc_stripe_customer_{$mode}", true );
145
+ }
146
+
147
+ /**
148
+ *
149
+ * @param string $customer_id
150
+ * @param int $user_id
151
+ * @param string $mode
152
+ *
153
+ * @package Stripe/Functions
154
+ */
155
+ function wc_stripe_save_customer( $customer_id, $user_id, $mode = '' ) {
156
+ $mode = empty( $mode ) ? wc_stripe_mode() : $mode;
157
+ $key = "wc_stripe_customer_{$mode}";
158
+ update_user_meta( $user_id, $key, $customer_id );
159
+ }
160
+
161
+ /**
162
+ *
163
+ * @param int $token_id
164
+ * @param WC_Payment_Token $token
165
+ *
166
+ * @since 3.0.0
167
+ * @package Stripe/Functions
168
+ */
169
+ function wc_stripe_woocommerce_payment_token_deleted( $token_id, $token ) {
170
+ if ( ! did_action( 'woocommerce_payment_gateways' ) ) {
171
+ WC_Payment_Gateways::instance();
172
+ }
173
+ do_action( 'wc_stripe_payment_token_deleted_' . $token->get_gateway_id(), $token_id, $token );
174
+ }
175
+
176
+ /**
177
+ * Log the provided message in the WC logs directory.
178
+ *
179
+ * @param int $level
180
+ * @param string $message
181
+ *
182
+ * @since 3.0.0
183
+ * @package Stripe/Functions
184
+ */
185
+ function wc_stripe_log( $level, $message ) {
186
+ if ( wc_stripe()->api_settings->is_active( 'debug_log' ) ) {
187
+ $log = wc_get_logger();
188
+ $log->log( $level, $message, array( 'source' => 'wc-stripe' ) );
189
+ }
190
+ }
191
+
192
+ /**
193
+ *
194
+ * @param string $message
195
+ *
196
+ * @package Stripe/Functions
197
+ * @since 3.0.0
198
+ */
199
+ function wc_stripe_log_error( $message ) {
200
+ wc_stripe_log( WC_Log_Levels::ERROR, $message );
201
+ }
202
+
203
+ /**
204
+ *
205
+ * @param string $message
206
+ *
207
+ * @package Stripe/Functions
208
+ * @since 3.0.0
209
+ */
210
+ function wc_stripe_log_info( $message ) {
211
+ wc_stripe_log( WC_Log_Levels::INFO, $message );
212
+ }
213
+
214
+ /**
215
+ * Return the mode that the order was created in.
216
+ * Values can be <strong>live</strong> or <strong>test</strong>
217
+ *
218
+ * @param WC_Order|int $order
219
+ *
220
+ * @package Stripe/Functions
221
+ * @since 3.0.0
222
+ */
223
+ function wc_stripe_order_mode( $order ) {
224
+ if ( is_object( $order ) ) {
225
+ return $order->get_meta( WC_Stripe_Constants::MODE, true );
226
+ }
227
+
228
+ return get_post_meta( $order, WC_Stripe_Constants::MODE, true );
229
+ }
230
+
231
+ /**
232
+ *
233
+ * @param array $gateways
234
+ *
235
+ * @package Stripe\Functions
236
+ * @since 3.0.0
237
+ */
238
+ function wc_stripe_payment_gateways( $gateways ) {
239
+ return array_merge( $gateways, wc_stripe()->payment_gateways() );
240
+ }
241
+
242
+ /**
243
+ * Cancel the Stripe charge
244
+ *
245
+ * @param int $order_id
246
+ * @param WC_Order $order
247
+ *
248
+ * @package Stripe/Functions
249
+ */
250
+ function wc_stripe_order_cancelled( $order_id, $order ) {
251
+ $gateways = WC()->payment_gateways()->payment_gateways();
252
+ /**
253
+ *
254
+ * @var WC_Payment_Gateway_Stripe $gateway
255
+ */
256
+ $gateway = isset( $gateways[ $order->get_payment_method() ] ) ? $gateways[ $order->get_payment_method() ] : null;
257
+
258
+ if ( $gateway && $gateway instanceof WC_Payment_Gateway_Stripe ) {
259
+ $gateway->void_charge( $order );
260
+ }
261
+ }
262
+
263
+ /**
264
+ *
265
+ * @param int $order_id
266
+ * @param WC_Order $order
267
+ *
268
+ * @since 3.0.0
269
+ * @package Stripe/Functions
270
+ */
271
+ function wc_stripe_order_status_completed( $order_id, $order ) {
272
+ $gateways = WC()->payment_gateways()->payment_gateways();
273
+ /**
274
+ *
275
+ * @var WC_Payment_Gateway_Stripe $gateway
276
+ */
277
+ $gateway = isset( $gateways[ $order->get_payment_method() ] ) ? $gateways[ $order->get_payment_method() ] : null;
278
+ // @since 3.0.3 check added to ensure this is a Stripe gateway.
279
+ if ( $gateway && $gateway instanceof WC_Payment_Gateway_Stripe && ! $gateway->processing_payment ) {
280
+ $gateway->capture_charge( $order->get_total(), $order );
281
+ }
282
+ }
283
+
284
+ /**
285
+ *
286
+ * @param [] $address
287
+ *
288
+ * @throws Exception
289
+ * @since 3.0.0
290
+ * @package Stripe/Functions
291
+ */
292
+ function wc_stripe_update_customer_location( $address ) {
293
+ // address validation for countries other than US is problematic when using responses from payment sources like
294
+ // Apple Pay.
295
+ if ( $address['postcode'] && $address['country'] === 'US' && ! WC_Validation::is_postcode( $address['postcode'], $address['country'] ) ) {
296
+ throw new Exception( __( 'Please enter a valid postcode / ZIP.', 'woocommerce' ) );
297
+ } elseif ( $address['postcode'] ) {
298
+ $address['postcode'] = wc_format_postcode( $address['postcode'], $address['country'] );
299
+ }
300
+
301
+ if ( $address['country'] ) {
302
+ WC()->customer->set_billing_location( $address['country'], $address['state'], $address['postcode'], $address['city'] );
303
+ WC()->customer->set_shipping_location( $address['country'], $address['state'], $address['postcode'], $address['city'] );
304
+ // set the customer's address if it's in the $address array
305
+ if ( ! empty( $address['address_1'] ) ) {
306
+ WC()->customer->set_shipping_address_1( wc_clean( $address['address_1'] ) );
307
+ }
308
+ if ( ! empty( $address['address_2'] ) ) {
309
+ WC()->customer->set_shipping_address_2( wc_clean( $address['address_2'] ) );
310
+ }
311
+ if ( ! empty( $address['first_name'] ) ) {
312
+ WC()->customer->set_shipping_first_name( $address['first_name'] );
313
+ }
314
+ if ( ! empty( $address['last_name'] ) ) {
315
+ WC()->customer->set_shipping_last_name( $address['last_name'] );
316
+ }
317
+ } else {
318
+ WC()->customer->set_billing_address_to_base();
319
+ WC()->customer->set_shipping_address_to_base();
320
+ }
321
+
322
+ WC()->customer->set_calculated_shipping( true );
323
+ WC()->customer->save();
324
+
325
+ do_action( 'woocommerce_calculated_shipping' );
326
+ }
327
+
328
+ /**
329
+ *
330
+ * @param [] $methods
331
+ *
332
+ * @package Stripe/Functions
333
+ * @since 3.0.0
334
+ */
335
+ function wc_stripe_update_shipping_methods( $methods ) {
336
+ $chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods', array() );
337
+
338
+ foreach ( $methods as $i => $method ) {
339
+ $chosen_shipping_methods[ $i ] = $method;
340
+ }
341
+
342
+ WC()->session->set( 'chosen_shipping_methods', $chosen_shipping_methods );
343
+ }
344
+
345
+ /**
346
+ * Return true if there are shipping packages that contain rates.
347
+ *
348
+ * @param array $packages
349
+ *
350
+ * @return boolean
351
+ * @package Stripe/Functions
352
+ * @since 3.0.0
353
+ */
354
+ function wc_stripe_shipping_address_serviceable( $packages = array() ) {
355
+ if ( $packages ) {
356
+ foreach ( $packages as $package ) {
357
+ if ( count( $package['rates'] ) > 0 ) {
358
+ return true;
359
+ }
360
+ }
361
+ }
362
+
363
+ return false;
364
+ }
365
+
366
+ /**
367
+ *
368
+ * @param string $page
369
+ * @param WC_Order $order
370
+ *
371
+ * @package Stripe/Functions
372
+ * @since 3.0.0
373
+ * @deprecated
374
+ */
375
+ function wc_stripe_get_display_items( $page = 'cart', $order = null ) {
376
+ // first argument used to be $encode param so make sure it's a string now
377
+ $page = false === $page ? 'cart' : $page;
378
+ $items = array();
379
+ if ( in_array( $page, array( 'cart', 'checkout' ) ) ) {
380
+ $cart = WC()->cart;
381
+ $incl_tax = wc_stripe_display_prices_including_tax();
382
+
383
+ foreach ( $cart->get_cart() as $cart_item ) {
384
+ /**
385
+ *
386
+ * @var WC_Product $product
387
+ */
388
+ $product = $cart_item['data'];
389
+ $qty = $cart_item['quantity'];
390
+ $items[] = array(
391
+ 'label' => $qty > 1 ? sprintf( '%s X %s', $product->get_name(), $qty ) : $product->get_name(),
392
+ 'pending' => false,
393
+ 'amount' => wc_stripe_add_number_precision(
394
+ $incl_tax ? wc_get_price_including_tax( $product, array( 'qty' => $qty ) ) : wc_get_price_excluding_tax(
395
+ $product,
396
+ array(
397
+ 'qty' => $qty,
398
+ )
399
+ )
400
+ ),
401
+ );
402
+ }
403
+ if ( $cart->needs_shipping() ) {
404
+ $items[] = array(
405
+ 'label' => __( 'Shipping', 'woo-stripe-payment' ),
406
+ 'pending' => false,
407
+ 'amount' => wc_stripe_add_number_precision( $incl_tax ? $cart->shipping_total + $cart->shipping_tax_total : $cart->shipping_total ),
408
+ );
409
+ }
410
+
411
+ // fees
412
+ foreach ( $cart->get_fees() as $fee ) {
413
+ $items[] = array(
414
+ 'label' => $fee->name,
415
+ 'pending' => false,
416
+ 'amount' => wc_stripe_add_number_precision( $incl_tax ? $fee->total + $fee->tax : $fee->total ),
417
+ );
418
+ }
419
+ // coupons
420
+ if ( 0 < $cart->discount_cart ) {
421
+ $items[] = array(
422
+ 'label' => __( 'Discount', 'woo-stripe-payment' ),
423
+ 'pending' => false,
424
+ 'amount' => wc_stripe_add_number_precision( - 1 * abs( $incl_tax ? $cart->discount_cart + $cart->discount_cart_tax : $cart->discount_cart ) ),
425
+ );
426
+ }
427
+
428
+ if ( ! $incl_tax && wc_tax_enabled() ) {
429
+ $item = array(
430
+ 'label' => __( 'Tax', 'woo-stripe-payment' ),
431
+ 'pending' => false,
432
+ 'amount' => wc_stripe_add_number_precision( $cart->get_taxes_total() ),
433
+ );
434
+ if ( 'itemized' === get_option( 'woocommerce_tax_total_display' ) ) {
435
+ if ( 0 < WC()->cart->get_taxes_total() ) {
436
+ $items[] = $item;
437
+ }
438
+ } else {
439
+ $items[] = $item;
440
+ }
441
+ }
442
+ } elseif ( 'product' === $page ) {
443
+ global $product;
444
+ $items[] = array(
445
+ 'amount' => wc_stripe_add_number_precision( $product->get_price() ),
446
+ 'label' => esc_attr( $product->get_name() ),
447
+ 'pending' => true,
448
+ );
449
+ } elseif ( 'order_pay' === $page ) {
450
+ global $wp;
451
+ $order = ! $order ? wc_get_order( absint( $wp->query_vars['order-pay'] ) ) : $order;
452
+ $currency = $order->get_currency();
453
+ // add all order items
454
+ foreach ( $order->get_items() as $item ) {
455
+ /**
456
+ *
457
+ * @var WC_Order_Item_Product $item
458
+ */
459
+ $qty = $item->get_quantity();
460
+
461
+ $items[] = array(
462
+ 'label' => $qty > 1 ? sprintf( '%s X %s', $item->get_name(), $qty ) : $item->get_name(),
463
+ 'pending' => false,
464
+ 'amount' => wc_stripe_add_number_precision( $item->get_subtotal(), $currency ),
465
+ );
466
+ }
467
+ // shipping total
468
+ if ( 0 < $order->get_shipping_total() ) {
469
+ $items[] = array(
470
+ 'label' => __( 'Shipping', 'woo-stripe-payment' ),
471
+ 'pending' => false,
472
+ 'amount' => wc_stripe_add_number_precision( $order->get_shipping_total(), $currency ),
473
+ );
474
+ }
475
+ // discount total
476
+ if ( 0 < $order->get_total_discount() ) {
477
+ $items[] = array(
478
+ 'label' => __( 'Discount', 'woo-stripe-payment' ),
479
+ 'pending' => false,
480
+ 'amount' => wc_stripe_add_number_precision( - 1 * $order->get_total_discount(), $currency ),
481
+ );
482
+ }
483
+ if ( 0 < $order->get_fees() ) {
484
+ $fee_total = 0;
485
+ foreach ( $order->get_fees() as $fee ) {
486
+ $fee_total += $fee->get_total();
487
+ }
488
+ $items[] = array(
489
+ 'label' => __( 'Fees', 'woo-stripe-payment' ),
490
+ 'pending' => false,
491
+ 'amount' => wc_stripe_add_number_precision( $fee_total, $currency ),
492
+ );
493
+ }
494
+ // tax total
495
+ if ( 0 < $order->get_total_tax() ) {
496
+ $items[] = array(
497
+ 'label' => __( 'Tax', 'woocommerce' ),
498
+ 'pending' => false,
499
+ 'amount' => wc_stripe_add_number_precision( $order->get_total_tax(), $currency ),
500
+ );
501
+ }
502
+ }
503
+
504
+ /**
505
+ * @param array $items
506
+ * @param WC_Order $order
507
+ */
508
+ return apply_filters( 'wc_stripe_get_display_items', $items, $order );
509
+ }
510
+
511
+ /**
512
+ *
513
+ * @param WC_Order $order
514
+ * @param array $packages
515
+ *
516
+ * @return mixed
517
+ * @package Stripe/Functions
518
+ * @since 3.0.0
519
+ * @deprecated
520
+ */
521
+ function wc_stripe_get_shipping_options( $order = null, $packages = array() ) {
522
+ $methods = array();
523
+ $incl_tax = wc_stripe_display_prices_including_tax();
524
+ $ids = array();
525
+ $chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods', array() );
526
+ $packages = empty( $packages ) ? WC()->shipping()->get_packages() : $packages;
527
+ foreach ( $packages as $i => $package ) {
528
+ foreach ( $package['rates'] as $rate ) {
529
+ /**
530
+ *
531
+ * @var WC_Shipping_Rate $rate
532
+ */
533
+ $method = array(
534
+ 'id' => sprintf( '%s:%s', $i, $rate->id ),
535
+ 'label' => sprintf( '%s', esc_attr( $rate->get_label() ) ),
536
+ 'detail' => '',
537
+ 'amount' => wc_stripe_add_number_precision( $incl_tax ? $rate->cost + $rate->get_shipping_tax() : $rate->cost ),
538
+ );
539
+ if ( $incl_tax ) {
540
+ if ( $rate->get_shipping_tax() > 0 && ! wc_prices_include_tax() ) {
541
+ $method['detail'] = WC()->countries->inc_tax_or_vat();
542
+ }
543
+ } else {
544
+ if ( $rate->get_shipping_tax() > 0 && wc_prices_include_tax() ) {
545
+ $method['detail'] = WC()->countries->ex_tax_or_vat();
546
+ }
547
+ }
548
+ $methods[] = $method;
549
+ if ( isset( $chosen_shipping_methods[ $i ] ) && $chosen_shipping_methods[ $i ] === $rate->id ) {
550
+ $ids[] = $method['id'];
551
+ }
552
+ }
553
+ /**
554
+ * Sort the shipping methods so that the selected method is always first
555
+ * in the array.
556
+ */
557
+ usort( $methods, function ( $a, $b ) use ( $ids ) {
558
+ return in_array( $a['id'], $ids ) ? - 1 : 1;
559
+ } );
560
+ }
561
+
562
+ /**
563
+ *
564
+ * @param array $methods
565
+ * @param WC_Order $orer
566
+ */
567
+ return apply_filters( 'wc_stripe_get_shipping_options', $methods, $order );
568
+ }
569
+
570
+ /**
571
+ *
572
+ * @since 3.0.0
573
+ * @package Stripe/Functions
574
+ */
575
+ function wc_stripe_set_checkout_error() {
576
+ add_action( 'woocommerce_after_template_part', 'wc_stripe_output_checkout_error' );
577
+ }
578
+
579
+ /**
580
+ *
581
+ * @param string $template_name
582
+ *
583
+ * @package Stripe/Functions
584
+ * @since 3.0.0
585
+ */
586
+ function wc_stripe_output_checkout_error( $template_name ) {
587
+ if ( $template_name === 'notices/error.php' && is_ajax() ) {
588
+ echo '<input type="hidden" id="wc_stripe_checkout_error" value="true"/>';
589
+ remove_action( 'woocommerce_after_template_part', 'wc_stripe_output_checkout_error' );
590
+ add_filter( 'wp_kses_allowed_html', 'wc_stripe_add_allowed_html', 10, 2 );
591
+ }
592
+ }
593
+
594
+ /**
595
+ *
596
+ * @since 3.0.0
597
+ * @package Stripe/Functions
598
+ */
599
+ function wc_stripe_add_allowed_html( $tags, $context ) {
600
+ if ( $context === 'post' ) {
601
+ $tags['input'] = array(
602
+ 'id' => true,
603
+ 'type' => true,
604
+ 'value' => true,
605
+ );
606
+ }
607
+
608
+ return $tags;
609
+ }
610
+
611
+ /**
612
+ * Save WCS meta data when it's changed in the admin section.
613
+ * By default WCS saves the
614
+ * payment method title as the gateway title. This method saves the payment method title in
615
+ * a human readable format suitable for the frontend.
616
+ *
617
+ * @param int $post_id
618
+ * @param WP_Post $post
619
+ *
620
+ * @package Stripe/Functions
621
+ */
622
+ function wc_stripe_process_shop_subscription_meta( $post_id, $post ) {
623
+ $subscription = wcs_get_subscription( $post_id );
624
+ $gateway_id = $subscription->get_payment_method();
625
+ $gateways = WC()->payment_gateways()->payment_gateways();
626
+ if ( isset( $gateways[ $gateway_id ] ) ) {
627
+ $gateway = $gateways[ $gateway_id ];
628
+ if ( $gateway instanceof WC_Payment_Gateway_Stripe ) {
629
+ $token = $gateway->get_token( $subscription->get_meta( WC_Stripe_Constants::PAYMENT_METHOD_TOKEN ), $subscription->get_customer_id() );
630
+ if ( $token ) {
631
+ $subscription->set_payment_method_title( $token->get_payment_method_title() );
632
+ $subscription->save();
633
+ }
634
+ }
635
+ }
636
+ }
637
+
638
+ /**
639
+ * Filter the WC payment gateways based on criteria specific to Stripe functionality.
640
+ *
641
+ * <strong>Example:</strong> on add payment method page, only show the CC gateway for Stripe.
642
+ *
643
+ * @param WC_Payment_Gateway[] $gateways
644
+ *
645
+ * @package Stripe/Functions
646
+ * @since 3.0.0
647
+ */
648
+ function wc_stripe_available_payment_gateways( $gateways ) {
649
+ global $wp;
650
+ if ( is_add_payment_method_page() && ! isset( $wp->query_vars['payment-methods'] ) ) {
651
+ foreach ( $gateways as $gateway ) {
652
+ if ( $gateway instanceof WC_Payment_Gateway_Stripe ) {
653
+ if ( 'stripe_cc' !== $gateway->id ) {
654
+ unset( $gateways[ $gateway->id ] );
655
+ }
656
+ }
657
+ }
658
+ }
659
+
660
+ return $gateways;
661
+ }
662
+
663
+ /**
664
+ *
665
+ * @return array
666
+ * @package Stripe/Functions
667
+ * @since 3.0.0
668
+ */
669
+ function wc_stripe_get_local_payment_params() {
670
+ global $wp;
671
+ $data = array();
672
+ $gateways = WC()->payment_gateways()->payment_gateways();
673
+ foreach ( $gateways as $gateway ) {
674
+ if ( $gateway instanceof WC_Payment_Gateway_Stripe_Local_Payment && $gateway->is_available() ) {
675
+ $data['gateways'][ $gateway->id ] = $gateway->get_localized_params();
676
+ if ( isset( $wp->query_vars['order-pay'] ) ) {
677
+ $data['gateways'][ $gateway->id ]['order_id'] = $wp->query_vars['order-pay'];
678
+ }
679
+ }
680
+ }
681
+ $data['api_key'] = wc_stripe_get_publishable_key();
682
+
683
+ return $data;
684
+ }
685
+
686
+ /**
687
+ *
688
+ * @param array $gateways
689
+ *
690
+ * @return WC_Payment_Gateway[]
691
+ * @package Stripe/Functions
692
+ * @since 3.0.0
693
+ */
694
+ function wc_stripe_get_available_local_gateways( $gateways ) {
695
+ foreach ( $gateways as $gateway ) {
696
+ if ( $gateway instanceof WC_Payment_Gateway_Stripe_Local_Payment ) {
697
+ if ( ! $gateway->is_local_payment_available() ) {
698
+ unset( $gateways[ $gateway->id ] );
699
+ }
700
+ }
701
+ }
702
+
703
+ return $gateways;
704
+ }
705
+
706
+ /**
707
+ *
708
+ * @param string|int $key
709
+ *
710
+ * @package Stripe/Functions
711
+ * @since 3.0.0
712
+ */
713
+ function wc_stripe_set_idempotency_key( $key ) {
714
+ global $wc_stripe_idempotency_key;
715
+ $wc_stripe_idempotency_key = $key;
716
+ }
717
+
718
+ /**
719
+ *
720
+ * @return mixed
721
+ * @package Stripe/Functions
722
+ * @since 3.0.0
723
+ */
724
+ function wc_stripe_get_idempotency_key() {
725
+ global $wc_stripe_idempotency_key;
726
+
727
+ return $wc_stripe_idempotency_key;
728
+ }
729
+
730
+ /**
731
+ *
732
+ * @param array $options
733
+ *
734
+ * @return array
735
+ * @since 3.0.0
736
+ * @package Stripe/Functions
737
+ */
738
+ function wc_stripe_api_options( $options ) {
739
+ $key = wc_stripe_get_idempotency_key();
740
+ if ( $key ) {
741
+ $options['idempotency_key'] = $key;
742
+ }
743
+
744
+ return $options;
745
+ }
746
+
747
+ /**
748
+ *
749
+ * @param string $order_status
750
+ * @param int $order_id
751
+ * @param WC_Order $order
752
+ *
753
+ * @package Stripe/Functions
754
+ * @since 3.0.0
755
+ * <br/><strong>3.1.7</strong> - default $order argument of null added to prevent errors when 3rd party plugins trigger
756
+ * action woocommerce_payment_complete_order_status and don't pass three arguments.
757
+ */
758
+ function wc_stripe_payment_complete_order_status( $order_status, $order_id, $order = null ) {
759
+ if ( is_checkout() && $order && $order->get_payment_method() ) {
760
+ $gateway = WC()->payment_gateways()->payment_gateways()[ $order->get_payment_method() ];
761
+ if ( $gateway instanceof WC_Payment_Gateway_Stripe && 'default' !== $gateway->get_option( 'order_status' ) ) {
762
+ $order_status = $gateway->get_option( 'order_status' );
763
+ }
764
+ }
765
+
766
+ return $order_status;
767
+ }
768
+
769
+ /**
770
+ * Converts the amount to cents.
771
+ * Stripe processes all requests in cents.
772
+ *
773
+ * @param float $value
774
+ * @param string $currency
775
+ * @param string $round
776
+ *
777
+ * @return number
778
+ * @package Stripe/Functions
779
+ * @since 3.0.0
780
+ */
781
+ function wc_stripe_add_number_precision( $value, $currency = '', $round = true ) {
782
+ if ( ! is_numeric( $value ) ) {
783
+ $value = 0;
784
+ }
785
+ $currency = empty( $currency ) ? get_woocommerce_currency() : $currency;
786
+ $currencies = wc_stripe_get_currencies();
787
+ $exp = isset( $currencies[ $currency ] ) ? $currencies[ $currency ] : 2;
788
+ $cent_precision = pow( 10, $exp );
789
+ $value = $value * $cent_precision;
790
+ $value = $round ? round( $value, wc_get_rounding_precision() - wc_get_price_decimals() ) : $value;
791
+
792
+ if ( is_numeric( $value ) && floor( $value ) != $value ) {
793
+ // there are some decimal points that need to be removed.
794
+ $value = round( $value );
795
+ }
796
+
797
+ return $value;
798
+ }
799
+
800
+ /**
801
+ * Return an array of credit card forms.
802
+ *
803
+ * @return mixed
804
+ * @package Stripe/Functions
805
+ * @since 3.0.0
806
+ */
807
+ function wc_stripe_get_custom_forms() {
808
+ return apply_filters(
809
+ 'wc_stripe_get_custom_forms',
810
+ array(
811
+ 'bootstrap' => array(
812
+ 'template' => 'cc-forms/bootstrap.php',
813
+ 'label' => __( 'Bootstrap form', 'woo-stripe-payment' ),
814
+ 'cardBrand' => wc_stripe()->assets_url( 'img/card_brand2.svg' ),
815
+ 'elementStyles' => array(
816
+ 'base' => array(
817
+ 'color' => '#495057',
818
+ 'fontWeight' => 300,
819
+ 'fontFamily' => 'Roboto, sans-serif, Source Code Pro, Consolas, Menlo, monospace',
820
+ 'fontSize' => '16px',
821
+ 'fontSmoothing' => 'antialiased',
822
+ '::placeholder' => array(
823
+ 'color' => '#fff',
824
+ 'fontSize' => '0px',
825
+ ),
826
+ ':-webkit-autofill' => array( 'color' => '#495057' ),
827
+ ),
828
+ 'invalid' => array(
829
+ 'color' => '#E25950',
830
+ '::placeholder' => array( 'color' => '#757575' ),
831
+ ),
832
+ ),
833
+ 'elementOptions' => array(
834
+ 'fonts' => array( array( 'cssSrc' => 'https://fonts.googleapis.com/css?family=Source+Code+Pro' ) ),
835
+ ),
836
+ ),
837
+ 'simple' => array(
838
+ 'template' => 'cc-forms/simple.php',
839
+ 'label' => __( 'Simple form', 'woo-stripe-payment' ),
840
+ 'cardBrand' => wc_stripe()->assets_url( 'img/card_brand2.svg' ),
841
+ 'elementStyles' => array(
842
+ 'base' => array(
843
+ 'color' => '#32325D',
844
+ 'fontWeight' => 500,
845
+ 'fontFamily' => 'Source Code Pro, Consolas, Menlo, monospace',
846
+ 'fontSize' => '16px',
847
+ 'fontSmoothing' => 'antialiased',
848
+ '::placeholder' => array( 'color' => '#CFD7DF' ),
849
+ ':-webkit-autofill' => array( 'color' => '#32325D' ),
850
+ ),
851
+ 'invalid' => array(
852
+ 'color' => '#E25950',
853
+ '::placeholder' => array( 'color' => '#FFCCA5' ),
854
+ ),
855
+ ),
856
+ 'elementOptions' => array(
857
+ 'fonts' => array( array( 'cssSrc' => 'https://fonts.googleapis.com/css?family=Source+Code+Pro' ) ),
858
+ ),
859
+ ),
860
+ 'minimalist' => array(
861
+ 'template' => 'cc-forms/minimalist.php',
862
+ 'label' => __( 'Minimalist form', 'woo-stripe-payment' ),
863
+ 'cardBrand' => wc_stripe()->assets_url( 'img/card_brand2.svg' ),
864
+ 'elementStyles' => array(
865
+ 'base' => array(
866
+ 'color' => '#495057',
867
+ 'fontWeight' => 300,
868
+ 'fontFamily' => 'Roboto, sans-serif, Source Code Pro, Consolas, Menlo, monospace',
869
+ 'fontSize' => '30px',
870
+ 'fontSmoothing' => 'antialiased',
871
+ '::placeholder' => array(
872
+ 'color' => '#fff',
873
+ 'fontSize' => '0px',
874
+ ),
875
+ ':-webkit-autofill' => array( 'color' => '#495057' ),
876
+ ),
877
+ 'invalid' => array(
878
+ 'color' => '#495057',
879
+ '::placeholder' => array( 'color' => '#495057' ),
880
+ ),
881
+ ),
882
+ 'elementOptions' => array(
883
+ 'fonts' => array( array( 'cssSrc' => 'https://fonts.googleapis.com/css?family=Source+Code+Pro' ) ),
884
+ ),
885
+ ),
886
+ 'inline' => array(
887
+ 'template' => 'cc-forms/inline.php',
888
+ 'label' => __( 'Inline Form', 'woo-stripe-payment' ),
889
+ 'cardBrand' => wc_stripe()->assets_url( 'img/card_brand.svg' ),
890
+ 'elementStyles' => array(
891
+ 'base' => array(
892
+ 'color' => '#819efc',
893
+ 'fontWeight' => 600,
894
+ 'fontFamily' => 'Roboto, Open Sans, Segoe UI, sans-serif',
895
+ 'fontSize' => '16px',
896
+ 'fontSmoothing' => 'antialiased',
897
+ ':focus' => array( 'color' => '#819efc' ),
898
+ '::placeholder' => array( 'color' => '#87BBFD' ),
899
+ ':focus::placeholder' => array( 'color' => '#CFD7DF' ),
900
+ ':-webkit-autofill' => array( 'color' => '#819efc' ),
901
+ ),
902
+ 'invalid' => array( 'color' => '#f99393' ),
903
+ ),
904
+ 'elementOptions' => array(
905
+ 'fonts' => array( array( 'cssSrc' => 'https://fonts.googleapis.com/css?family=Roboto' ) ),
906
+ ),
907
+ ),
908
+ 'rounded' => array(
909
+ 'template' => 'cc-forms/round.php',
910
+ 'label' => __( 'Rounded Form', 'woo-stripe-payment' ),
911
+ 'cardBrand' => wc_stripe()->assets_url( 'img/card_brand.svg' ),
912
+ 'elementStyles' => array(
913
+ 'base' => array(
914
+ 'color' => '#fff',
915
+ 'fontWeight' => 600,
916
+ 'fontFamily' => 'Quicksand, Open Sans, Segoe UI, sans-serif',
917
+ 'fontSize' => '16px',
918
+ 'fontSmoothing' => 'antialiased',
919
+ ':focus' => array( 'color' => '#424770' ),
920
+ '::placeholder' => array( 'color' => '#9BACC8' ),
921
+ ':focus::placeholder' => array( 'color' => '#CFD7DF' ),
922
+ ':-webkit-autofill' => array( 'color' => '#fff' ),
923
+ ),
924
+ 'invalid' => array(
925
+ 'color' => '#fff',
926
+ ':focus' => array( 'color' => '#FA755A' ),
927
+ '::placeholder' => array( 'color' => '#FFCCA5' ),
928
+ ),
929
+ ),
930
+ 'elementOptions' => array(
931
+ 'fonts' => array( array( 'cssSrc' => 'https://fonts.googleapis.com/css?family=Quicksand' ) ),
932
+ ),
933
+ ),
934
+ )
935
+ );
936
+ }
937
+
938
+ /**
939
+ *
940
+ * @param WC_Order $order
941
+ *
942
+ * @since 3.0.0
943
+ * @package Stripe/Functions
944
+ */
945
+ function wc_stripe_order_has_shipping_address( $order ) {
946
+ if ( method_exists( $order, 'has_shipping_address' ) ) {
947
+ return $order->has_shipping_address();
948
+ } else {
949
+ return $order->get_shipping_address_1() || $order->get_shipping_address_2();
950
+ }
951
+ }
952
+
953
+ /**
954
+ *
955
+ * @since 3.0.0
956
+ * @package Stripe/Functions
957
+ */
958
+ function wc_stripe_display_prices_including_tax() {
959
+ $cart = WC()->cart;
960
+ if ( method_exists( $cart, 'display_prices_including_tax' ) ) {
961
+ return $cart->display_prices_including_tax();
962
+ }
963
+ if ( is_callable( array( $cart, 'get_tax_price_display_mode' ) ) ) {
964
+ return 'incl' == $cart->get_tax_price_display_mode() && ( WC()->customer && ! WC()->customer->is_vat_exempt() );
965
+ }
966
+
967
+ return 'incl' == $cart->tax_display_cart && ( WC()->customer && ! WC()->customer->is_vat_exempt() );
968
+ }
969
+
970
+ /**
971
+ * Return true if the WC pre-orders plugin is active
972
+ *
973
+ * @since 3.0.1
974
+ * @package Stripe/Functions
975
+ */
976
+ function wc_stripe_pre_orders_active() {
977
+ return class_exists( 'WC_Pre_Orders' );
978
+ }
979
+
980
+ /**
981
+ *
982
+ * @param string $source_id
983
+ *
984
+ * @package Stripe/Functions
985
+ * @since 3.0.5
986
+ */
987
+ function wc_stripe_get_order_from_source_id( $source_id ) {
988
+ global $wpdb;
989
+ $order_id = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} AS posts LEFT JOIN {$wpdb->postmeta} AS meta ON posts.ID = meta.post_id WHERE meta.meta_key = %s AND meta.meta_value = %s LIMIT 1", '_stripe_source_id', $source_id ) );
990
+
991
+ return wc_get_order( $order_id );
992
+ }
993
+
994
+ /**
995
+ *
996
+ * @param string $transaction_id
997
+ *
998
+ * @return WC_Order|WC_Refund|boolean|WC_Order_Refund
999
+ * @since 3.0.5
1000
+ * @package Stripe/Functions
1001
+ */
1002
+ function wc_stripe_get_order_from_transaction( $transaction_id ) {
1003
+ global $wpdb;
1004
+ $order_id = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} AS posts LEFT JOIN {$wpdb->postmeta} AS meta ON posts.ID = meta.post_id WHERE meta.meta_key = %s AND meta.meta_value = %s LIMIT 1", '_transaction_id', $transaction_id ) );
1005
+
1006
+ return wc_get_order( $order_id );
1007
+ }
1008
+
1009
+ /**
1010
+ * Stash the WC cart contents in the session and empty it's contents.
1011
+ * If $product_cart is true, add the stashed product(s)
1012
+ * to the cart.
1013
+ *
1014
+ * @param WC_Cart $cart
1015
+ *
1016
+ * @package Stripe/Functions
1017
+ * @todo Maybe empty cart silently so actions are not triggered that cause session data to be removed
1018
+ * from 3rd party plugins.
1019
+ *
1020
+ * @since 3.0.6
1021
+ */
1022
+ function wc_stripe_stash_cart( $cart, $product_cart = true ) {
1023
+ $data = WC()->session->get( 'wc_stripe_cart', array() );
1024
+ $data['cart'] = $cart->get_cart_for_session();
1025
+ WC()->session->set( 'wc_stripe_cart', $data );
1026
+ $cart->empty_cart( false );
1027
+ if ( $product_cart && isset( $data['product_cart'] ) ) {
1028
+ foreach ( $data['product_cart'] as $cart_item ) {
1029
+ $cart->add_to_cart( $cart_item['product_id'], $cart_item['quantity'], $cart_item['variation_id'] );
1030
+ }
1031
+ }
1032
+ }
1033
+
1034
+ /**
1035
+ *
1036
+ * @param number $product_id
1037
+ * @param number $qty
1038
+ * @param number $variation_id
1039
+ *
1040
+ * @package Stripe/Functions
1041
+ * @since 3.0.6
1042
+ */
1043
+ function wc_stripe_stash_product_cart( $cart ) {
1044
+ $data = WC()->session->get( 'wc_stripe_cart', array() );
1045
+ $data['product_cart'] = $cart->get_cart_for_session();
1046
+ WC()->session->set( 'wc_stripe_cart', $data );
1047
+ WC()->cart->set_session();
1048
+ }
1049
+
1050
+ /**
1051
+ *
1052
+ * @param WC_Cart $cart
1053
+ *
1054
+ * @package Stripe/Functions
1055
+ * @since 3.0.6
1056
+ */
1057
+ function wc_stripe_restore_cart( $cart ) {
1058
+ $data = WC()->session->get( 'wc_stripe_cart', array( 'cart' => array() ) );
1059
+ $cart->cart_contents = $data['cart'];
1060
+ $cart->set_session();
1061
+ }
1062
+
1063
+ /**
1064
+ *
1065
+ * @since 3.0.6
1066
+ * @package Stripe/Functions
1067
+ */
1068
+ function wc_stripe_restore_cart_after_product_checkout() {
1069
+ wc_stripe_restore_cart( WC()->cart );
1070
+ $cart_contents = array();
1071
+ foreach ( WC()->cart->get_cart() as $key => $cart_item ) {
1072
+ $cart_item['data'] = wc_get_product( $cart_item['variation_id'] ? $cart_item['variation_id'] : $cart_item['product_id'] );
1073
+ $cart_contents[ $key ] = $cart_item;
1074
+ }
1075
+ WC()->cart->cart_contents = $cart_contents;
1076
+ WC()->cart->calculate_totals();
1077
+ }
1078
+
1079
+ /**
1080
+ *
1081
+ * @param WC_Payment_Token[] $tokens
1082
+ * @param int $user_id
1083
+ * @param string $gateway_id
1084
+ *
1085
+ * @return WC_Payment_Token[]
1086
+ * @since 3.1.0
1087
+ * @package Stripe/Functions
1088
+ */
1089
+ function wc_stripe_get_customer_payment_tokens( $tokens, $user_id, $gateway_id ) {
1090
+ foreach ( $tokens as $idx => $token ) {
1091
+ if ( $token instanceof WC_Payment_Token_Stripe ) {
1092
+ $mode = wc_stripe_mode();
1093
+ if ( $token->get_environment() != $mode ) {
1094
+ unset( $tokens[ $idx ] );
1095
+ }
1096
+ }
1097
+ }
1098
+
1099
+ return $tokens;
1100
+ }
1101
+
1102
+ /**
1103
+ *
1104
+ * @param array $labels
1105
+ *
1106
+ * @return string
1107
+ * @since 3.1.0
1108
+ * @package Stripe/Functions
1109
+ */
1110
+ function wc_stripe_credit_card_labels( $labels ) {
1111
+ if ( ! isset( $labels['amex'] ) ) {
1112
+ $labels['amex'] = __( 'Amex', 'woocommerce' );
1113
+ }
1114
+
1115
+ return $labels;
1116
+ }
1117
+
1118
+ /**
1119
+ * Return an array of Stripe error messages.
1120
+ *
1121
+ * @since 3.1.1
1122
+ * @package Stripe/Functions
1123
+ */
1124
+ function wc_stripe_get_error_messages() {
1125
+ return apply_filters(
1126
+ 'wc_stripe_get_error_messages',
1127
+ array(
1128
+ 'stripe_cc_generic' => __( 'There was an error processing your credit card.', 'woo-stripe-payment' ),
1129
+ 'incomplete_number' => __( 'Your card number is incomplete.', 'woo-stripe-payment' ),
1130
+ 'incorrect_number' => __( 'The card number is incorrect. Check the card\'s number or use a different card.', 'woo-stripe-payment' ),
1131
+ 'incorrect_cvc' => __( 'The card\'s security code is incorrect. Check the card\'s security code or use a different card.', 'woo-stripe-payment' ),
1132
+ 'incorrect_zip' => __( 'The card\'s ZIP code is incorrect. Check the card\'s ZIP code or use a different card.', 'woo-stripe-payment' ),
1133
+ 'invalid_number' => __( 'The card number is invalid. Check the card details or use a different card.', 'woo-stripe-payment' ),
1134
+ 'invalid_characters' => __( 'This value provided to the field contains characters that are unsupported by the field.', 'woo-stripe-payment' ),
1135
+ 'invalid_cvc' => __( 'The card\'s security code is invalid. Check the card\'s security code or use a different card.', 'woo-stripe-payment' ),
1136
+ 'invalid_expiry_month' => __( 'The card\'s expiration month is incorrect. Check the expiration date or use a different card.', 'woo-stripe-payment' ),
1137
+ 'invalid_expiry_year' => __( 'The card\'s expiration year is incorrect. Check the expiration date or use a different card.', 'woo-stripe-payment' ),
1138
+ 'invalid_number' => __( 'The card number is invalid. Check the card details or use a different card.', 'woo-stripe-payment' ),
1139
+ 'incorrect_address' => __( 'The card\'s address is incorrect. Check the card\'s address or use a different card.', 'woo-stripe-payment' ),
1140
+ 'expired_card' => __( 'The card has expired. Check the expiration date or use a different card.', 'woo-stripe-payment' ),
1141
+ 'card_declined' => __( 'The card has been declined.', 'woo-stripe-payment' ),
1142
+ 'invalid_expiry_year_past' => __( 'Your card\'s expiration year is in the past.', 'woo-stripe-payment' ),
1143
+ 'account_number_invalid' => __( 'The bank account number provided is invalid (e.g., missing digits). Bank account information varies from country to country. We recommend creating validations in your entry forms based on the bank account formats we provide.', 'woo-stripe-payment' ),
1144
+ 'amount_too_large' => __( 'The specified amount is greater than the maximum amount allowed. Use a lower amount and try again.', 'woo-stripe-payment' ),
1145
+ 'amount_too_small' => __( 'The specified amount is less than the minimum amount allowed. Use a higher amount and try again.', 'woo-stripe-payment' ),
1146
+ 'authentication_required' => __( 'The payment requires authentication to proceed. If your customer is off session, notify your customer to return to your application and complete the payment. If you provided the error_on_requires_action parameter, then your customer should try another card that does not require authentication.', 'woo-stripe-payment' ),
1147
+ 'balance_insufficient' => __( 'The transfer or payout could not be completed because the associated account does not have a sufficient balance available. Create a new transfer or payout using an amount less than or equal to the account\'s available balance.', 'woo-stripe-payment' ),
1148
+ 'bank_account_declined' => __( 'The bank account provided can not be used to charge, either because it is not verified yet or it is not supported.', 'woo-stripe-payment' ),
1149
+ 'bank_account_exists' => __( 'The bank account provided already exists on the specified Customer object. If the bank account should also be attached to a different customer, include the correct customer ID when making the request again.', 'woo-stripe-payment' ),
1150
+ 'bank_account_unusable' => __( 'The bank account provided cannot be used for payouts. A different bank account must be used.', 'woo-stripe-payment' ),
1151
+ 'bank_account_unverified' => __( 'Your Connect platform is attempting to share an unverified bank account with a connected account.', 'woo-stripe-payment' ),
1152
+ 'bank_account_verification_failed' => __( 'The bank account cannot be verified, either because the microdeposit amounts provided do not match the actual amounts, or because verification has failed too many times.', 'woo-stripe-payment' ),
1153
+ 'card_decline_rate_limit_exceeded' => __( 'This card has been declined too many times. You can try to charge this card again after 24 hours. We suggest reaching out to your customer to make sure they have entered all of their information correctly and that there are no issues with their card.', 'woo-stripe-payment' ),
1154
+ 'charge_already_captured' => __( 'The charge you\'re attempting to capture has already been captured. Update the request with an uncaptured charge ID.', 'woo-stripe-payment' ),
1155
+ 'charge_already_refunded' => __( 'The charge you\'re attempting to refund has already been refunded. Update the request to use the ID of a charge that has not been refunded.', 'woo-stripe-payment' ),
1156
+ 'charge_disputed' => __( 'The charge you\'re attempting to refund has been charged back. Check the disputes documentation to learn how to respond to the dispute.', 'woo-stripe-payment' ),
1157
+ 'charge_exceeds_source_limit' => __( 'This charge would cause you to exceed your rolling-window processing limit for this source type. Please retry the charge later, or contact us to request a higher processing limit.', 'woo-stripe-payment' ),
1158
+ 'charge_expired_for_capture' => __( 'The charge cannot be captured as the authorization has expired. Auth and capture charges must be captured within seven days.', 'woo-stripe-payment' ),
1159
+ 'charge_invalid_parameter' => __( 'One or more provided parameters was not allowed for the given operation on the Charge. Check our API reference or the returned error message to see which values were not correct for that Charge.', 'woo-stripe-payment' ),
1160
+ 'email_invalid' => __( 'The email address is invalid (e.g., not properly formatted). Check that the email address is properly formatted and only includes allowed characters.', 'woo-stripe-payment' ),
1161
+ 'idempotency_key_in_use' => __( 'The idempotency key provided is currently being used in another request. This occurs if your integration is making duplicate requests simultaneously.', 'woo-stripe-payment' ),
1162
+ 'invalid_charge_amount' => __( 'The specified amount is invalid. The charge amount must be a positive integer in the smallest currency unit, and not exceed the minimum or maximum amount.', 'woo-stripe-payment' ),
1163
+ 'invalid_source_usage' => __( 'The source cannot be used because it is not in the correct state (e.g., a charge request is trying to use a source with a pending, failed, or consumed source). Check the status of the source you are attempting to use.', 'woo-stripe-payment' ),
1164
+ 'missing' => __( 'Both a customer and source ID have been provided, but the source has not been saved to the customer. To create a charge for a customer with a specified source, you must first save the card details.', 'woo-stripe-payment' ),
1165
+ 'postal_code_invalid' => __( 'The ZIP code provided was incorrect.', 'woo-stripe-payment' ),
1166
+ 'processing_error' => __( 'An error occurred while processing the card. Try again later or with a different payment method.', 'woo-stripe-payment' ),
1167
+ 'card_not_supported' => __( 'The card does not support this type of purchase.', 'woo-stripe-payment' ),
1168
+ 'call_issuer' => __( 'The card has been declined for an unknown reason.', 'woo-stripe-payment' ),
1169
+ 'card_velocity_exceeded' => __( 'The customer has exceeded the balance or credit limit available on their card.', 'woo-stripe-payment' ),
1170
+ 'currency_not_supported' => __( 'The card does not support the specified currency.', 'woo-stripe-payment' ),
1171
+ 'do_not_honor' => __( 'The card has been declined for an unknown reason.', 'woo-stripe-payment' ),
1172
+ 'fraudulent' => __( 'The payment has been declined as Stripe suspects it is fraudulent.', 'woo-stripe-payment' ),
1173
+ 'generic_decline' => __( 'The card has been declined for an unknown reason.', 'woo-stripe-payment' ),
1174
+ 'incorrect_pin' => __( 'The PIN entered is incorrect. ', 'woo-stripe-payment' ),
1175
+ 'insufficient_funds' => __( 'The card has insufficient funds to complete the purchase.', 'woo-stripe-payment' ),
1176
+ 'empty_element' => __( 'Please select a payment method before proceeding.', 'woo-stripe-payment' ),
1177
+ 'empty_element_sepa_debit' => __( 'Please enter your IBAN before proceeding.', 'woo-stripe-payment' ),
1178
+ 'empty_element_ideal' => __(
1179
+ 'Please select a bank before proceeding',
1180
+ 'woo-stripe-payment'
1181
+ ),
1182
+ )
1183
+ );
1184
+ }
1185
+
1186
+ /**
1187
+ * Return an array of Stripe currencies where the value of each
1188
+ * currency is the curency multiplier.
1189
+ *
1190
+ * @return mixed
1191
+ * @package Stripe/Functions
1192
+ * @since 3.1.2
1193
+ */
1194
+ function wc_stripe_get_currencies() {
1195
+ return apply_filters(
1196
+ 'wc_stripe_get_currencies',
1197
+ array(
1198
+ 'BIF' => 0,
1199
+ 'CLP' => 0,
1200
+ 'DJF' => 0,
1201
+ 'GNF' => 0,
1202
+ 'JPY' => 0,
1203
+ 'KMF' => 0,
1204
+ 'KRW' => 0,
1205
+ 'MGA' => 0,
1206
+ 'PYG' => 0,
1207
+ 'RWF' => 0,
1208
+ 'UGX' => 0,
1209
+ 'VND' => 0,
1210
+ 'VUV' => 0,
1211
+ 'XAF' => 0,
1212
+ 'XOF' => 0,
1213
+ 'XPF' => 0,
1214
+ )
1215
+ );
1216
+ }
1217
+
1218
+ /**
1219
+ * Function that triggers a filter on the order id.
1220
+ * Allows 3rd parties to
1221
+ * convert the order_id from the metadata of the Stripe object.
1222
+ *
1223
+ * @param int $order_id
1224
+ * @param \Stripe\ApiResource $object
1225
+ *
1226
+ * @since 3.1.3
1227
+ * @package Stripe/Functions
1228
+ */
1229
+ function wc_stripe_filter_order_id( $order_id, $object ) {
1230
+ return apply_filters( 'wc_stripe_filter_order_id', $order_id, $object );
1231
+ }
1232
+
1233
+ /**
1234
+ * Removes order locks that have expired so the options table does not get cluttered with transients.
1235
+ * @since 3.1.6
1236
+ * @package Stripe/Functions
1237
+ */
1238
+ function wc_stripe_remove_order_locks() {
1239
+ global $wpdb;
1240
+
1241
+ // this operation could take some time, ensure it completes.
1242
+ wc_set_time_limit();
1243
+
1244
+ $results = $wpdb->get_results( $wpdb->prepare( "SELECT option_name FROM $wpdb->options WHERE option_name LIKE %s AND option_value < %d", '_transient_timeout_stripe_lock_order_%', time() ) );
1245
+ if ( $results ) {
1246
+ foreach ( $results as $result ) {
1247
+ // call delete_transient so Wordpress can fire all it's transient actions.
1248
+ delete_transient( substr( $result->option_name, strlen( '_transient_timeout_' ) ) );
1249
+ }
1250
+ }
1251
+ }
1252
+
1253
+ /**
1254
+ * Returns an array of checkout fields needed to complete an order.
1255
+ * @return array
1256
+ * @since 3.1.8
1257
+ */
1258
+ function wc_stripe_get_checkout_fields() {
1259
+ global $wp;
1260
+ $fields = array();
1261
+ $order = false;
1262
+ if ( ! empty( $wp->query_vars['order-pay'] ) ) {
1263
+ $order = wc_get_order( absint( ( $wp->query_vars['order-pay'] ) ) );
1264
+ }
1265
+ foreach ( array( 'billing', 'shipping' ) as $key ) {
1266
+ if ( ( $field_set = WC()->checkout()->get_checkout_fields( $key ) ) ) {
1267
+ $fields = array_merge( $fields, $field_set );
1268
+ }
1269
+ }
1270
+ // loop through fields and assign their value to the field.
1271
+ array_walk( $fields, function ( &$field, $key ) use ( $order ) {
1272
+ if ( $order ) {
1273
+ if ( is_callable( array( $order, "get_{$key}" ) ) ) {
1274
+ $field['value'] = $order->{"get_{$key}"}();
1275
+ } else {
1276
+ $field['value'] = WC()->checkout()->get_value( $key );
1277
+ }
1278
+ } else {
1279
+ $field['value'] = WC()->checkout()->get_value( $key );
1280
+ }
1281
+ /**
1282
+ * Some 3rd party plugins hook in to WC filters and alter the expected
1283
+ * type for required. This ensures it's converted back to a boolean.
1284
+ */
1285
+ if ( isset( $field['required'] ) && ! is_bool( $field['required'] ) ) {
1286
+ $field['required'] = (bool) $field['required'];
1287
+ }
1288
+ } );
1289
+
1290
+ return $fields;
1291
+ }
1292
+
1293
+ /**
1294
+ * Filters a state value, making sure the abbreviated state value recognized by WC is returned.
1295
+ * Example: Texas = TX
1296
+ *
1297
+ * @param string $state
1298
+ * @param string $country
1299
+ *
1300
+ * @return string
1301
+ *
1302
+ * @since 3.2.1
1303
+ */
1304
+ function wc_stripe_filter_address_state( $state, $country ) {
1305
+ $states = WC()->countries ? WC()->countries->get_states( $country ) : array();
1306
+ if ( ! empty( $states ) && is_array( $states ) && ! isset( $states[ $state ] ) ) {
1307
+ $state_keys = array_flip( array_map( 'strtoupper', $states ) );
1308
+ if ( isset( $state_keys[ strtoupper( $state ) ] ) ) {
1309
+ $state = $state_keys[ strtoupper( $state ) ];
1310
+ }
1311
+ }
1312
+
1313
+ return $state;
1314
+ }
1315
+
1316
+ /**
1317
+ * @since 3.2.3
1318
+ * @retun string
1319
+ */
1320
+ function wc_stripe_get_current_page() {
1321
+ global $wp;
1322
+ if ( is_product() ) {
1323
+ return 'product';
1324
+ }
1325
+ if ( is_cart() ) {
1326
+ return 'cart';
1327
+ }
1328
+ if ( is_checkout() ) {
1329
+ if ( ! empty( $wp->query_vars['order-pay'] ) ) {
1330
+ if ( wcs_stripe_active() && WC_Subscriptions_Change_Payment_Gateway::$is_request_to_change_payment ) {
1331
+ return 'change_payment_method';
1332
+ }
1333
+
1334
+ return 'order_pay';
1335
+ }
1336
+
1337
+ return 'checkout';
1338
+ }
1339
+ if ( is_add_payment_method_page() ) {
1340
+ return 'add_payment_method';
1341
+ }
1342
+
1343
+ return '';
1344
+ }
readme.txt CHANGED
@@ -4,7 +4,7 @@ Tags: stripe, ach, klarna, credit card, apple pay, google pay, ideal, sepa, sofo
4
  Requires at least: 3.0.1
5
  Tested up to: 5.5
6
  Requires PHP: 5.6
7
- Stable tag: 3.2.2
8
  Copyright: Payment Plugins
9
  License: GPLv2 or later
10
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
@@ -58,6 +58,11 @@ If you're site is not loading over https, then Stripe won't render the Payment R
58
  8. Edit payment gateways on the product page
59
 
60
  == Changelog ==
 
 
 
 
 
61
  = 3.2.2 =
62
  * Fixed - 403 for logged out user when link-token fetched on checkout page
63
  * Added - Payment method format for GPay. Example: Visa 1111 (Google Pay)
4
  Requires at least: 3.0.1
5
  Tested up to: 5.5
6
  Requires PHP: 5.6
7
+ Stable tag: 3.2.3
8
  Copyright: Payment Plugins
9
  License: GPLv2 or later
10
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
58
  8. Edit payment gateways on the product page
59
 
60
  == Changelog ==
61
+ = 3.2.3 =
62
+ * Fixed - 3DS pop up on order pay page
63
+ * Fixed - One time use coupon error when 3DS triggered on checkout page
64
+ * Fixed - Formatting in class-wc-stripe-admin-notices.php
65
+ * Added - Apple Pay, GPay, Payment Request, do not request shipping address or shipping options on checkout page if customer has already filled out shipping fields
66
  = 3.2.2 =
67
  * Fixed - 403 for logged out user when link-token fetched on checkout page
68
  * Added - Payment method format for GPay. Example: Visa 1111 (Google Pay)
stripe-payments.php CHANGED
@@ -3,7 +3,7 @@
3
  * Plugin Name: Stripe For WooCommerce
4
  * Plugin URI: https://docs.paymentplugins.com/wc-stripe/config/
5
  * Description: Accept credit cards, Google Pay, Apple Pay, ACH, Klarna and more using Stripe.
6
- * Version: 3.2.2
7
  * Author: Payment Plugins, support@paymentplugins.com
8
  * Text Domain: woo-stripe-payment
9
  * Domain Path: /i18n/languages/
3
  * Plugin Name: Stripe For WooCommerce
4
  * Plugin URI: https://docs.paymentplugins.com/wc-stripe/config/
5
  * Description: Accept credit cards, Google Pay, Apple Pay, ACH, Klarna and more using Stripe.
6
+ * Version: 3.2.3
7
  * Author: Payment Plugins, support@paymentplugins.com
8
  * Text Domain: woo-stripe-payment
9
  * Domain Path: /i18n/languages/