-
Notifications
You must be signed in to change notification settings - Fork 69
/
class-wc-payment-gateway-wcpay.php
3263 lines (2894 loc) · 120 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\Order_Status;
use WCPay\Constants\Payment_Capture_Type;
use WCPay\Constants\Payment_Initiated_By;
use WCPay\Constants\Payment_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 };
use WCPay\Fraud_Prevention\Fraud_Prevention_Service;
use WCPay\Logger;
use WCPay\Payment_Information;
use WCPay\Payment_Methods\UPE_Payment_Gateway;
use WCPay\Payment_Methods\Link_Payment_Method;
use WCPay\Platform_Checkout\Platform_Checkout_Order_Status_Sync;
use WCPay\Platform_Checkout\Platform_Checkout_Utilities;
use WCPay\Session_Rate_Limiter;
use WCPay\Tracker;
/**
* Gateway class for WooCommerce Payments
*/
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';
const ACCOUNT_SETTINGS_MAPPING = [
'account_statement_descriptor' => 'statement_descriptor',
'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',
];
/**
* Stripe intents that are treated as successfully created.
*
* @type array
*/
const SUCCESSFUL_INTENT_STATUS = [
Payment_Intent_Status::SUCCEEDED,
Payment_Intent_Status::REQUIRES_CAPTURE,
Payment_Intent_Status::PROCESSING,
];
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;
/**
* Key name for saving the current processing order_id to WC Session with the purpose
* of preventing duplicate payments in a single order.
*
* @type string
*/
const SESSION_KEY_PROCESSING_ORDER = 'wcpay_processing_order';
/**
* Flag to indicate that a previous order with the same cart content has already paid.
*
* @type string
*/
const FLAG_PREVIOUS_ORDER_PAID = 'wcpay_paid_for_previous_order';
/**
* Flag to indicate that a previous intention attached to the order was successful.
*/
const FLAG_PREVIOUS_SUCCESSFUL_INTENT = 'wcpay_previous_successful_intent';
/**
* 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;
/**
* Platform checkout utilities.
*
* @var Platform_Checkout_Utilities
*/
protected $platform_checkout_util;
/**
* 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 Session_Rate_Limiter $failed_transaction_rate_limiter - Rate Limiter for failed transactions.
* @param WC_Payments_Order_Service $order_service - Order class 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,
Session_Rate_Limiter $failed_transaction_rate_limiter = null,
WC_Payments_Order_Service $order_service
) {
$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->id = static::GATEWAY_ID;
$this->icon = ''; // TODO: icon.
$this->has_fields = true;
$this->method_title = __( 'WooCommerce Payments', 'woocommerce-payments' );
$this->method_description = WC_Payments_Utils::esc_interpolated_html(
/* translators: tosLink: Link to terms of service page, privacyLink: Link to privacy policy page */
__(
'WooCommerce Payments gives your store flexibility to accept credit cards, debit cards, and Apple Pay. Enable popular local payment methods and other digital wallets like Google Pay to give customers even more choice.<br/><br/>
By using WooCommerce Payments you agree to be bound by our <tosLink>Terms of Service</tosLink> and acknowledge that you have read our <privacyLink>Privacy Policy</privacyLink>',
'woocommerce-payments'
),
[
'br' => '<br/>',
'tosLink' => '<a href="https://wordpress.com/tos/" target="_blank" rel="noopener noreferrer">',
'privacyLink' => '<a href="https://automattic.com/privacy/" target="_blank" rel="noopener noreferrer">',
]
);
$this->title = __( 'Credit card / debit card', 'woocommerce-payments' );
$this->description = __( 'Enter your card details', 'woocommerce-payments' );
$this->supports = [
'products',
'refunds',
];
// Define setting fields.
$this->form_fields = [
'enabled' => [
'title' => __( 'Enable/disable', 'woocommerce-payments' ),
'label' => __( 'Enable WooCommerce Payments', 'woocommerce-payments' ),
'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://woocommerce.com/document/payments/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' => 'default',
'desc_tip' => true,
'options' => [
'default' => __( 'Default', 'woocommerce-payments' ),
'medium' => __( 'Medium', 'woocommerce-payments' ),
'large' => __( 'Large', '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',
];
// Platform checkout utilities.
$this->platform_checkout_util = new Platform_Checkout_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' );
}
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, [ $this, 'process_admin_options' ] );
add_action( 'admin_notices', [ $this, 'display_errors' ], 9999 );
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( 'wp_ajax_update_order_status', [ $this, 'update_order_status' ] );
add_action( 'wp_ajax_nopriv_update_order_status', [ $this, 'update_order_status' ] );
add_action( 'wp_enqueue_scripts', [ $this, 'register_scripts' ] );
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' ] );
add_action( 'woocommerce_update_order', [ $this, 'schedule_order_tracking' ], 10, 2 );
// 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 );
// Priority 21 to run right after wc_clear_cart_after_payment.
add_action( 'template_redirect', [ $this, 'clear_session_processing_order_after_landing_order_received_page' ], 21 );
}
/**
* Proceed with current request using new login session (to ensure consistent nonce).
*
* @param string $cookie New cookie value.
*/
public function set_cookie_on_current_request( $cookie ) {
$_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();
}
/**
* 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'];
}
/**
* Check the defined constant to determine the current plugin mode.
*
* @return bool
*/
public function is_in_dev_mode() {
$is_extension_dev_mode = defined( 'WCPAY_DEV_MODE' ) && WCPAY_DEV_MODE;
$is_wordpress_dev_environment = function_exists( 'wp_get_environment_type' ) && in_array( wp_get_environment_type(), [ 'development', 'staging' ], true );
return apply_filters( 'wcpay_dev_mode', $is_extension_dev_mode || $is_wordpress_dev_environment );
}
/**
* Returns whether test_mode or dev_mode is active for the gateway
*
* @return boolean Test mode enabled if true, disabled if false
*/
public function is_in_test_mode() {
return apply_filters( 'wcpay_test_mode', $this->is_in_dev_mode() || 'yes' === $this->get_option( 'test_mode' ) );
}
/**
* 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 ! $this->is_in_test_mode() && ! 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() {
// 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();
}
/**
* 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 WooCommerce Payments 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;
}
/**
* Registers all scripts, necessary for the gateway.
*/
public function register_scripts() {
// Register Stripe's JavaScript using the same ID as the Stripe Gateway plugin. This prevents this JS being
// loaded twice in the event a site has both plugins enabled. We still run the risk of different plugins
// loading different versions however. If Stripe release a v4 of their JavaScript, we could consider
// changing the ID to stripe_v4. This would allow older plugins to keep using v3 while we used any new
// feature in v4. Stripe have allowed loading of 2 different versions of stripe.js in the past (
// https://stripe.com/docs/stripe-js/elements/migrating).
wp_register_script(
'stripe',
'https://js.stripe.com/v3/',
[],
'3.0',
true
);
$script_dependencies = [ 'stripe', 'wc-checkout' ];
if ( $this->supports( 'tokenization' ) ) {
$script_dependencies[] = 'woocommerce-tokenization-form';
}
wp_register_script(
'WCPAY_CHECKOUT',
plugins_url( 'dist/checkout.js', WCPAY_PLUGIN_FILE ),
$script_dependencies,
WC_Payments::get_file_version( 'dist/checkout.js' ),
true
);
wp_set_script_translations( 'WCPAY_CHECKOUT', 'woocommerce-payments' );
}
/**
* 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;" <?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 (
WC_Payments_Features::is_platform_checkout_eligible() &&
'yes' === $this->get_option( 'platform_checkout', 'no' ) &&
! WC_Payments_Features::is_upe_enabled() &&
( is_checkout() || has_block( 'woocommerce/checkout' ) ) &&
! is_wc_endpoint_url( 'order-pay' ) &&
! WC()->cart->is_empty() &&
WC()->cart->needs_payment()
) {
return true;
}
return false;
}
/**
* 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_add_payment_fields' );
}
/**
* Process the payment for a given order.
*
* @param int $order_id Order ID to process the payment for.
*
* @return array|null An array with result of payment and redirect URL, or nothing.
* @throws Process_Payment_Exception Error processing the payment.
* @throws Exception Error processing the payment.
*/
public function process_payment( $order_id ) {
$order = wc_get_order( $order_id );
try {
// Check if session exists before instantiating Fraud_Prevention_Service.
if ( WC()->session ) {
$fraud_prevention_service = Fraud_Prevention_Service::get_instance();
// phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.MissingUnslash,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
if ( $fraud_prevention_service->is_enabled() && ! $fraud_prevention_service->verify_token( $_POST['wcpay-fraud-prevention-token'] ?? null ) ) {
throw new Process_Payment_Exception(
__( "We're not able to process this payment. Please refresh the page and try again.", 'woocommerce-payments' ),
'fraud_prevention_enabled'
);
}
}
if ( $this->failed_transaction_rate_limiter->is_limited() ) {
throw new Process_Payment_Exception(
__( 'Your payment was not processed.', 'woocommerce-payments' ),
'rate_limiter_enabled'
);
}
// The request is a preflight check from WooPay.
// phpcs:ignore WordPress.Security.NonceVerification.Missing
if ( ! empty( $_POST['is-woopay-preflight-check'] ) ) {
// Set the order status to "pending payment".
$order->update_status( 'pending' );
// Bail out with success so we don't process the payment now,
// but still let WooPay continue with the payment processing.
return [
'result' => 'success',
'redirect' => '',
];
}
UPE_Payment_Gateway::remove_upe_payment_intent_from_session();
$check_session_order = $this->check_against_session_processing_order( $order );
if ( is_array( $check_session_order ) ) {
return $check_session_order;
}
$this->maybe_update_session_processing_order( $order_id );
$check_existing_intention = $this->check_payment_intent_attached_to_order_succeeded( $order );
if ( is_array( $check_existing_intention ) ) {
return $check_existing_intention;
}
$payment_information = $this->prepare_payment_information( $order );
return $this->process_payment_for_order( WC()->cart, $payment_information );
} catch ( Exception $e ) {
/**
* TODO: Determine how to do this update with Order_Service.
* It seems that the status only needs to change in certain instances, and within those instances the intent
* information is not added to the order, as shown by tests.
*/
if ( empty( $payment_information ) || ! $payment_information->is_changing_payment_method_for_subscription() ) {
$order->update_status( Order_Status::FAILED );
}
if ( $e instanceof API_Exception && $this->should_bump_rate_limiter( $e->get_error_code() ) ) {
$this->failed_transaction_rate_limiter->bump();
}
if ( ! empty( $payment_information ) ) {
/* translators: %1: the failed payment amount, %2: error message */
$error_message = __(
'A payment of %1$s <strong>failed</strong> to complete with the following message: <code>%2$s</code>.',
'woocommerce-payments'
);
$error_details = esc_html( rtrim( $e->getMessage(), '.' ) );
if ( $e instanceof API_Exception && 'card_error' === $e->get_error_type() && 'incorrect_zip' === $e->get_error_code() ) {
/* translators: %1: the failed payment amount, %2: error message */
$error_message = __(
'A payment of %1$s <strong>failed</strong>. %2$s',
'woocommerce-payments'
);
$error_details = __(
'We couldn’t verify the postal code in the billing address. If the issue persists, suggest the customer to reach out to the card issuing bank.',
'woocommerce-payments'
);
}
$note = sprintf(
WC_Payments_Utils::esc_interpolated_html(
$error_message,
[
'strong' => '<strong>',
'code' => '<code>',
]
),
WC_Payments_Explicit_Price_Formatter::get_explicit_price( wc_price( $order->get_total(), [ 'currency' => $order->get_currency() ] ), $order ),
$error_details
);
$order->add_order_note( $note );
}
if ( $e instanceof Process_Payment_Exception && 'rate_limiter_enabled' === $e->get_error_code() ) {
$note = sprintf(
WC_Payments_Utils::esc_interpolated_html(
/* translators: %1: the failed payment amount */
__(
'A payment of %1$s <strong>failed</strong> to complete because of too many failed transactions. A rate limiter was enabled for the user to prevent more attempts temporarily.',
'woocommerce-payments'
),
[
'strong' => '<strong>',
]
),
WC_Payments_Explicit_Price_Formatter::get_explicit_price( wc_price( $order->get_total(), [ 'currency' => $order->get_currency() ] ), $order )
);
$order->add_order_note( $note );
}
UPE_Payment_Gateway::remove_upe_payment_intent_from_session();
// Re-throw the exception after setting everything up.
// This makes the error notice show up both in the regular and block checkout.
throw new Exception( WC_Payments_Utils::get_filtered_error_message( $e ) );
}
}
/**
* Prepares the payment information object.
*
* @param WC_Order $order The order whose payment will be processed.
* @return Payment_Information An object, which describes the payment.
*/
protected function prepare_payment_information( $order ) {
// phpcs:ignore WordPress.Security.NonceVerification.Missing
$payment_information = Payment_Information::from_payment_request( $_POST, $order, Payment_Type::SINGLE(), Payment_Initiated_By::CUSTOMER(), $this->get_capture_type() );
$payment_information = $this->maybe_prepare_subscription_payment_information( $payment_information, $order->get_id() );
if ( ! empty( $_POST[ 'wc-' . static::GATEWAY_ID . '-new-payment-method' ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
// During normal orders the payment method is saved when the customer enters a new one and chooses to save it.
$payment_information->must_save_payment_method_to_store();
}
if ( $this->platform_checkout_util->should_save_platform_customer() ) {
do_action( 'woocommerce_payments_save_user_in_platform_checkout' );
$payment_information->must_save_payment_method_to_platform();
}
return $payment_information;
}
/**
* Update the customer details with the incoming order data, in a CRON job.
*
* @param \WC_Order $order WC order id.
* @param string $customer_id The customer id to update details for.
* @param bool $is_test_mode Whether to run the CRON job in test mode.
* @param bool $is_woopay Whether CRON job was queued from WooPay.
*/
public function update_customer_with_order_data( $order, $customer_id, $is_test_mode = false, $is_woopay = false ) {
// Since this CRON job may have been created in test_mode, when the CRON job runs, it
// may lose the test_mode context. So, instead, we pass that context when creating
// the CRON job and apply the context here.
$apply_test_mode_context = function () use ( $is_test_mode ) {
return $is_test_mode;
};
add_filter( 'wcpay_test_mode', $apply_test_mode_context );
$user = $order->get_user();
if ( false === $user ) {
$user = wp_get_current_user();
}
// Since this function will run in a CRON job, "wp_get_current_user()" will default
// to user with ID of 0. So, instead, we replace it with the user from the $order,
// when updating a WooPay user.
$apply_order_user_email = function ( $params ) use ( $user, $is_woopay ) {
if ( $is_woopay ) {
$params['email'] = $user->user_email;
}
return $params;
};
add_filter( 'wcpay_api_request_params', $apply_order_user_email, 20, 1 );
// Update the existing customer with the current order details.
$customer_data = WC_Payments_Customer_Service::map_customer_data( $order, new WC_Customer( $user->ID ) );
$this->customer_service->update_customer_for_user( $customer_id, $user, $customer_data );
}
/**
* Manages customer details held on WCPay server for WordPress user associated with an order.
*
* @param WC_Order $order WC Order object.
* @param array $options Additional options to apply.
*
* @return array First element is the new or updated WordPress user, the second element is the WCPay customer ID.
*/
protected function manage_customer_details_for_order( $order, $options = [] ) {
$user = $order->get_user();
if ( false === $user ) {
$user = wp_get_current_user();
}
// Determine the customer making the payment, create one if we don't have one already.
$customer_id = $this->customer_service->get_customer_id_by_user_id( $user->ID );
if ( null === $customer_id ) {
$customer_data = WC_Payments_Customer_Service::map_customer_data( $order, new WC_Customer( $user->ID ) );
// Create a new customer.
$customer_id = $this->customer_service->create_customer_for_user( $user, $customer_data );
} else {
// Update the customer with order data async.
$this->update_customer_with_order_data( $order, $customer_id, $this->is_in_test_mode(), $options['is_woopay'] ?? false );
}
return [ $user, $customer_id ];
}
/**
* Update the saved payment method information with checkout values, in a CRON job.
*
* @param string $payment_method The payment method to update.
* @param int $order_id WC order id.
* @param bool $is_test_mode Whether to run the CRON job in test mode.
*/
public function update_saved_payment_method( $payment_method, $order_id, $is_test_mode = false ) {
// Since this CRON job may have been created in test_mode, when the CRON job runs, it
// may lose the test_mode context. So, instead, we pass that context when creating
// the CRON job and apply the context here.
$apply_test_mode_context = function () use ( $is_test_mode ) {
return $is_test_mode;
};
add_filter( 'wcpay_test_mode', $apply_test_mode_context );
$order = wc_get_order( $order_id );
try {
$this->customer_service->update_payment_method_with_billing_details_from_order( $payment_method, $order );
} catch ( Exception $e ) {
// If updating the payment method fails, log the error message.
Logger::log( 'Error when updating saved payment method: ' . $e->getMessage() );
}
}
/**
* Process the payment for a given order.
*
* @param WC_Cart|null $cart Cart.
* @param WCPay\Payment_Information $payment_information Payment info.
* @param array $additional_api_parameters Any additional fields required for payment method to pass to API.
*
* @return array|null An array with result of payment and redirect URL, or nothing.
* @throws API_Exception Error processing the payment.
* @throws Add_Payment_Method_Exception When $0 order processing failed.
* @throws Intent_Authentication_Exception When the payment intent could not be authenticated.
*/
public function process_payment_for_order( $cart, $payment_information, $additional_api_parameters = [] ) {
$order = $payment_information->get_order();
$save_payment_method_to_store = $payment_information->should_save_payment_method_to_store();
$is_changing_payment_method_for_subscription = $payment_information->is_changing_payment_method_for_subscription();
$order_id = $order->get_id();
$amount = $order->get_total();
$metadata = $this->get_metadata_from_order( $order, $payment_information->get_payment_type() );
$customer_details_options = [
'is_woopay' => filter_var( $metadata['paid_on_woopay'] ?? false, FILTER_VALIDATE_BOOLEAN ),
];
list( $user, $customer_id ) = $this->manage_customer_details_for_order( $order, $customer_details_options );
// Update saved payment method async to include billing details, if missing.
if ( $payment_information->is_using_saved_payment_method() ) {
$this->action_scheduler_service->schedule_job(
time(),
self::UPDATE_SAVED_PAYMENT_METHOD,
[
'payment_method' => $payment_information->get_payment_method(),
'order_id' => $order->get_id(),
'is_test_mode' => $this->is_in_test_mode(),
]
);
}
$intent_failed = false;
$payment_needed = $amount > 0;
// Make sure that we attach the payment method and the customer ID to the order meta data.
$payment_method = $payment_information->get_payment_method();
$order->update_meta_data( '_payment_method_id', $payment_method );
$order->update_meta_data( '_stripe_customer_id', $customer_id );
$order->update_meta_data( '_wcpay_mode', $this->is_in_test_mode() ? 'test' : 'prod' );
// 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', ! $payment_needed && ! $save_payment_method_to_store ) ) {
$order->payment_complete();
if ( $payment_information->is_using_saved_payment_method() ) {
// We need to make sure the saved payment method is saved to the order so we can
// charge the payment method for a future payment.
$this->add_token_to_order( $order, $payment_information->get_payment_token() );
}
if ( $is_changing_payment_method_for_subscription && $payment_information->is_using_saved_payment_method() ) {
$payment_token = $payment_information->get_payment_token();
$note = sprintf(
WC_Payments_Utils::esc_interpolated_html(
/* translators: %1: the last 4 digit of the credit card */
__( 'Payment method is changed to: <strong>Credit card ending in %1$s</strong>.', 'woocommerce-payments' ),
[
'strong' => '<strong>',
]
),
$payment_token instanceof WC_Payment_Token_CC ? $payment_token->get_last4() : '----'
);
$order->add_order_note( $note );
do_action( 'woocommerce_payments_changed_subscription_payment_method', $order, $payment_token );
}
$order->set_payment_method_title( __( 'Credit / Debit Card', 'woocommerce-payments' ) );