-
Notifications
You must be signed in to change notification settings - Fork 207
/
Copy pathclass-wc-stripe-payment-request.php
2142 lines (1833 loc) · 71.3 KB
/
class-wc-stripe-payment-request.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Stripe Payment Request API
* Adds support for Apple Pay and Chrome Payment Request API buttons.
* Utilizes the Stripe Payment Request Button to support checkout from the product detail and cart pages.
*
* @package WooCommerce_Stripe/Classes/Payment_Request
* @since 4.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* WC_Stripe_Payment_Request class.
*/
class WC_Stripe_Payment_Request {
use WC_Stripe_Pre_Orders_Trait;
/**
* Enabled.
*
* @var
*/
public $stripe_settings;
/**
* Total label
*
* @var
*/
public $total_label;
/**
* Key
*
* @var
*/
public $publishable_key;
/**
* Key
*
* @var
*/
public $secret_key;
/**
* Is test mode active?
*
* @var bool
*/
public $testmode;
/**
* This Instance.
*
* @var
*/
private static $_this;
/**
* Initialize class actions.
*
* @since 3.0.0
* @version 4.0.0
*/
public function __construct() {
self::$_this = $this;
$this->stripe_settings = WC_Stripe_Helper::get_stripe_settings();
$this->testmode = WC_Stripe_Mode::is_test();
$this->publishable_key = ! empty( $this->stripe_settings['publishable_key'] ) ? $this->stripe_settings['publishable_key'] : '';
$this->secret_key = ! empty( $this->stripe_settings['secret_key'] ) ? $this->stripe_settings['secret_key'] : '';
$this->total_label = ! empty( $this->stripe_settings['statement_descriptor'] ) ? WC_Stripe_Helper::clean_statement_descriptor( $this->stripe_settings['statement_descriptor'] ) : '';
if ( $this->testmode ) {
$this->publishable_key = ! empty( $this->stripe_settings['test_publishable_key'] ) ? $this->stripe_settings['test_publishable_key'] : '';
$this->secret_key = ! empty( $this->stripe_settings['test_secret_key'] ) ? $this->stripe_settings['test_secret_key'] : '';
}
$this->total_label = str_replace( "'", '', $this->total_label ) . apply_filters( 'wc_stripe_payment_request_total_label_suffix', ' (via WooCommerce)' );
add_action( 'woocommerce_stripe_updated', [ $this, 'migrate_button_size' ] );
// Check if ECE feature flag is enabled.
if ( WC_Stripe_Feature_Flags::is_upe_checkout_enabled() && WC_Stripe_Feature_Flags::is_stripe_ece_enabled() ) {
return;
}
// Checks if Stripe Gateway is enabled.
if ( empty( $this->stripe_settings ) || ( isset( $this->stripe_settings['enabled'] ) && 'yes' !== $this->stripe_settings['enabled'] ) ) {
return;
}
// Don't initiate this class if none of the PRBs are enabled.
if ( ! $this->is_at_least_one_payment_request_button_enabled() ) {
return;
}
// Don't load for change payment method page.
if ( isset( $_GET['change_payment_method'] ) ) {
return;
}
// Don't load for switch subscription page.
if ( isset( $_GET['switch-subscription'] ) ) {
return;
}
$this->init();
}
/**
* Checks whether authentication is required for checkout.
*
* @since 5.1.0
* @version 5.3.0
*
* @return bool
*/
public function is_authentication_required() {
// If guest checkout is disabled and account creation upon checkout is not possible, authentication is required.
if ( 'no' === get_option( 'woocommerce_enable_guest_checkout', 'yes' ) && ! $this->is_account_creation_possible() ) {
return true;
}
// If cart contains subscription and account creation upon checkout is not posible, authentication is required.
if ( $this->has_subscription_product() && ! $this->is_account_creation_possible() ) {
return true;
}
return false;
}
/**
* Checks whether account creation is possible upon checkout.
*
* @since 5.1.0
*
* @return bool
*/
public function is_account_creation_possible() {
// If automatically generate username/password are disabled, the Payment Request API
// can't include any of those fields, so account creation is not possible.
return (
'yes' === get_option( 'woocommerce_enable_signup_and_login_from_checkout', 'no' ) &&
'yes' === get_option( 'woocommerce_registration_generate_username', 'yes' ) &&
'yes' === get_option( 'woocommerce_registration_generate_password', 'yes' )
);
}
/**
* Checks if keys are set and valid.
*
* @since 4.0.6
* @return boolean True if the keys are set *and* valid, false otherwise (for example, if keys are empty or the secret key was pasted as publishable key).
*/
public function are_keys_set() {
// NOTE: updates to this function should be added to are_keys_set()
// in includes/abstracts/abstract-wc-stripe-payment-gateway.php
if ( $this->testmode ) {
return preg_match( '/^pk_test_/', $this->publishable_key )
&& preg_match( '/^[rs]k_test_/', $this->secret_key );
} else {
return preg_match( '/^pk_live_/', $this->publishable_key )
&& preg_match( '/^[rs]k_live_/', $this->secret_key );
}
}
/**
* Get this instance.
*
* @since 4.0.6
* @return class
*/
public static function instance() {
return self::$_this;
}
/**
* Sets the WC customer session if one is not set.
* This is needed so nonces can be verified by AJAX Request.
*
* @since 4.0.0
* @version 5.2.0
* @return void
*/
public function set_session() {
// Don't set session cookies on product pages to allow for caching when payment request
// buttons are disabled. But keep cookies if there is already an active WC session in place.
if (
! ( $this->is_product() && $this->should_show_payment_request_button() )
|| ( isset( WC()->session ) && WC()->session->has_session() )
) {
return;
}
WC()->session->set_customer_session_cookie( true );
}
/**
* Handles payment request redirect when the redirect dialog "Continue" button is clicked.
*
* @since 5.3.0
*/
public function handle_payment_request_redirect() {
if (
! empty( $_GET['wc_stripe_payment_request_redirect_url'] )
&& ! empty( $_GET['_wpnonce'] )
&& wp_verify_nonce( $_GET['_wpnonce'], 'wc-stripe-set-redirect-url' ) // @codingStandardsIgnoreLine
) {
$url = rawurldecode( esc_url_raw( wp_unslash( $_GET['wc_stripe_payment_request_redirect_url'] ) ) );
// Sets a redirect URL cookie for 10 minutes, which we will redirect to after authentication.
// Users will have a 10 minute timeout to login/create account, otherwise redirect URL expires.
wc_setcookie( 'wc_stripe_payment_request_redirect_url', $url, time() + MINUTE_IN_SECONDS * 10 );
// Redirects to "my-account" page.
wp_safe_redirect( get_permalink( get_option( 'woocommerce_myaccount_page_id' ) ) );
exit;
}
}
/**
* Initialize hooks.
*
* @since 4.0.0
* @version 5.3.0
* @return void
*/
public function init() {
add_action( 'template_redirect', [ $this, 'set_session' ] );
add_action( 'template_redirect', [ $this, 'handle_payment_request_redirect' ] );
add_action( 'wp_enqueue_scripts', [ $this, 'scripts' ] );
add_action( 'woocommerce_after_add_to_cart_form', [ $this, 'display_payment_request_button_html' ], 1 );
add_action( 'woocommerce_proceed_to_checkout', [ $this, 'display_payment_request_button_html' ], 25 );
add_action( 'woocommerce_checkout_before_customer_details', [ $this, 'display_payment_request_button_html' ], 1 );
add_action( 'wc_ajax_wc_stripe_get_cart_details', [ $this, 'ajax_get_cart_details' ] );
add_action( 'wc_ajax_wc_stripe_get_shipping_options', [ $this, 'ajax_get_shipping_options' ] );
add_action( 'wc_ajax_wc_stripe_update_shipping_method', [ $this, 'ajax_update_shipping_method' ] );
add_action( 'wc_ajax_wc_stripe_create_order', [ $this, 'ajax_create_order' ] );
add_action( 'wc_ajax_wc_stripe_add_to_cart', [ $this, 'ajax_add_to_cart' ] );
add_action( 'wc_ajax_wc_stripe_get_selected_product_data', [ $this, 'ajax_get_selected_product_data' ] );
add_action( 'wc_ajax_wc_stripe_clear_cart', [ $this, 'ajax_clear_cart' ] );
add_action( 'wc_ajax_wc_stripe_log_errors', [ $this, 'ajax_log_errors' ] );
add_filter( 'woocommerce_gateway_title', [ $this, 'filter_gateway_title' ], 10, 2 );
add_action( 'woocommerce_checkout_order_processed', [ $this, 'add_order_meta' ], 10, 2 );
add_filter( 'woocommerce_login_redirect', [ $this, 'get_login_redirect_url' ], 10, 3 );
add_filter( 'woocommerce_registration_redirect', [ $this, 'get_login_redirect_url' ], 10, 3 );
}
/**
* Gets the button type.
*
* @since 4.0.0
* @version 4.0.0
* @return string
*/
public function get_button_type() {
return isset( $this->stripe_settings['payment_request_button_type'] ) ? $this->stripe_settings['payment_request_button_type'] : 'default';
}
/**
* Gets the button theme.
*
* @since 4.0.0
* @version 4.0.0
* @return string
*/
public function get_button_theme() {
return isset( $this->stripe_settings['payment_request_button_theme'] ) ? $this->stripe_settings['payment_request_button_theme'] : 'dark';
}
/**
* Gets the button height.
*
* @since 4.0.0
* @version 4.0.0
* @return string
*/
public function get_button_height() {
if ( ! WC_Stripe_Feature_Flags::is_upe_preview_enabled() ) {
return isset( $this->stripe_settings['payment_request_button_height'] ) ? str_replace( 'px', '', $this->stripe_settings['payment_request_button_height'] ) : '64';
}
$height = isset( $this->stripe_settings['payment_request_button_size'] ) ? $this->stripe_settings['payment_request_button_size'] : 'default';
if ( 'small' === $height ) {
return '40';
}
if ( 'large' === $height ) {
return '56';
}
// for the "default" and "catch-all" scenarios.
return '48';
}
/**
* Checks if the button is branded.
*
* @since 4.4.0
* @version 4.4.0
* @return boolean
*/
public function is_branded_button() {
return 'branded' === $this->get_button_type();
}
/**
* Gets the branded button type.
*
* @since 4.4.0
* @version 4.4.0
* @return string
*/
public function get_button_branded_type() {
return isset( $this->stripe_settings['payment_request_button_branded_type'] ) ? $this->stripe_settings['payment_request_button_branded_type'] : 'default';
}
/**
* Checks if the button is custom.
*
* @since 4.4.0
* @version 4.4.0
* @return boolean
*/
public function is_custom_button() {
// no longer a valid option
if ( WC_Stripe_Feature_Flags::is_upe_preview_enabled() ) {
return false;
}
return 'custom' === $this->get_button_type();
}
/**
* Returns custom button css selector.
*
* @since 4.4.0
* @version 4.4.0
* @return string
*/
public function custom_button_selector() {
return $this->is_custom_button() ? '#wc-stripe-custom-button' : '';
}
/**
* Gets the custom button label.
*
* @since 4.4.0
* @version 4.4.0
* @return string
*/
public function get_button_label() {
// no longer a valid option
if ( WC_Stripe_Feature_Flags::is_upe_preview_enabled() ) {
return '';
}
return isset( $this->stripe_settings['payment_request_button_label'] ) ? $this->stripe_settings['payment_request_button_label'] : 'Buy now';
}
/**
* Gets the product total price.
*
* @since 5.2.0
*
* @param object $product WC_Product_* object.
* @return float Total price.
*/
public function get_product_price( $product ) {
$product_price = (float) $product->get_price();
// Add subscription sign-up fees to product price.
if ( in_array( $product->get_type(), [ 'subscription', 'subscription_variation' ] ) && class_exists( 'WC_Subscriptions_Product' ) ) {
$product_price += (float) WC_Subscriptions_Product::get_sign_up_fee( $product );
}
return $product_price;
}
/**
* Gets the product data for the currently viewed page
*
* @since 4.0.0
* @version 5.2.0
* @return mixed Returns false if not on a product page, the product information otherwise.
*/
public function get_product_data() {
if ( ! $this->is_product() ) {
return false;
}
$product = $this->get_product();
$variation_id = 0;
if ( in_array( $product->get_type(), [ 'variable', 'variable-subscription' ], true ) ) {
$variation_attributes = $product->get_variation_attributes();
$attributes = [];
foreach ( $variation_attributes as $attribute_name => $attribute_values ) {
$attribute_key = 'attribute_' . sanitize_title( $attribute_name );
// Passed value via GET takes precedence, then POST, otherwise get the default value for given attribute
if ( isset( $_GET[ $attribute_key ] ) ) {
$attributes[ $attribute_key ] = wc_clean( wp_unslash( $_GET[ $attribute_key ] ) );
} elseif ( isset( $_POST[ $attribute_key ] ) ) {
$attributes[ $attribute_key ] = wc_clean( wp_unslash( $_POST[ $attribute_key ] ) );
} else {
$attributes[ $attribute_key ] = $product->get_variation_default_attribute( $attribute_name );
}
}
$data_store = WC_Data_Store::load( 'product' );
$variation_id = $data_store->find_matching_product_variation( $product, $attributes );
if ( ! empty( $variation_id ) ) {
$product = wc_get_product( $variation_id );
}
}
$data = [];
$items = [];
$items[] = [
'label' => $product->get_name(),
'amount' => WC_Stripe_Helper::get_stripe_amount( $this->get_product_price( $product ) ),
];
if ( wc_tax_enabled() ) {
$items[] = [
'label' => __( 'Tax', 'woocommerce-gateway-stripe' ),
'amount' => 0,
'pending' => true,
];
}
if ( wc_shipping_enabled() && $product->needs_shipping() ) {
$items[] = [
'label' => __( 'Shipping', 'woocommerce-gateway-stripe' ),
'amount' => 0,
'pending' => true,
];
$data['shippingOptions'] = [
'id' => 'pending',
'label' => __( 'Pending', 'woocommerce-gateway-stripe' ),
'detail' => '',
'amount' => 0,
];
}
$data['displayItems'] = $items;
$data['total'] = [
'label' => apply_filters( 'wc_stripe_payment_request_total_label', $this->total_label ),
'amount' => WC_Stripe_Helper::get_stripe_amount( $this->get_product_price( $product ) ),
];
$data['requestShipping'] = ( wc_shipping_enabled() && $product->needs_shipping() && 0 !== wc_get_shipping_method_count( true ) );
$data['currency'] = strtolower( get_woocommerce_currency() );
$data['country_code'] = substr( get_option( 'woocommerce_default_country' ), 0, 2 );
// On product page load, if there's a variation already selected, check if it's supported.
$data['validVariationSelected'] = ! empty( $variation_id ) ? $this->is_product_supported( $product ) : true;
return apply_filters( 'wc_stripe_payment_request_product_data', $data, $product );
}
/**
* Filters the gateway title to reflect Payment Request type
*/
public function filter_gateway_title( $title, $id ) {
global $theorder;
// If $theorder is empty (i.e. non-HPOS), fallback to using the global post object.
if ( empty( $theorder ) && ! empty( $GLOBALS['post']->ID ) ) {
$theorder = wc_get_order( $GLOBALS['post']->ID );
}
if ( ! is_object( $theorder ) ) {
return $title;
}
$method_title = $theorder->get_payment_method_title();
if ( 'stripe' === $id && ! empty( $method_title ) ) {
if ( 'Apple Pay (Stripe)' === $method_title
|| 'Google Pay (Stripe)' === $method_title
|| 'Payment Request (Stripe)' === $method_title
) {
return $method_title;
}
// We renamed 'Chrome Payment Request' to just 'Payment Request' since Payment Requests
// are supported by other browsers besides Chrome. As such, we need to check for the
// old title to make sure older orders still reflect that they were paid via Payment
// Request Buttons.
if ( 'Chrome Payment Request (Stripe)' === $method_title ) {
return 'Payment Request (Stripe)';
}
}
return $title;
}
/**
* Normalizes postal code in case of redacted data from Apple Pay.
*
* @since 5.2.0
*
* @param string $postcode Postal code.
* @param string $country Country.
*/
public function get_normalized_postal_code( $postcode, $country ) {
/**
* Currently, Apple Pay truncates the UK postcodes by removing the "inward" (last 3 chars) of the postcode.
* Apple Pay also truncates Canadian postal codes to the first 4 characters.
* When either of these are passed back from the shippingcontactselected object. This causes WC to invalidate
* the postal code and not calculate shipping zones correctly.
*/
if ( 'GB' === $country ) {
// UK Postcodes returned from Apple Pay can be alpha numeric 2 chars, 3 chars, or 4 chars long will optionally have a trailing space,
// depending on whether the customer put a space in their postcode between the outcode and incode part.
// See https://assets.publishing.service.gov.uk/media/5a7b997d40f0b62826a049e0/ILRSpecification2013_14Appendix_C_Dec2012_v1.pdf for more details.
// Here is a table showing the functionality by example:
// Original | Apple Pay | Normalized
// 'LN10 1AA' | 'LN10 ' | 'LN10 ***'
// 'LN101AA' | 'LN10' | 'LN10 ***'
// 'W10 2AA' | 'W10 ' | 'W10 ***'
// 'W102AA' | 'W10' | 'W10 ***'
// 'N2 3AA | 'N2 ' | 'N2 ***'
// 'N23AA | 'N2' | 'N2 ***'
$spaceless_postcode = preg_replace( '/\s+/', '', $postcode );
if ( strlen( $spaceless_postcode ) < 5 ) {
// Always reintroduce the space so that Shipping Zones regex like 'N1 *' work to match N1 postcodes like N1 1AA, but don't match N10 postcodes like N10 1AA
return $spaceless_postcode . ' ***';
}
return $postcode; // 5 or more chars means it probably wasn't redacted and will likely validate unchanged.
}
if ( 'CA' === $country ) {
// Replaces a redacted string with something like L4Y***.
return str_pad( preg_replace( '/\s+/', '', $postcode ), 6, '*' );
}
return $postcode;
}
/**
* Add needed order meta
*
* @param integer $order_id The order ID.
* @param array $posted_data The posted data from checkout form.
*
* @since 4.0.0
* @version 4.0.0
* @return void
*/
public function add_order_meta( $order_id, $posted_data ) {
if ( empty( $_POST['payment_request_type'] ) || ! isset( $_POST['payment_method'] ) || 'stripe' !== $_POST['payment_method'] ) {
return;
}
$order = wc_get_order( $order_id );
$payment_request_type = wc_clean( wp_unslash( $_POST['payment_request_type'] ) );
if ( 'apple_pay' === $payment_request_type ) {
$order->set_payment_method_title( 'Apple Pay (Stripe)' );
$order->save();
} elseif ( 'google_pay' === $payment_request_type ) {
$order->set_payment_method_title( 'Google Pay (Stripe)' );
$order->save();
} elseif ( 'payment_request_api' === $payment_request_type ) {
$order->set_payment_method_title( 'Payment Request (Stripe)' );
$order->save();
}
}
/**
* Checks to make sure product type is supported.
*
* @since 3.1.0
* @version 4.0.0
* @return array
*/
public function supported_product_types() {
return apply_filters(
'wc_stripe_payment_request_supported_types',
[
'simple',
'variable',
'variation',
'subscription',
'variable-subscription',
'subscription_variation',
'booking',
'bundle',
'composite',
]
);
}
/**
* Checks the cart to see if all items are allowed to be used.
*
* @since 3.1.4
* @version 4.0.0
* @return boolean
*/
public function allowed_items_in_cart() {
// Pre Orders compatibility where we don't support charge upon release.
if ( $this->is_pre_order_item_in_cart() && $this->is_pre_order_product_charged_upon_release( $this->get_pre_order_product_from_cart() ) ) {
return false;
}
// If the cart is not available or if the cart is empty we don't have any unsupported products in the cart, so we
// return true. This can happen e.g. when loading the cart or checkout blocks in Gutenberg.
if ( is_null( WC()->cart ) || WC()->cart->is_empty() ) {
return true;
}
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
if ( ! in_array( $_product->get_type(), $this->supported_product_types() ) ) {
return false;
}
// Subscriptions with a trial period that need shipping are not supported.
if ( $this->is_invalid_subscription_product( $_product ) ) {
return false;
}
}
// We don't support multiple packages with Payment Request Buttons because we can't offer
// a good UX.
$packages = WC()->cart->get_shipping_packages();
if ( 1 < count( $packages ) ) {
return false;
}
return true;
}
/**
* Returns true if the given product is a subscription that cannot be purchased with Payment Request Buttons.
*
* Invalid subscription products include those with:
* - a free trial that requires shipping (synchronised subscriptions with a delayed first payment are considered to have a free trial)
* - a synchronised subscription with no upfront payment and is virtual (this limitation only applies to the product page as we cannot calculate totals correctly)
*
* If the product is a variable subscription, this function will return true if all of its variations have a trial and require shipping.
*
* @since 7.8.0
*
* @param WC_Product|null $product Product object.
* @param boolean $is_product_page_request Whether this is a request from the product page.
*
* @return boolean
*/
public function is_invalid_subscription_product( $product, $is_product_page_request = false ) {
if ( ! class_exists( 'WC_Subscriptions_Product' ) || ! class_exists( 'WC_Subscriptions_Synchroniser' ) || ! WC_Subscriptions_Product::is_subscription( $product ) ) {
return false;
}
$is_invalid = true;
if ( $product->get_type() === 'variable-subscription' ) {
$products = $product->get_available_variations( 'object' );
} else {
$products = [ $product ];
}
foreach ( $products as $product ) {
$needs_shipping = $product->needs_shipping();
$is_synced = WC_Subscriptions_Synchroniser::is_product_synced( $product );
$is_payment_upfront = WC_Subscriptions_Synchroniser::is_payment_upfront( $product );
$has_trial_period = WC_Subscriptions_Product::get_trial_length( $product ) > 0;
if ( $is_product_page_request && $is_synced && ! $is_payment_upfront && ! $needs_shipping ) {
/**
* This condition prevents the purchase of virtual synced subscription products with no upfront costs via Payment Request Buttons from the product page.
*
* The main issue is that calling $product->get_price() on a synced subscription does not take into account a mock trial period or prorated price calculations
* until the product is in the cart. This means that the totals passed to Payment Request are incorrect when purchasing from the product page.
* Another part of the problem is because the product is virtual this stops the Stripe PaymentRequest API from triggering the necessary `shippingaddresschange` event
* which is when we call WC()->cart->calculate_totals(); which would fix the totals.
*
* The fix here is to not allow virtual synced subscription products with no upfront costs to be purchased via Payment Request Buttons on the product page.
*/
continue;
} elseif ( $is_synced && ! $is_payment_upfront && $needs_shipping ) {
continue;
} elseif ( $has_trial_period && $needs_shipping ) {
continue;
} else {
// If we made it this far, the product is valid. Break out of the foreach and return early as we only care about invalid cases.
$is_invalid = false;
break;
}
}
return $is_invalid;
}
/**
* Checks whether cart contains a subscription product or this is a subscription product page.
*
* @since 5.3.0
* @version 5.3.0
* @return boolean
*/
public function has_subscription_product() {
if ( ! class_exists( 'WC_Subscriptions_Product' ) ) {
return false;
}
if ( $this->is_product() ) {
$product = $this->get_product();
if ( WC_Subscriptions_Product::is_subscription( $product ) ) {
return true;
}
} elseif ( WC_Stripe_Helper::has_cart_or_checkout_on_current_page() ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
if ( WC_Subscriptions_Product::is_subscription( $_product ) ) {
return true;
}
}
}
return false;
}
/**
* Checks if this is a product page or content contains a product_page shortcode.
*
* @since 5.2.0
* @return boolean
*/
public function is_product() {
return is_product() || wc_post_content_has_shortcode( 'product_page' );
}
/**
* Get product from product page or product_page shortcode.
*
* @since 5.2.0
* @return WC_Product Product object.
*/
public function get_product() {
global $post;
if ( is_product() ) {
return wc_get_product( $post->ID );
} elseif ( wc_post_content_has_shortcode( 'product_page' ) ) {
// Get id from product_page shortcode.
preg_match( '/\[product_page id="(?<id>\d+)"\]/', $post->post_content, $shortcode_match );
if ( ! isset( $shortcode_match['id'] ) ) {
return false;
}
return wc_get_product( $shortcode_match['id'] );
}
return false;
}
/**
* Returns the login redirect URL.
*
* @since 5.3.0
*
* @param string $redirect Default redirect URL.
* @return string Redirect URL.
*/
public function get_login_redirect_url( $redirect ) {
$url = esc_url_raw( wp_unslash( isset( $_COOKIE['wc_stripe_payment_request_redirect_url'] ) ? $_COOKIE['wc_stripe_payment_request_redirect_url'] : '' ) );
if ( empty( $url ) ) {
return $redirect;
}
wc_setcookie( 'wc_stripe_payment_request_redirect_url', null );
return $url;
}
/**
* Returns the JavaScript configuration object used for any pages with a payment request button.
*
* @return array The settings used for the payment request button in JavaScript.
*/
public function javascript_params() {
$needs_shipping = 'no';
if ( ! is_null( WC()->cart ) && WC()->cart->needs_shipping() ) {
$needs_shipping = 'yes';
}
return [
'ajax_url' => WC_AJAX::get_endpoint( '%%endpoint%%' ),
'stripe' => [
'key' => $this->publishable_key,
'allow_prepaid_card' => apply_filters( 'wc_stripe_allow_prepaid_card', true ) ? 'yes' : 'no',
'locale' => WC_Stripe_Helper::convert_wc_locale_to_stripe_locale( get_locale() ),
'is_link_enabled' => WC_Stripe_UPE_Payment_Method_Link::is_link_enabled(),
'is_payment_request_enabled' => $this->is_payment_request_enabled(),
],
'nonce' => [
'payment' => wp_create_nonce( 'wc-stripe-payment-request' ),
'shipping' => wp_create_nonce( 'wc-stripe-payment-request-shipping' ),
'update_shipping' => wp_create_nonce( 'wc-stripe-update-shipping-method' ),
'checkout' => wp_create_nonce( 'woocommerce-process_checkout' ),
'add_to_cart' => wp_create_nonce( 'wc-stripe-add-to-cart' ),
'get_selected_product_data' => wp_create_nonce( 'wc-stripe-get-selected-product-data' ),
'log_errors' => wp_create_nonce( 'wc-stripe-log-errors' ),
'clear_cart' => wp_create_nonce( 'wc-stripe-clear-cart' ),
],
'i18n' => [
'no_prepaid_card' => __( 'Sorry, we\'re not accepting prepaid cards at this time.', 'woocommerce-gateway-stripe' ),
/* translators: Do not translate the [option] placeholder */
'unknown_shipping' => __( 'Unknown shipping option "[option]".', 'woocommerce-gateway-stripe' ),
],
'checkout' => [
'url' => wc_get_checkout_url(),
'currency_code' => strtolower( get_woocommerce_currency() ),
'country_code' => substr( get_option( 'woocommerce_default_country' ), 0, 2 ),
'needs_shipping' => $needs_shipping,
// Defaults to 'required' to match how core initializes this option.
'needs_payer_phone' => 'required' === get_option( 'woocommerce_checkout_phone_field', 'required' ),
],
'button' => $this->get_button_settings(),
'login_confirmation' => $this->get_login_confirmation_settings(),
'is_product_page' => $this->is_product(),
'product' => $this->get_product_data(),
];
}
/**
* Load public scripts and styles.
*
* @since 3.1.0
* @version 5.2.0
*/
public function scripts() {
// If page is not supported, bail.
// Note: This check is not in `should_show_payment_request_button()` because that function is
// also called by the blocks support class, and this check would fail *incorrectly* when
// called from there.
if ( ! $this->is_page_supported() ) {
return;
}
if ( ! $this->should_show_payment_request_button() ) {
return;
}
$suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
wp_register_script( 'stripe', 'https://js.stripe.com/v3/', '', '3.0', true );
wp_register_script( 'wc_stripe_payment_request', plugins_url( 'assets/js/stripe-payment-request' . $suffix . '.js', WC_STRIPE_MAIN_FILE ), [ 'jquery', 'stripe' ], WC_STRIPE_VERSION, true );
wp_localize_script(
'wc_stripe_payment_request',
'wc_stripe_payment_request_params',
apply_filters(
'wc_stripe_payment_request_params',
$this->javascript_params()
)
);
wp_enqueue_script( 'wc_stripe_payment_request' );
}
/**
* Returns true if the current page supports Payment Request Buttons, false otherwise.
*
* @since 5.3.0
* @version 5.3.0
* @return boolean True if the current page is supported, false otherwise.
*/
private function is_page_supported() {
return $this->is_product()
|| WC_Stripe_Helper::has_cart_or_checkout_on_current_page()
|| is_wc_endpoint_url( 'order-pay' );
}
/**
* Display the payment request button.
*
* @since 4.0.0
* @version 5.2.0
*/
public function display_payment_request_button_html() {
$gateways = WC()->payment_gateways->get_available_payment_gateways();
if ( ! isset( $gateways['stripe'] ) ) {
return;
}
if ( ! $this->is_page_supported() ) {
return;
}
if ( ! $this->should_show_payment_request_button() ) {
return;
}
?>
<div id="wc-stripe-payment-request-wrapper" style="margin-top: 1em;clear:both;display:none;">
<div id="wc-stripe-payment-request-button">
<?php
if ( $this->is_custom_button() ) {
echo '<button id="wc-stripe-custom-button" class="' . esc_attr( 'button ' . $this->get_button_theme() ) . '" style="' . esc_attr( 'height:' . $this->get_button_height() . 'px;' ) . '"> ' . esc_html( $this->get_button_label() ) . ' </button>';
}
?>
<!-- A Stripe Element will be inserted here. -->
</div>
</div>
<?php
$this->display_payment_request_button_separator_html();
}
/**
* Display payment request button separator.
*
* @since 4.0.0
* @version 5.2.0
*/
public function display_payment_request_button_separator_html() {
$gateways = WC()->payment_gateways->get_available_payment_gateways();
if ( ! isset( $gateways['stripe'] ) ) {
return;
}
if ( ! is_checkout() && ! is_wc_endpoint_url( 'order-pay' ) ) {
return;
}
if ( is_checkout() && ! in_array( 'checkout', $this->get_button_locations(), true ) ) {
return;
}
?>
<p id="wc-stripe-payment-request-button-separator" style="margin-top:1.5em;text-align:center;display:none;">— <?php esc_html_e( 'OR', 'woocommerce-gateway-stripe' ); ?> —</p>
<?php
}
/**
* Returns whether at least one of the Express checkouts is enabled.
*
* We have one setting for the Apple Pay / Google Pay wallet and another for Link.
* This method returns true if at least one of those two options is enabled.
*
* @return boolean
*/
public function is_at_least_one_payment_request_button_enabled() {
// Apple Pay / Google Pay is enabled.
if ( $this->is_payment_request_enabled() ) {
return true;
}
// Link is enabled.
if ( WC_Stripe_UPE_Payment_Method_Link::is_link_enabled() ) {
return true;
}
return false;
}
/**
* Returns true if Payment Request Buttons are supported on the current page, false
* otherwise.
*
* @since 5.3.0
* @version 5.3.0
* @return boolean True if PRBs are supported on current page, false otherwise
*/
public function should_show_payment_request_button() {
// If keys are not set bail.
if ( ! $this->are_keys_set() ) {
WC_Stripe_Logger::log( 'Keys are not set correctly.' );
return false;
}
// If no SSL bail.
if ( ! $this->testmode && ! is_ssl() ) {
WC_Stripe_Logger::log( 'Stripe Payment Request live mode requires SSL.' );
return false;
}