-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathclass-wc-payment-gateway-wcpay.php
4349 lines (3863 loc) · 162 KB
/
class-wc-payment-gateway-wcpay.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
/**
* Class WC_Payment_Gateway_WCPay
*
* @package WooCommerce\Payments
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
use WCPay\Constants\Country_Code;
use WCPay\Constants\Fraud_Meta_Box_Type;
use WCPay\Constants\Order_Mode;
use WCPay\Constants\Order_Status;
use WCPay\Constants\Payment_Capture_Type;
use WCPay\Constants\Payment_Initiated_By;
use WCPay\Constants\Intent_Status;
use WCPay\Constants\Payment_Type;
use WCPay\Constants\Payment_Method;
use WCPay\Exceptions\{ Add_Payment_Method_Exception, Amount_Too_Small_Exception, Process_Payment_Exception, Intent_Authentication_Exception, API_Exception, Invalid_Address_Exception};
use WCPay\Core\Server\Request\Cancel_Intention;
use WCPay\Core\Server\Request\Capture_Intention;
use WCPay\Core\Server\Request\Create_And_Confirm_Intention;
use WCPay\Core\Server\Request\Create_And_Confirm_Setup_Intention;
use WCPay\Core\Server\Request\Create_Intention;
use WCPay\Core\Server\Request\Get_Charge;
use WCPay\Core\Server\Request\Get_Intention;
use WCPay\Core\Server\Request\Get_Setup_Intention;
use WCPay\Core\Server\Request\List_Charge_Refunds;
use WCPay\Core\Server\Request\Refund_Charge;
use WCPay\Duplicate_Payment_Prevention_Service;
use WCPay\Fraud_Prevention\Fraud_Prevention_Service;
use WCPay\Fraud_Prevention\Fraud_Risk_Tools;
use WCPay\Internal\Payment\State\AuthenticationRequiredState;
use WCPay\Internal\Payment\State\DuplicateOrderDetectedState;
use WCPay\Internal\Service\DuplicatePaymentPreventionService;
use WCPay\Logger;
use WCPay\Payment_Information;
use WCPay\Payment_Methods\Link_Payment_Method;
use WCPay\WooPay\WooPay_Order_Status_Sync;
use WCPay\WooPay\WooPay_Utilities;
use WCPay\Session_Rate_Limiter;
use WCPay\Tracker;
use WCPay\Internal\Service\PaymentProcessingService;
use WCPay\Internal\Payment\Factor;
use WCPay\Internal\Payment\Router;
use WCPay\Internal\Payment\State\CompletedState;
use WCPay\Internal\Service\Level3Service;
use WCPay\Internal\Service\OrderService;
use WCPay\Payment_Methods\Affirm_Payment_Method;
use WCPay\Payment_Methods\Afterpay_Payment_Method;
use WCPay\Payment_Methods\Bancontact_Payment_Method;
use WCPay\Payment_Methods\Becs_Payment_Method;
use WCPay\Payment_Methods\CC_Payment_Method;
use WCPay\Payment_Methods\Eps_Payment_Method;
use WCPay\Payment_Methods\Giropay_Payment_Method;
use WCPay\Payment_Methods\Ideal_Payment_Method;
use WCPay\Payment_Methods\Klarna_Payment_Method;
use WCPay\Payment_Methods\P24_Payment_Method;
use WCPay\Payment_Methods\Sepa_Payment_Method;
use WCPay\Payment_Methods\Sofort_Payment_Method;
use WCPay\Payment_Methods\UPE_Payment_Method;
/**
* Gateway class for WooPayments
*/
class WC_Payment_Gateway_WCPay extends WC_Payment_Gateway_CC {
use WC_Payment_Gateway_WCPay_Subscriptions_Trait;
/**
* Internal ID of the payment gateway.
*
* @type string
*/
const GATEWAY_ID = 'woocommerce_payments';
const METHOD_ENABLED_KEY = 'enabled';
/**
* Mapping between the client and server accepted params:
* - Keys are WCPay client accepted params (in WC_REST_Payments_Settings_Controller).
* - Values are WCPay Server accepted params.
*
* @type array
*/
const ACCOUNT_SETTINGS_MAPPING = [
'account_statement_descriptor' => 'statement_descriptor',
'account_statement_descriptor_kanji' => 'statement_descriptor_kanji',
'account_statement_descriptor_kana' => 'statement_descriptor_kana',
'account_business_name' => 'business_name',
'account_business_url' => 'business_url',
'account_business_support_address' => 'business_support_address',
'account_business_support_email' => 'business_support_email',
'account_business_support_phone' => 'business_support_phone',
'account_branding_logo' => 'branding_logo',
'account_branding_icon' => 'branding_icon',
'account_branding_primary_color' => 'branding_primary_color',
'account_branding_secondary_color' => 'branding_secondary_color',
'deposit_schedule_interval' => 'deposit_schedule_interval',
'deposit_schedule_weekly_anchor' => 'deposit_schedule_weekly_anchor',
'deposit_schedule_monthly_anchor' => 'deposit_schedule_monthly_anchor',
];
const UPDATE_SAVED_PAYMENT_METHOD = 'wcpay_update_saved_payment_method';
/**
* Set a large limit argument for retrieving user tokens.
*
* @type int
*/
const USER_FORMATTED_TOKENS_LIMIT = 100;
const PROCESS_REDIRECT_ORDER_MISMATCH_ERROR_CODE = 'upe_process_redirect_order_id_mismatched';
const UPE_APPEARANCE_TRANSIENT = 'wcpay_upe_appearance';
const WC_BLOCKS_UPE_APPEARANCE_TRANSIENT = 'wcpay_wc_blocks_upe_appearance';
/**
* Client for making requests to the WooCommerce Payments API
*
* @var WC_Payments_API_Client
*/
protected $payments_api_client;
/**
* WC_Payments_Account instance to get information about the account
*
* @var WC_Payments_Account
*/
protected $account;
/**
* WC_Payments_Customer instance for working with customer information
*
* @var WC_Payments_Customer_Service
*/
protected $customer_service;
/**
* WC_Payments_Token instance for working with customer tokens
*
* @var WC_Payments_Token_Service
*/
protected $token_service;
/**
* WC_Payments_Order_Service instance
*
* @var WC_Payments_Order_Service
*/
protected $order_service;
/**
* WC_Payments_Action_Scheduler_Service instance for scheduling ActionScheduler jobs.
*
* @var WC_Payments_Action_Scheduler_Service
*/
private $action_scheduler_service;
/**
* Session_Rate_Limiter instance for limiting failed transactions.
*
* @var Session_Rate_Limiter
*/
protected $failed_transaction_rate_limiter;
/**
* Mapping between capability keys and payment type keys
*
* @var array
*/
protected $payment_method_capability_key_map;
/**
* WooPay utilities.
*
* @var WooPay_Utilities
*/
protected $woopay_util;
/**
* Duplicate payment prevention service.
*
* @var Duplicate_Payment_Prevention_Service
*/
protected $duplicate_payment_prevention_service;
/**
* WC_Payments_Localization_Service instance.
*
* @var WC_Payments_Localization_Service
*/
protected $localization_service;
/**
* WC_Payments_Fraud_Service instance to get information about fraud services.
*
* @var WC_Payments_Fraud_Service
*/
protected $fraud_service;
/**
* UPE Payment Method for gateway.
*
* @var UPE_Payment_Method
*/
protected $payment_method;
/**
* Array mapping payment method string IDs to classes
*
* @var UPE_Payment_Method[]
*/
protected $payment_methods = [];
/**
* Stripe payment method type ID.
*
* @var string
*/
protected $stripe_id;
/**
* WC_Payment_Gateway_WCPay constructor.
*
* @param WC_Payments_API_Client $payments_api_client - WooCommerce Payments API client.
* @param WC_Payments_Account $account - Account class instance.
* @param WC_Payments_Customer_Service $customer_service - Customer class instance.
* @param WC_Payments_Token_Service $token_service - Token class instance.
* @param WC_Payments_Action_Scheduler_Service $action_scheduler_service - Action Scheduler service instance.
* @param UPE_Payment_Method $payment_method - Specific UPE_Payment_Method instance for gateway.
* @param array $payment_methods - Array of UPE payment methods.
* @param Session_Rate_Limiter|null $failed_transaction_rate_limiter - Rate Limiter for failed transactions.
* @param WC_Payments_Order_Service $order_service - Order class instance.
* @param Duplicate_Payment_Prevention_Service $duplicate_payment_prevention_service - Service for preventing duplicate payments.
* @param WC_Payments_Localization_Service $localization_service - Localization service instance.
* @param WC_Payments_Fraud_Service $fraud_service - Fraud service instance.
*/
public function __construct(
WC_Payments_API_Client $payments_api_client,
WC_Payments_Account $account,
WC_Payments_Customer_Service $customer_service,
WC_Payments_Token_Service $token_service,
WC_Payments_Action_Scheduler_Service $action_scheduler_service,
UPE_Payment_Method $payment_method,
array $payment_methods,
Session_Rate_Limiter $failed_transaction_rate_limiter = null,
WC_Payments_Order_Service $order_service,
Duplicate_Payment_Prevention_Service $duplicate_payment_prevention_service,
WC_Payments_Localization_Service $localization_service,
WC_Payments_Fraud_Service $fraud_service
) {
$this->payment_methods = $payment_methods;
$this->payment_method = $payment_method;
$this->stripe_id = $payment_method->get_id();
$this->payments_api_client = $payments_api_client;
$this->account = $account;
$this->customer_service = $customer_service;
$this->token_service = $token_service;
$this->action_scheduler_service = $action_scheduler_service;
$this->failed_transaction_rate_limiter = $failed_transaction_rate_limiter;
$this->order_service = $order_service;
$this->duplicate_payment_prevention_service = $duplicate_payment_prevention_service;
$this->localization_service = $localization_service;
$this->fraud_service = $fraud_service;
$this->id = static::GATEWAY_ID;
$this->icon = $payment_method->get_icon();
$this->has_fields = true;
$this->method_title = 'WooPayments';
$this->method_description = $this->get_method_description();
$this->title = $payment_method->get_title();
$this->description = '';
$this->supports = [
'products',
'refunds',
];
if ( 'card' !== $this->stripe_id ) {
$this->id = self::GATEWAY_ID . '_' . $this->stripe_id;
$this->method_title = "WooPayments ($this->title)";
}
// Define setting fields.
$this->form_fields = [
'enabled' => [
'title' => __( 'Enable/disable', 'woocommerce-payments' ),
'label' => sprintf(
/* translators: %s: WooPayments */
__( 'Enable %s', 'woocommerce-payments' ),
'WooPayments'
),
'type' => 'checkbox',
'description' => '',
'default' => 'no',
],
'account_statement_descriptor' => [
'type' => 'account_statement_descriptor',
'title' => __( 'Customer bank statement', 'woocommerce-payments' ),
'description' => WC_Payments_Utils::esc_interpolated_html(
__( 'Edit the way your store name appears on your customers’ bank statements (read more about requirements <a>here</a>).', 'woocommerce-payments' ),
[ 'a' => '<a href="https://woo.com/document/woopayments/customization-and-translation/bank-statement-descriptor/" target="_blank" rel="noopener noreferrer">' ]
),
],
'manual_capture' => [
'title' => __( 'Manual capture', 'woocommerce-payments' ),
'label' => __( 'Issue an authorization on checkout, and capture later.', 'woocommerce-payments' ),
'type' => 'checkbox',
'description' => __( 'Charge must be captured within 7 days of authorization, otherwise the authorization and order will be canceled.', 'woocommerce-payments' ),
'default' => 'no',
],
'saved_cards' => [
'title' => __( 'Saved cards', 'woocommerce-payments' ),
'label' => __( 'Enable payment via saved cards', 'woocommerce-payments' ),
'type' => 'checkbox',
'description' => __( 'If enabled, users will be able to pay with a saved card during checkout. Card details are saved on our platform, not on your store.', 'woocommerce-payments' ),
'default' => 'yes',
'desc_tip' => true,
],
'test_mode' => [
'title' => __( 'Test mode', 'woocommerce-payments' ),
'label' => __( 'Enable test mode', 'woocommerce-payments' ),
'type' => 'checkbox',
'description' => __( 'Simulate transactions using test card numbers.', 'woocommerce-payments' ),
'default' => 'no',
'desc_tip' => true,
],
'enable_logging' => [
'title' => __( 'Debug log', 'woocommerce-payments' ),
'label' => __( 'When enabled debug notes will be added to the log.', 'woocommerce-payments' ),
'type' => 'checkbox',
'description' => '',
'default' => 'no',
],
'payment_request_details' => [
'title' => __( 'Payment request buttons', 'woocommerce-payments' ),
'type' => 'title',
'description' => '',
],
'payment_request' => [
'title' => __( 'Enable/disable', 'woocommerce-payments' ),
'label' => sprintf(
/* translators: 1) br tag 2) Stripe anchor tag 3) Apple anchor tag */
__( 'Enable payment request buttons (Apple Pay, Google Pay, and more). %1$sBy using Apple Pay, you agree to %2$s and %3$s\'s Terms of Service.', 'woocommerce-payments' ),
'<br />',
'<a href="https://stripe.com/apple-pay/legal" target="_blank">Stripe</a>',
'<a href="https://developer.apple.com/apple-pay/acceptable-use-guidelines-for-websites/" target="_blank">Apple</a>'
),
'type' => 'checkbox',
'description' => __( 'If enabled, users will be able to pay using Apple Pay, Google Pay or the Payment Request API if supported by the browser.', 'woocommerce-payments' ),
'default' => empty( get_option( 'woocommerce_woocommerce_payments_settings' ) ) ? 'yes' : 'no', // Enable by default for new installations only.
'desc_tip' => true,
],
'payment_request_button_type' => [
'title' => __( 'Button type', 'woocommerce-payments' ),
'type' => 'select',
'description' => __( 'Select the button type you would like to show.', 'woocommerce-payments' ),
'default' => 'buy',
'desc_tip' => true,
'options' => [
'default' => __( 'Only icon', 'woocommerce-payments' ),
'buy' => __( 'Buy', 'woocommerce-payments' ),
'donate' => __( 'Donate', 'woocommerce-payments' ),
'book' => __( 'Book', 'woocommerce-payments' ),
],
],
'payment_request_button_theme' => [
'title' => __( 'Button theme', 'woocommerce-payments' ),
'type' => 'select',
'description' => __( 'Select the button theme you would like to show.', 'woocommerce-payments' ),
'default' => 'dark',
'desc_tip' => true,
'options' => [
'dark' => __( 'Dark', 'woocommerce-payments' ),
'light' => __( 'Light', 'woocommerce-payments' ),
'light-outline' => __( 'Light-Outline', 'woocommerce-payments' ),
],
],
'payment_request_button_height' => [
'title' => __( 'Button height', 'woocommerce-payments' ),
'type' => 'text',
'description' => __( 'Enter the height you would like the button to be in pixels. Width will always be 100%.', 'woocommerce-payments' ),
'default' => '44',
'desc_tip' => true,
],
'payment_request_button_label' => [
'title' => __( 'Custom button label', 'woocommerce-payments' ),
'type' => 'text',
'description' => __( 'Enter the custom text you would like the button to have.', 'woocommerce-payments' ),
'default' => __( 'Buy now', 'woocommerce-payments' ),
'desc_tip' => true,
],
'payment_request_button_locations' => [
'title' => __( 'Button locations', 'woocommerce-payments' ),
'type' => 'multiselect',
'description' => __( 'Select where you would like to display the button.', 'woocommerce-payments' ),
'default' => [
'product',
'cart',
'checkout',
],
'class' => 'wc-enhanced-select',
'desc_tip' => true,
'options' => [
'product' => __( 'Product', 'woocommerce-payments' ),
'cart' => __( 'Cart', 'woocommerce-payments' ),
'checkout' => __( 'Checkout', 'woocommerce-payments' ),
],
'custom_attributes' => [
'data-placeholder' => __( 'Select pages', 'woocommerce-payments' ),
],
],
'upe_enabled_payment_method_ids' => [
'title' => __( 'Payments accepted on checkout', 'woocommerce-payments' ),
'type' => 'multiselect',
'default' => [ 'card' ],
'options' => [],
],
'payment_request_button_size' => [
'title' => __( 'Size of the button displayed for Express Checkouts', 'woocommerce-payments' ),
'type' => 'select',
'description' => __( 'Select the size of the button.', 'woocommerce-payments' ),
'default' => 'medium',
'desc_tip' => true,
'options' => [
'small' => __( 'Small', 'woocommerce-payments' ),
'medium' => __( 'Medium', 'woocommerce-payments' ),
'large' => __( 'Large', 'woocommerce-payments' ),
],
],
'platform_checkout_button_locations' => [
'title' => __( 'WooPay button locations', 'woocommerce-payments' ),
'type' => 'multiselect',
'description' => __( 'Select where you would like to display the button.', 'woocommerce-payments' ),
'default' => [
'product',
'cart',
'checkout',
],
'class' => 'wc-enhanced-select',
'desc_tip' => true,
'options' => [
'product' => __( 'Product', 'woocommerce-payments' ),
'cart' => __( 'Cart', 'woocommerce-payments' ),
'checkout' => __( 'Checkout', 'woocommerce-payments' ),
],
'custom_attributes' => [
'data-placeholder' => __( 'Select pages', 'woocommerce-payments' ),
],
],
'platform_checkout_custom_message' => [ 'default' => __( 'By placing this order, you agree to our [terms] and understand our [privacy_policy].', 'woocommerce-payments' ) ],
];
// Capabilities have different keys than the payment method ID's,
// so instead of appending '_payments' to the end of the ID, it'll be better
// to have a map for it instead, just in case the pattern changes.
$this->payment_method_capability_key_map = [
'sofort' => 'sofort_payments',
'giropay' => 'giropay_payments',
'bancontact' => 'bancontact_payments',
'eps' => 'eps_payments',
'ideal' => 'ideal_payments',
'p24' => 'p24_payments',
'card' => 'card_payments',
'sepa_debit' => 'sepa_debit_payments',
'au_becs_debit' => 'au_becs_debit_payments',
'link' => 'link_payments',
'affirm' => 'affirm_payments',
'afterpay_clearpay' => 'afterpay_clearpay_payments',
'klarna' => 'klarna_payments',
'jcb' => 'jcb_payments',
];
// WooPay utilities.
$this->woopay_util = new WooPay_Utilities();
// Load the settings.
$this->init_settings();
// Check if subscriptions are enabled and add support for them.
$this->maybe_init_subscriptions();
// If the setting to enable saved cards is enabled, then we should support tokenization and adding payment methods.
if ( $this->is_saved_cards_enabled() ) {
array_push( $this->supports, 'tokenization', 'add_payment_method' );
}
}
/**
* Initializes this class's WP hooks.
*
* @return void
*/
public function init_hooks() {
add_action( 'init', [ $this, 'maybe_update_properties_with_country' ] );
// Only add certain actions/filter if this is the main gateway (i.e. not split UPE).
if ( self::GATEWAY_ID === $this->id ) {
add_action( 'woocommerce_order_actions', [ $this, 'add_order_actions' ] );
add_action( 'woocommerce_order_action_capture_charge', [ $this, 'capture_charge' ] );
add_action( 'woocommerce_order_action_cancel_authorization', [ $this, 'cancel_authorization' ] );
add_action( 'woocommerce_order_status_cancelled', [ $this, 'cancel_authorizations_on_order_cancel' ] );
add_action( 'wp_ajax_update_order_status', [ $this, 'update_order_status' ] );
add_action( 'wp_ajax_nopriv_update_order_status', [ $this, 'update_order_status' ] );
add_action( 'wp_ajax_create_setup_intent', [ $this, 'create_setup_intent_ajax' ] );
add_action( 'wp_ajax_nopriv_create_setup_intent', [ $this, 'create_setup_intent_ajax' ] );
// Update the current request logged_in cookie after a guest user is created to avoid nonce inconsistencies.
add_action( 'set_logged_in_cookie', [ $this, 'set_cookie_on_current_request' ] );
add_action( self::UPDATE_SAVED_PAYMENT_METHOD, [ $this, 'update_saved_payment_method' ], 10, 3 );
// Update the email field position.
add_filter( 'woocommerce_billing_fields', [ $this, 'checkout_update_email_field_priority' ], 50 );
add_action( 'woocommerce_update_order', [ $this, 'schedule_order_tracking' ], 10, 2 );
add_filter( 'rest_request_before_callbacks', [ $this, 'remove_all_actions_on_preflight_check' ], 10, 3 );
}
$this->maybe_init_subscriptions_hooks();
}
/**
* Updates icon and title using the account country.
* This method runs on init is not in the controller because get_account_country might
* make a request to the API if the account data is not cached.
*
* @return void
*/
public function maybe_update_properties_with_country(): void {
if ( Afterpay_Payment_Method::PAYMENT_METHOD_STRIPE_ID !== $this->stripe_id ) {
return;
}
$account_country = $this->get_account_country();
$this->icon = $this->payment_method->get_icon( $account_country );
$this->title = $this->payment_method->get_title( $account_country );
}
/**
* Displays HTML tags for WC payment gateway radio button content.
*/
public function display_gateway_html() {
?>
<div class="wcpay-upe-element" data-payment-method-type="<?php echo esc_attr( $this->stripe_id ); ?>"></div>
<?php
}
/**
* Renders the credit card input fields needed to get the user's payment information on the checkout page.
*
* We also add the JavaScript which drives the UI.
*/
public function payment_fields() {
do_action( 'wc_payments_set_gateway', $this->get_selected_stripe_payment_type_id() );
do_action( 'wc_payments_add_upe_payment_fields' );
}
/**
* Adds a token to current user from a setup intent id.
*
* @param string $setup_intent_id ID of the setup intent.
* @param WP_User $user User to add token to.
*
* @return WC_Payment_Token_CC|WC_Payment_Token_WCPay_SEPA|null The added token.
*/
public function create_token_from_setup_intent( $setup_intent_id, $user ) {
try {
$setup_intent_request = Get_Setup_Intention::create( $setup_intent_id );
/** @var WC_Payments_API_Setup_Intention $setup_intent */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$setup_intent = $setup_intent_request->send();
$payment_method_id = $setup_intent->get_payment_method_id();
// TODO: When adding SEPA and Sofort, we will need a new API call to get the payment method and from there get the type.
// Leaving 'card' as a hardcoded value for now to avoid the extra API call.
// $payment_method = $this->payment_methods['card'];// Maybe this should be enforced.
$payment_method = $this->payment_method;
return $payment_method->get_payment_token_for_user( $user, $payment_method_id );
} catch ( Exception $e ) {
wc_add_notice( WC_Payments_Utils::get_filtered_error_message( $e ), 'error', [ 'icon' => 'error' ] );
Logger::log( 'Error when adding payment method: ' . $e->getMessage() );
}
}
/**
* Validate order_id received from the request vs value saved in the intent metadata.
* Throw an exception if they're not matched.
*
* @param WC_Order $order The received order to process.
* @param array $intent_metadata The metadata of attached intent to the order.
*
* @return void
* @throws Process_Payment_Exception
*/
private function validate_order_id_received_vs_intent_meta_order_id( WC_Order $order, array $intent_metadata ): void {
$intent_meta_order_id_raw = $intent_metadata['order_id'] ?? '';
$intent_meta_order_id = is_numeric( $intent_meta_order_id_raw ) ? intval( $intent_meta_order_id_raw ) : 0;
if ( $order->get_id() !== $intent_meta_order_id ) {
Logger::error(
sprintf(
'UPE Process Redirect Payment - Order ID mismatched. Received: %1$d. Intent Metadata Value: %2$d',
$order->get_id(),
$intent_meta_order_id
)
);
throw new Process_Payment_Exception(
__( "We're not able to process this payment due to the order ID mismatch. Please try again later.", 'woocommerce-payments' ),
self::PROCESS_REDIRECT_ORDER_MISMATCH_ERROR_CODE
);
}
}
/**
* If we're in a WooPay preflight check, remove all the checkout order processed
* actions to prevent a quantity reduction of the available resources.
*
* @param mixed $response The response object.
* @param mixed $handler The handler used for the response.
* @param WP_REST_Request $request The request used to generate the response.
*
* @return mixed
*/
public function remove_all_actions_on_preflight_check( $response, $handler, $request ) {
$payment_data = $this->get_request_payment_data( $request );
if ( ! empty( $payment_data['is-woopay-preflight-check'] ) ) {
remove_all_actions( 'woocommerce_store_api_checkout_update_order_meta' );
remove_all_actions( 'woocommerce_store_api_checkout_order_processed' );
// Avoid increasing coupon usage count during preflight check.
remove_all_actions( 'woocommerce_order_status_pending' );
}
return $response;
}
/**
* Gets and formats payment request data.
*
* @param \WP_REST_Request $request Request object.
* @return array
*/
private function get_request_payment_data( \WP_REST_Request $request ) {
static $payment_data = [];
if ( ! empty( $payment_data ) ) {
return $payment_data;
}
if ( ! empty( $request['payment_data'] ) ) {
foreach ( $request['payment_data'] as $data ) {
$payment_data[ sanitize_key( $data['key'] ) ] = wc_clean( $data['value'] );
}
}
return $payment_data;
}
/**
* Proceed with current request using new login session (to ensure consistent nonce).
* Only apply during the checkout process with the account creation.
*
* @param string $cookie New cookie value.
*/
public function set_cookie_on_current_request( $cookie ) {
if ( defined( 'WOOCOMMERCE_CHECKOUT' ) && WOOCOMMERCE_CHECKOUT && did_action( 'woocommerce_created_customer' ) > 0 ) {
$_COOKIE[ LOGGED_IN_COOKIE ] = $cookie;
}
}
/**
* Check if the payment gateway is connected. This method is also used by
* external plugins to check if a connection has been established.
*/
public function is_connected() {
return $this->account->is_stripe_connected();
}
/**
* Checks if the account has not completed onboarding due to users abandoning the process half way.
* Also used by WC Core to complete the task "Set up WooPayments".
* Called directly by WooCommerce Core.
*
* @return bool
*/
public function is_account_partially_onboarded(): bool {
return $this->account->is_stripe_connected() && ! $this->account->is_details_submitted();
}
/**
* Returns the URL of the configuration screen for this gateway, for use in internal links.
* Called directly by WooCommerce Core.
*
* @return string URL of the configuration screen for this gateway
*/
public static function get_settings_url() {
return WC_Payments_Admin_Settings::get_settings_url();
}
/**
* Text provided to users during onboarding setup.
* Called directly by WooCommerce Core.
*
* @return string
*/
public function get_setup_help_text() {
return __( 'Next we’ll ask you to share a few details about your business to create your account.', 'woocommerce-payments' );
}
/**
* Get the connection URL.
* Called directly by WooCommerce Core.
*
* @return string Connection URL.
*/
public function get_connection_url() {
$account_data = $this->account->get_cached_account_data();
// The onboarding is finished if account_id is set. `Set up` will be shown instead of `Connect`.
if ( isset( $account_data['account_id'] ) ) {
return '';
}
return html_entity_decode( WC_Payments_Account::get_connect_url( 'WCADMIN_PAYMENT_TASK' ) );
}
/**
* Add a url to the admin order page that links directly to the transactions detail view.
* Called directly by WooCommerce Core.
*
* @since 1.4.0
*
* @param WC_Order $order The context passed into this function when the user view the order details page in WordPress admin.
* @return string
*/
public function get_transaction_url( $order ) {
$intent_id = $this->order_service->get_intent_id_for_order( $order );
$charge_id = $this->order_service->get_charge_id_for_order( $order );
return WC_Payments_Utils::compose_transaction_url( $intent_id, $charge_id );
}
/**
* Returns true if the gateway needs additional configuration, false if it's ready to use.
*
* @see WC_Payment_Gateway::needs_setup
* @return bool
*/
public function needs_setup() {
if ( ! $this->is_connected() ) {
return true;
}
$account_status = $this->account->get_account_status_data();
return parent::needs_setup() || ! empty( $account_status['error'] ) || ! $account_status['paymentsEnabled'];
}
/**
* Returns whether a store that is not in test mode needs to set https
* in the checkout
*
* @return boolean True if needs to set up forced ssl in checkout or https
*/
public function needs_https_setup() {
return ! WC_Payments::mode()->is_test() && ! wc_checkout_is_https();
}
/**
* Checks if the gateway is enabled, and also if it's configured enough to accept payments from customers.
*
* Use parent method value alongside other business rules to make the decision.
*
* @return bool Whether the gateway is enabled and ready to accept payments.
*/
public function is_available() {
$processing_payment_method = $this->payment_methods[ $this->payment_method->get_id() ];
if ( ! $processing_payment_method->is_enabled_at_checkout( $this->get_account_country() ) ) {
return false;
}
// Disable the gateway if using live mode without HTTPS set up or the currency is not
// available in the country of the account.
if ( $this->needs_https_setup() || ! $this->is_available_for_current_currency() ) {
return false;
}
return parent::is_available() && ! $this->needs_setup();
}
/**
* Overrides the parent method by adding an additional check to see if the tokens list is empty.
* If it is, the method avoids displaying the HTML element with an empty line to maintain a clean user interface and remove unnecessary space.
*
* @return void
*/
public function saved_payment_methods() {
if ( empty( $this->get_tokens() ) ) {
return;
}
parent::saved_payment_methods();
}
/**
* Checks if the setting to allow the user to save cards is enabled.
*
* @return bool Whether the setting to allow saved cards is enabled or not.
*/
public function is_saved_cards_enabled() {
return 'yes' === $this->get_option( 'saved_cards' );
}
/**
* Check if account is eligible for card present.
*
* @return bool
*/
public function is_card_present_eligible(): bool {
try {
return $this->account->is_card_present_eligible();
} catch ( Exception $e ) {
Logger::error( 'Failed to get account card present eligible. ' . $e );
return false;
}
}
/**
* Check if account is eligible for card testing protection.
*
* @return bool
*/
public function is_card_testing_protection_eligible(): bool {
try {
return $this->account->is_card_testing_protection_eligible();
} catch ( Exception $e ) {
Logger::error( 'Failed to get account card testing protection eligible. ' . $e );
return false;
}
}
/**
* Checks if the account country is compatible with the current currency.
*
* @return bool Whether the currency is supported in the country set in the account.
*/
public function is_available_for_current_currency() {
$supported_currencies = $this->account->get_account_customer_supported_currencies();
$current_currency = strtolower( get_woocommerce_currency() );
if ( count( $supported_currencies ) === 0 ) {
// If we don't have info related to the supported currencies
// of the country, we won't disable the gateway.
return true;
}
return in_array( $current_currency, $supported_currencies, true );
}
/**
* Admin Panel Options.
*/
public function admin_options() {
// Add notices to the WooPayments settings page.
do_action( 'woocommerce_woocommerce_payments_admin_notices' );
$this->output_payments_settings_screen();
}
/**
* Generates markup for the settings screen.
*/
public function output_payments_settings_screen() {
// hiding the save button because the react container has its own.
global $hide_save_button;
$hide_save_button = true;
if ( ! empty( $_GET['method'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended
?>
<div
id="wcpay-express-checkout-settings-container"
data-method-id="<?php echo esc_attr( sanitize_text_field( wp_unslash( $_GET['method'] ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>"
></div>
<?php else : ?>
<div id="wcpay-account-settings-container"></div>
<?php
endif;
}
/**
* Displays the save to account checkbox.
*
* @param bool $force_checked True if the checkbox must be forced to "checked" state (and invisible).
*/
public function save_payment_method_checkbox( $force_checked = false ) {
$id = 'wc-' . $this->id . '-new-payment-method';
$should_hide = $force_checked || $this->should_use_stripe_platform_on_checkout_page();
?>
<div <?php echo $should_hide ? 'style="display:none;"' : ''; /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped */ ?>>
<p class="form-row woocommerce-SavedPaymentMethods-saveNew">
<input id="<?php echo esc_attr( $id ); ?>" name="<?php echo esc_attr( $id ); ?>" type="checkbox" value="true" style="width:auto; vertical-align: middle; position: relative; bottom: 1px;" <?php echo $force_checked ? 'checked' : ''; /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped */ ?> />
<label for="<?php echo esc_attr( $id ); ?>" style="display:inline;">
<?php echo esc_html( apply_filters( 'wc_payments_save_to_account_text', __( 'Save payment information to my account for future purchases.', 'woocommerce-payments' ) ) ); ?>
</label>
</p>
</div>
<?php
}
/**
* Whether we should use the platform account to initialize Stripe on the checkout page.
*
* @return bool
*/
public function should_use_stripe_platform_on_checkout_page() {
if ( 'card' !== $this->stripe_id ) {
return false;
}
if (
WC_Payments_Features::is_woopay_eligible() &&
'yes' === $this->get_option( 'platform_checkout', 'no' ) &&
( is_checkout() || has_block( 'woocommerce/checkout' ) ) &&
! is_wc_endpoint_url( 'order-pay' ) &&
WC()->cart instanceof WC_Cart &&
! WC()->cart->is_empty() &&
WC()->cart->needs_payment()
) {
return true;
}
return false;
}
/**
* Checks whether the new payment process should be used to pay for a given order.
*
* @param WC_Order $order Order that's being paid.
* @return bool
*/
public function should_use_new_process( WC_Order $order ) {
$order_id = $order->get_id();
// The new process us under active development, and not ready for production yet.
if ( ! WC_Payments::mode()->is_dev() ) {
return false;
}
// This array will contain all factors, present during checkout.
$factors = [
/**
* The new payment process is a factor itself.
* Even if no other factors are present, this will make entering
* the new payment process possible only if this factor is allowed.
*/
Factor::NEW_PAYMENT_PROCESS(),
];
// If there is a token in the request, we're using a saved PM.
// phpcs:ignore WordPress.Security.NonceVerification.Missing
$using_saved_payment_method = ! empty( Payment_Information::get_token_from_request( $_POST ) );
if ( $using_saved_payment_method ) {
$factors[] = Factor::USE_SAVED_PM();
}
// The PM should be saved when chosen, or when it's a recurrent payment, but not if already saved.
$save_payment_method = ! $using_saved_payment_method && (
// phpcs:ignore WordPress.Security.NonceVerification.Missing
! empty( $_POST[ 'wc-' . static::GATEWAY_ID . '-new-payment-method' ] )
|| $this->is_payment_recurring( $order_id )
);
if ( $save_payment_method ) {
$factors[] = Factor::SAVE_PM();
}
// In case amount is 0 and we're not saving the payment method, we won't be using intents and can confirm the order payment.
if (
apply_filters(
'wcpay_confirm_without_payment_intent',
$order->get_total() <= 0 && ! $save_payment_method
)
) {
$factors[] = Factor::NO_PAYMENT();
}
// Subscription (both WCPay and WCSubs) if when the order contains one.
if ( function_exists( 'wcs_order_contains_subscription' ) && wcs_order_contains_subscription( $order_id ) ) {
$factors[] = Factor::SUBSCRIPTION_SIGNUP();
}
// WooPay might change how payment fields were loaded.
if (
$this->woopay_util->should_enable_woopay( $this )
&& $this->woopay_util->should_enable_woopay_on_cart_or_checkout()
) {
$factors[] = Factor::WOOPAY_ENABLED();
}