-
Notifications
You must be signed in to change notification settings - Fork 210
/
Copy pathclass-wc-stripe-upe-payment-gateway.php
2072 lines (1784 loc) · 79.8 KB
/
class-wc-stripe-upe-payment-gateway.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
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class that handles UPE payment method.
*
* @extends WC_Gateway_Stripe
*
* @since 5.5.0
*/
class WC_Stripe_UPE_Payment_Gateway extends WC_Gateway_Stripe {
const ID = 'stripe';
/**
* Upe Available Methods
*
* @type WC_Stripe_UPE_Payment_Method[]
*/
const UPE_AVAILABLE_METHODS = [
WC_Stripe_UPE_Payment_Method_CC::class,
WC_Stripe_UPE_Payment_Method_Giropay::class,
WC_Stripe_UPE_Payment_Method_Eps::class,
WC_Stripe_UPE_Payment_Method_Bancontact::class,
WC_Stripe_UPE_Payment_Method_Boleto::class,
WC_Stripe_UPE_Payment_Method_Ideal::class,
WC_Stripe_UPE_Payment_Method_Oxxo::class,
WC_Stripe_UPE_Payment_Method_Sepa::class,
WC_Stripe_UPE_Payment_Method_P24::class,
WC_Stripe_UPE_Payment_Method_Sofort::class,
WC_Stripe_UPE_Payment_Method_Link::class,
];
/**
* Stripe intents that are treated as successfully created.
*
* @type array
*/
const SUCCESSFUL_INTENT_STATUS = [ 'succeeded', 'requires_capture', 'processing' ];
/**
* Notices (array)
*
* @var array
*/
public $notices = [];
/**
* Is test mode active?
*
* @var bool
*/
public $testmode;
/**
* Alternate credit card statement name
*
* @var bool
*/
public $statement_descriptor;
/**
* Are saved cards enabled
*
* @var bool
*/
public $saved_cards;
/**
* API access secret key
*
* @var string
*/
public $secret_key;
/**
* Api access publishable key
*
* @var string
*/
public $publishable_key;
/**
* Instance of WC_Stripe_Intent_Controller.
*
* @var WC_Stripe_Intent_Controller
*/
public $intent_controller;
/**
* Array mapping payment method string IDs to classes
*
* @var WC_Stripe_UPE_Payment_Method[]
*/
public $payment_methods = [];
/**
* Constructor
*/
public function __construct() {
$this->id = self::ID;
$this->method_title = __( 'Stripe', 'woocommerce-gateway-stripe' );
/* translators: link */
$this->method_description = __( 'Accept debit and credit cards in 135+ currencies, methods such as SEPA, and one-touch checkout with Apple Pay.', 'woocommerce-gateway-stripe' );
$this->has_fields = true;
$this->supports = [
'products',
'refunds',
'tokenization',
'add_payment_method',
];
$this->payment_methods = [];
foreach ( self::UPE_AVAILABLE_METHODS as $payment_method_class ) {
$payment_method = new $payment_method_class();
$this->payment_methods[ $payment_method->get_id() ] = $payment_method;
}
$this->intent_controller = new WC_Stripe_Intent_Controller();
// Load the form fields.
$this->init_form_fields();
// Load the settings.
$this->init_settings();
// Check if subscriptions are enabled and add support for them.
$this->maybe_init_subscriptions();
// Check if pre-orders are enabled and add support for them.
$this->maybe_init_pre_orders();
$main_settings = get_option( 'woocommerce_stripe_settings' );
$this->title = ! empty( $this->get_option( 'title_upe' ) ) ? $this->get_option( 'title_upe' ) : $this->form_fields['title_upe']['default'];
$this->description = '';
$this->enabled = $this->get_option( 'enabled' );
$this->saved_cards = 'yes' === $this->get_option( 'saved_cards' );
$this->testmode = ! empty( $main_settings['testmode'] ) && 'yes' === $main_settings['testmode'];
$this->publishable_key = ! empty( $main_settings['publishable_key'] ) ? $main_settings['publishable_key'] : '';
$this->secret_key = ! empty( $main_settings['secret_key'] ) ? $main_settings['secret_key'] : '';
$this->statement_descriptor = ! empty( $main_settings['statement_descriptor'] ) ? $main_settings['statement_descriptor'] : '';
$enabled_at_checkout_payment_methods = $this->get_upe_enabled_at_checkout_payment_method_ids();
if ( count( $enabled_at_checkout_payment_methods ) === 1 ) {
$this->title = $this->payment_methods[ $enabled_at_checkout_payment_methods[0] ]->get_title();
}
// When feature flags are enabled, title shows the count of enabled payment methods in settings page only.
if ( WC_Stripe_Feature_Flags::is_upe_checkout_enabled() && WC_Stripe_Feature_Flags::is_upe_preview_enabled() && isset( $_GET['page'] ) && 'wc-settings' === $_GET['page'] ) {
$enabled_payment_methods_count = count( $this->get_upe_enabled_payment_method_ids() );
$this->title = $enabled_payment_methods_count ?
/* translators: $1. Count of enabled payment methods. */
sprintf( _n( '%d payment method', '%d payment methods', $enabled_payment_methods_count, 'woocommerce-gateway-stripe' ), $enabled_payment_methods_count )
: $this->method_title;
}
if ( $this->testmode ) {
$this->publishable_key = ! empty( $main_settings['test_publishable_key'] ) ? $main_settings['test_publishable_key'] : '';
$this->secret_key = ! empty( $main_settings['test_secret_key'] ) ? $main_settings['test_secret_key'] : '';
}
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, [ $this, 'process_admin_options' ] );
add_action( 'wp_footer', [ $this, 'payment_scripts' ] );
// Needed for 3DS compatibility when checking out with PRBs..
// Copied from WC_Gateway_Stripe::__construct().
add_filter( 'woocommerce_payment_successful_result', [ $this, 'modify_successful_payment_result' ], 99999, 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' ] );
}
/**
* 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;
}
/**
* Hides refund through stripe when payment method does not allow refund
*
* @param WC_Order $order
*
* @return array|bool
*/
public function can_refund_order( $order ) {
$upe_payment_type = $order->get_meta( '_stripe_upe_payment_type' );
if ( ! $upe_payment_type ) {
return true;
}
return $this->payment_methods[ $upe_payment_type ]->can_refund_via_stripe();
}
/**
* Return the gateway icon - None for UPE.
*/
public function get_icon() {
return apply_filters( 'woocommerce_gateway_icon', null, $this->id );
}
/**
* Initialize Gateway Settings Form Fields.
*/
public function init_form_fields() {
$this->form_fields = require WC_STRIPE_PLUGIN_PATH . '/includes/admin/stripe-settings.php';
unset( $this->form_fields['inline_cc_form'] );
unset( $this->form_fields['title'] );
unset( $this->form_fields['description'] );
}
/**
* Outputs scripts used for stripe payment
*/
public function payment_scripts() {
if (
! is_product()
&& ! WC_Stripe_Helper::has_cart_or_checkout_on_current_page()
&& ! parent::is_valid_pay_for_order_endpoint()
&& ! is_add_payment_method_page() ) {
return;
}
if ( is_product() && ! WC_Stripe_Helper::should_load_scripts_on_product_page() ) {
return;
}
if ( is_cart() && ! WC_Stripe_Helper::should_load_scripts_on_cart_page() ) {
return;
}
$asset_path = WC_STRIPE_PLUGIN_PATH . '/build/checkout_upe.asset.php';
$version = WC_STRIPE_VERSION;
$dependencies = [];
if ( file_exists( $asset_path ) ) {
$asset = require $asset_path;
$version = is_array( $asset ) && isset( $asset['version'] )
? $asset['version']
: $version;
$dependencies = is_array( $asset ) && isset( $asset['dependencies'] )
? $asset['dependencies']
: $dependencies;
}
wp_register_script(
'stripe',
'https://js.stripe.com/v3/',
[],
'3.0',
true
);
wp_register_script(
'wc-stripe-upe-classic',
WC_STRIPE_PLUGIN_URL . '/build/upe_classic.js',
array_merge( [ 'stripe', 'wc-checkout' ], $dependencies ),
$version,
true
);
wp_set_script_translations(
'wc-stripe-upe-classic',
'woocommerce-gateway-stripe'
);
wp_localize_script(
'wc-stripe-upe-classic',
'wc_stripe_upe_params',
apply_filters( 'wc_stripe_upe_params', $this->javascript_params() )
);
wp_register_style(
'wc-stripe-upe-classic',
WC_STRIPE_PLUGIN_URL . '/build/upe_classic.css',
[],
$version
);
wp_enqueue_script( 'wc-stripe-upe-classic' );
wp_enqueue_style( 'wc-stripe-upe-classic' );
wp_register_style( 'stripelink_styles', plugins_url( 'assets/css/stripe-link.css', WC_STRIPE_MAIN_FILE ), [], WC_STRIPE_VERSION );
wp_enqueue_style( 'stripelink_styles' );
}
/**
* Returns the JavaScript configuration object used on the product, cart, and checkout pages.
*
* @return array The configuration object to be loaded to JS.
*/
public function javascript_params() {
global $wp;
$is_change_payment_method = $this->is_changing_payment_method_for_subscription();
$stripe_params = [
'gatewayId' => self::ID,
'title' => $this->title,
'isUPEEnabled' => true,
'key' => $this->publishable_key,
'locale' => WC_Stripe_Helper::convert_wc_locale_to_stripe_locale( get_locale() ),
];
$enabled_billing_fields = [];
foreach ( WC()->checkout()->get_checkout_fields( 'billing' ) as $billing_field => $billing_field_options ) {
if ( ! isset( $billing_field_options['enabled'] ) || $billing_field_options['enabled'] ) {
$enabled_billing_fields[] = $billing_field;
}
}
$stripe_params['isCheckout'] = ( is_checkout() || has_block( 'woocommerce/checkout' ) ) && empty( $_GET['pay_for_order'] ); // wpcs: csrf ok.
$stripe_params['return_url'] = $this->get_stripe_return_url();
$stripe_params['ajax_url'] = WC_AJAX::get_endpoint( '%%endpoint%%' );
$stripe_params['theme_name'] = get_option( 'stylesheet' );
$stripe_params['testMode'] = $this->testmode;
$stripe_params['createPaymentIntentNonce'] = wp_create_nonce( 'wc_stripe_create_payment_intent_nonce' );
$stripe_params['updatePaymentIntentNonce'] = wp_create_nonce( 'wc_stripe_update_payment_intent_nonce' );
$stripe_params['createSetupIntentNonce'] = wp_create_nonce( 'wc_stripe_create_setup_intent_nonce' );
$stripe_params['createAndConfirmSetupIntentNonce'] = wp_create_nonce( 'wc_stripe_create_and_confirm_setup_intent_nonce' );
$stripe_params['updateFailedOrderNonce'] = wp_create_nonce( 'wc_stripe_update_failed_order_nonce' );
$stripe_params['paymentMethodsConfig'] = $this->get_enabled_payment_method_config();
$stripe_params['genericErrorMessage'] = __( 'There was a problem processing the payment. Please check your email inbox and refresh the page to try again.', 'woocommerce-gateway-stripe' );
$stripe_params['accountDescriptor'] = $this->statement_descriptor;
$stripe_params['addPaymentReturnURL'] = wc_get_account_endpoint_url( 'payment-methods' );
$stripe_params['enabledBillingFields'] = $enabled_billing_fields;
$cart_total = ( WC()->cart ? WC()->cart->get_total( '' ) : 0 );
$currency = get_woocommerce_currency();
$stripe_params['cartTotal'] = WC_Stripe_Helper::get_stripe_amount( $cart_total, strtolower( $currency ) );
$stripe_params['currency'] = $currency;
if ( parent::is_valid_pay_for_order_endpoint() || $is_change_payment_method ) {
if ( $this->is_subscriptions_enabled() && $is_change_payment_method ) {
$stripe_params['isChangingPayment'] = true;
$stripe_params['addPaymentReturnURL'] = wp_sanitize_redirect( esc_url_raw( home_url( add_query_arg( [] ) ) ) );
if ( $this->is_setup_intent_success_creation_redirection() && isset( $_GET['_wpnonce'] ) && wp_verify_nonce( wc_clean( wp_unslash( $_GET['_wpnonce'] ) ) ) ) {
$setup_intent_id = isset( $_GET['setup_intent'] ) ? wc_clean( wp_unslash( $_GET['setup_intent'] ) ) : '';
$token = $this->create_token_from_setup_intent( $setup_intent_id, wp_get_current_user() );
$stripe_params['newTokenFormId'] = '#wc-' . $token->get_gateway_id() . '-payment-token-' . $token->get_id();
}
return $stripe_params;
}
$order_id = absint( get_query_var( 'order-pay' ) );
$stripe_params['orderId'] = $order_id;
$stripe_params['isOrderPay'] = true;
$order = wc_get_order( $order_id );
if ( is_a( $order, 'WC_Order' ) ) {
$order_currency = $order->get_currency();
$stripe_params['currency'] = $order_currency;
$stripe_params['cartTotal'] = WC_Stripe_Helper::get_stripe_amount( $order->get_total(), $order_currency );
$stripe_params['orderReturnURL'] = esc_url_raw(
add_query_arg(
[
'order_id' => $order_id,
'wc_payment_method' => self::ID,
'_wpnonce' => wp_create_nonce( 'wc_stripe_process_redirect_order_nonce' ),
],
$this->get_return_url( $order )
)
);
}
}
// Pre-orders and free trial subscriptions don't require payments.
$stripe_params['isPaymentNeeded'] = $this->is_payment_needed( isset( $order_id ) ? $order_id : null );
return array_merge( $stripe_params, WC_Stripe_Helper::get_localized_messages() );
}
/**
* Gets payment method settings to pass to client scripts
*
* @return array
*/
private function get_enabled_payment_method_config() {
$settings = [];
$enabled_payment_methods = $this->get_upe_enabled_at_checkout_payment_method_ids();
foreach ( $enabled_payment_methods as $payment_method ) {
$settings[ $payment_method ] = [
'isReusable' => $this->payment_methods[ $payment_method ]->is_reusable(),
'title' => $this->payment_methods[ $payment_method ]->get_title(),
'testingInstructions' => $this->payment_methods[ $payment_method ]->get_testing_instructions(),
'showSaveOption' => $this->payment_methods[ $payment_method ]->should_show_save_option(),
];
}
return $settings;
}
/**
* Returns the list of enabled payment method types for UPE.
*
* @return string[]
*/
public function get_upe_enabled_payment_method_ids() {
return $this->get_option( 'upe_checkout_experience_accepted_payments', [ 'card' ] );
}
/**
* Returns the list of enabled payment method types that will function with the current checkout.
*
* @param int|null $order_id
* @return string[]
*/
public function get_upe_enabled_at_checkout_payment_method_ids( $order_id = null ) {
$is_automatic_capture_enabled = $this->is_automatic_capture_enabled();
$available_method_ids = [];
foreach ( $this->get_upe_enabled_payment_method_ids() as $payment_method_id ) {
if ( ! isset( $this->payment_methods[ $payment_method_id ] ) ) {
continue;
}
$method = $this->payment_methods[ $payment_method_id ];
if ( $method->is_enabled_at_checkout( $order_id ) === false ) {
continue;
}
if ( ! $is_automatic_capture_enabled && $method->requires_automatic_capture() ) {
continue;
}
$available_method_ids[] = $payment_method_id;
}
return $available_method_ids;
}
/**
* Returns the list of available payment method types for UPE.
* See https://stripe.com/docs/stripe-js/payment-element#web-create-payment-intent for a complete list.
*
* @return string[]
*/
public function get_upe_available_payment_methods() {
$available_payment_methods = [];
foreach ( $this->payment_methods as $payment_method ) {
if ( is_callable( [ $payment_method, 'is_available_for_account_country' ] ) && ! $payment_method->is_available_for_account_country() ) {
continue;
}
$available_payment_methods[] = $payment_method->get_id();
}
return $available_payment_methods;
}
/**
* Renders the UPE input fields needed to get the user's payment information on the checkout page
*/
public function payment_fields() {
try {
$display_tokenization = $this->supports( 'tokenization' ) && is_checkout();
// Output the form HTML.
?>
<?php if ( ! empty( $this->get_description() ) ) : ?>
<p><?php echo wp_kses_post( $this->get_description() ); ?></p>
<?php endif; ?>
<?php if ( $this->testmode ) : ?>
<p class="testmode-info">
<?php
printf(
/* translators: 1) HTML strong open tag 2) HTML strong closing tag 3) HTML anchor open tag 2) HTML anchor closing tag */
esc_html__( '%1$sTest mode:%2$s use the test VISA card 4242424242424242 with any expiry date and CVC. Other payment methods may redirect to a Stripe test page to authorize payment. More test card numbers are listed %3$shere%4$s.', 'woocommerce-gateway-stripe' ),
'<strong>',
'</strong>',
'<a href="https://stripe.com/docs/testing" target="_blank">',
'</a>'
);
?>
</p>
<?php endif; ?>
<?php
if ( $display_tokenization ) {
$this->tokenization_script();
$this->saved_payment_methods();
}
?>
<fieldset id="wc-stripe-upe-form" class="wc-upe-form wc-payment-form">
<div class="wc-stripe-upe-element"></div>
<div id="wc-stripe-upe-errors" role="alert"></div>
<input id="wc-stripe-payment-method-upe" type="hidden" name="wc-stripe-payment-method-upe" />
<input id="wc_stripe_selected_upe_payment_type" type="hidden" name="wc_stripe_selected_upe_payment_type" />
<input type="hidden" class="wc-stripe-is-deferred-intent" name="wc-stripe-is-deferred-intent" value="1" />
</fieldset>
<?php
$methods_enabled_for_saved_payments = array_filter( $this->get_upe_enabled_payment_method_ids(), [ $this, 'is_enabled_for_saved_payments' ] );
if ( $this->is_saved_cards_enabled() && ! empty( $methods_enabled_for_saved_payments ) ) {
$force_save_payment = ( $display_tokenization && ! apply_filters( 'wc_stripe_display_save_payment_method_checkbox', $display_tokenization ) ) || is_add_payment_method_page();
if ( is_user_logged_in() ) {
$this->save_payment_method_checkbox( $force_save_payment );
}
}
} catch ( Exception $e ) {
// Output the error message.
WC_Stripe_Logger::log( 'Error: ' . $e->getMessage() );
?>
<div>
<?php
echo esc_html__( 'An error was encountered when preparing the payment form. Please try again later.', 'woocommerce-gateway-stripe' );
?>
</div>
<?php
}
}
/**
* Process the payment for a given order.
*
* @param int $order_id Reference.
* @param bool $retry Should we retry on fail.
* @param bool $force_save_source Force save the payment source.
* @param mix $previous_error Any error message from previous request.
* @param bool $use_order_source Whether to use the source, which should already be attached to the order.
*
* @return array|null An array with result of payment and redirect URL, or nothing.
*/
public function process_payment( $order_id, $retry = true, $force_save_source = false, $previous_error = false, $use_order_source = false ) {
// Flag for using a deferred intent. To be removed.
if ( ! empty( $_POST['wc-stripe-is-deferred-intent'] ) ) {
return $this->process_payment_with_deferred_intent( $order_id );
}
if ( $this->maybe_change_subscription_payment_method( $order_id ) ) {
return $this->process_change_subscription_payment_method( $order_id );
}
if ( $this->is_using_saved_payment_method() ) {
return $this->process_payment_with_saved_payment_method( $order_id );
}
$payment_intent_id = isset( $_POST['wc_payment_intent_id'] ) ? wc_clean( wp_unslash( $_POST['wc_payment_intent_id'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing
$order = wc_get_order( $order_id );
$payment_needed = $this->is_payment_needed( $order_id );
$save_payment_method = $this->has_subscription( $order_id ) || ! empty( $_POST[ 'wc-' . self::ID . '-new-payment-method' ] ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
$selected_upe_payment_type = ! empty( $_POST['wc_stripe_selected_upe_payment_type'] ) ? wc_clean( wp_unslash( $_POST['wc_stripe_selected_upe_payment_type'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing
$statement_descriptor = ! empty( $this->get_option( 'statement_descriptor' ) ) ? str_replace( "'", '', $this->get_option( 'statement_descriptor' ) ) : '';
$short_statement_descriptor = ! empty( $this->get_option( 'short_statement_descriptor' ) ) ? str_replace( "'", '', $this->get_option( 'short_statement_descriptor' ) ) : '';
$is_short_statement_descriptor_enabled = ! empty( $this->get_option( 'is_short_statement_descriptor_enabled' ) ) && 'yes' === $this->get_option( 'is_short_statement_descriptor_enabled' );
$descriptor = null;
if ( 'card' === $selected_upe_payment_type && $is_short_statement_descriptor_enabled && ! ( empty( $short_statement_descriptor ) && empty( $statement_descriptor ) ) ) {
// Use the shortened statement descriptor for card transactions only
$descriptor = WC_Stripe_Helper::get_dynamic_statement_descriptor( $short_statement_descriptor, $order, $statement_descriptor );
} elseif ( ! empty( $statement_descriptor ) ) {
$descriptor = WC_Stripe_Helper::clean_statement_descriptor( $statement_descriptor );
}
if ( $payment_intent_id ) {
if ( $payment_needed ) {
$amount = $order->get_total();
$currency = $order->get_currency();
$converted_amount = WC_Stripe_Helper::get_stripe_amount( $amount, $currency );
$request = [
'amount' => $converted_amount,
'currency' => $currency,
'statement_descriptor' => $descriptor,
/* translators: 1) blog name 2) order number */
'description' => sprintf( __( '%1$s - Order %2$s', 'woocommerce-gateway-stripe' ), wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ), $order->get_order_number() ),
];
$customer = $this->get_stripe_customer_from_order( $order );
// Update customer or create customer if customer does not exist.
if ( ! $customer->get_id() ) {
$request['customer'] = $customer->create_customer();
} else {
$request['customer'] = $customer->update_customer();
}
if ( '' !== $selected_upe_payment_type ) {
// Only update the payment_method_types if we have a reference to the payment type the customer selected.
$request['payment_method_types'] = [ $selected_upe_payment_type ];
if ( WC_Stripe_UPE_Payment_Method_CC::STRIPE_ID === $selected_upe_payment_type ) {
if ( in_array(
WC_Stripe_UPE_Payment_Method_Link::STRIPE_ID,
$this->get_upe_enabled_payment_method_ids(),
true
) ) {
$request['payment_method_types'] = [
WC_Stripe_UPE_Payment_Method_CC::STRIPE_ID,
WC_Stripe_UPE_Payment_Method_Link::STRIPE_ID,
];
}
}
$this->set_payment_method_title_for_order( $order, $selected_upe_payment_type );
if ( ! $this->payment_methods[ $selected_upe_payment_type ]->is_allowed_on_country( $order->get_billing_country() ) ) {
throw new \Exception( __( 'This payment method is not available on the selected country', 'woocommerce-gateway-stripe' ) );
}
}
if ( $save_payment_method ) {
$request['setup_future_usage'] = 'off_session';
}
$request['metadata'] = $this->get_metadata_from_order( $order );
// If order requires shipping, add the shipping address details to the payment intent request.
if ( method_exists( $order, 'get_shipping_postcode' ) && ! empty( $order->get_shipping_postcode() ) ) {
$request['shipping'] = $this->get_address_data_for_payment_request( $order );
}
// Run the necessary filter to make sure mandate information is added when it's required.
$request = apply_filters(
'wc_stripe_generate_create_intent_request',
$request,
$order,
null // $prepared_source parameter is not necessary for adding mandate information.
);
WC_Stripe_Helper::add_payment_intent_to_order( $payment_intent_id, $order );
$order->update_status( 'pending', __( 'Awaiting payment.', 'woocommerce-gateway-stripe' ) );
$order->update_meta_data( '_stripe_upe_payment_type', $selected_upe_payment_type );
// TODO: This is a stop-gap to fix a critical issue, see
// https://github.com/woocommerce/woocommerce-gateway-stripe/issues/2536. It would
// be better if we removed the need for additional meta data in favor of refactoring
// this part of the payment processing.
$order->update_meta_data( '_stripe_upe_waiting_for_redirect', true );
$order->save();
$this->stripe_request(
"payment_intents/$payment_intent_id",
$request,
$order
);
}
} else {
return parent::process_payment( $order_id, $retry, $force_save_source, $previous_error, $use_order_source );
}
return [
'result' => 'success',
'payment_needed' => $payment_needed,
'order_id' => $order_id,
'redirect_url' => wp_sanitize_redirect(
esc_url_raw(
add_query_arg(
[
'order_id' => $order_id,
'wc_payment_method' => self::ID,
'_wpnonce' => wp_create_nonce( 'wc_stripe_process_redirect_order_nonce' ),
'save_payment_method' => $save_payment_method ? 'yes' : 'no',
],
$this->get_return_url( $order )
)
)
),
];
}
/**
* Process the payment for an order using a deferred intent.
*
* @param int $order_id WC Order ID to be paid for.
*
* @return array An array with the result of the payment processing, and a redirect URL on success.
*/
private function process_payment_with_deferred_intent( int $order_id ) {
$order = wc_get_order( $order_id );
try {
$payment_information = $this->prepare_payment_information_from_request( $order );
$this->validate_selected_payment_method_type( $payment_information, $order->get_billing_country() );
$payment_needed = $this->is_payment_needed( $order->get_id() );
$payment_method_id = $payment_information['payment_method'];
$selected_payment_type = $payment_information['selected_payment_type'];
// Make sure that we attach the payment method and the customer ID to the order meta data.
$this->set_payment_method_id_for_order( $order, $payment_method_id );
$this->set_customer_id_for_order( $order, $payment_information['customer'] );
// Only update the payment_type if we have a reference to the payment type the customer selected.
if ( '' !== $selected_payment_type ) {
$this->set_selected_payment_type_for_order( $order, $selected_payment_type );
}
// Retrieve the payment method object from Stripe.
$payment_method = WC_Stripe_API::get_payment_method( $payment_method_id );
// Throw an exception when the payment method is a prepaid card and it's disallowed.
$this->maybe_disallow_prepaid_card( $payment_method );
if ( $payment_needed ) {
// Throw an exception if the minimum order amount isn't met.
$this->validate_minimum_order_amount( $order );
// Create a payment intent, or update an existing one associated with the order.
$payment_intent = $this->process_payment_intent_for_order( $order, $payment_information );
// Handle saving the payment method in the store.
// It's already attached to the Stripe customer at this point.
if ( $payment_information['save_payment_method_to_store'] ) {
$this->handle_saving_payment_method(
$order,
$payment_information['payment_method'],
$selected_payment_type
);
}
// Use the last charge within the intent to proceed.
$charge = end( $payment_intent->charges->data );
// Only process the response if it contains a charge object. Intents with no charge require further action like 3DS and will be processed later.
if ( $charge ) {
$this->process_response( $charge, $order );
}
// Set the selected UPE payment method type title in the WC order.
$this->set_payment_method_title_for_order( $order, $selected_payment_type );
} else {
// It's a setup intent. To be handled.
return [ 'result' => 'failure' ];
}
$redirect = $this->get_return_url( $order );
/**
* Depending on the payment method used to process the payment, we may need to redirect the user to a URL for further processing.
*
* - Voucher payments (Boleto or Oxxo) respond with a hash URL so the client JS code can recognize the response, pull out the necessary args and handle the displaying of the voucher.
* - Other payment methods like Giropay, iDEAL etc require a redirect to a URL provided by Stripe.
* - 3DS Card payments return a hash URL so the client JS code can recognize the response, pull out the necessary PI args and display the 3DS confirmation modal.
*/
if ( in_array( $payment_intent->status, [ 'requires_confirmation', 'requires_action' ], true ) ) {
if ( isset( $payment_intent->payment_method_types ) && count( array_intersect( [ 'boleto', 'oxxo' ], $payment_intent->payment_method_types ) ) !== 0 ) {
// For Voucher payment method types (Boleto/Oxxo), redirect the customer to a URL hash formatted #wc-stripe-voucher-{order_id}:{payment_method_type}:{client_secret}:{redirect_url} to confirm the intent which also displays the voucher.
$redirect = sprintf(
'#wc-stripe-voucher-%s:%s:%s:%s',
$order_id,
$payment_information['selected_payment_type'],
$payment_intent->client_secret,
rawurlencode( $redirect )
);
} elseif ( isset( $payment_intent->next_action->type ) && 'redirect_to_url' === $payment_intent->next_action->type && ! empty( $payment_intent->next_action->redirect_to_url->url ) ) {
$redirect = $payment_intent->next_action->redirect_to_url->url;
} else {
$redirect = sprintf(
'#wc-stripe-confirm-%s:%s:%s:%s',
$payment_needed ? 'pi' : 'si',
$order_id,
$payment_intent->client_secret,
wp_create_nonce( 'wc_stripe_update_order_status_nonce' )
);
}
}
return [
'result' => 'success',
'redirect' => $redirect,
];
} catch ( WC_Stripe_Exception $e ) {
$shopper_error_message = sprintf(
/* translators: localized exception message */
__( 'There was an error processing the payment: %s', 'woocommerce-gateway-stripe' ),
$e->getLocalizedMessage()
);
wc_add_notice( $shopper_error_message, 'error' );
WC_Stripe_Logger::log( 'Error: ' . $e->getMessage() );
do_action( 'wc_gateway_stripe_process_payment_error', $e, $order );
$order->update_status(
'failed',
/* translators: localized exception message */
sprintf( __( 'Payment failed: %s', 'woocommerce-gateway-stripe' ), $e->getLocalizedMessage() )
);
return [
'result' => 'failure',
'redirect' => '',
];
}
}
/**
* Process payment using saved payment method.
* This follows WC_Gateway_Stripe::process_payment,
* but uses Payment Methods instead of Sources.
*
* @param int $order_id The order ID being processed.
* @param bool $can_retry Should we retry on fail.
*/
public function process_payment_with_saved_payment_method( $order_id, $can_retry = true ) {
try {
$order = wc_get_order( $order_id );
if ( $this->maybe_process_pre_orders( $order_id ) ) {
return $this->process_pre_order( $order_id );
}
$token = WC_Stripe_Payment_Tokens::get_token_from_request( $_POST );
$payment_method = $this->stripe_request( 'payment_methods/' . $token->get_token(), [], null, 'GET' );
$prepared_payment_method = $this->prepare_payment_method( $payment_method );
$this->maybe_disallow_prepaid_card( $payment_method );
$this->save_payment_method_to_order( $order, $prepared_payment_method );
WC_Stripe_Logger::log( "Info: Begin processing payment with saved payment method for order $order_id for the amount of {$order->get_total()}" );
// If we are retrying request, maybe intent has been saved to order.
$intent = $this->get_intent_from_order( $order );
$enabled_payment_methods = array_filter( $this->get_upe_enabled_payment_method_ids(), [ $this, 'is_enabled_at_checkout' ] );
$payment_needed = $this->is_payment_needed( $order_id );
if ( $payment_needed ) {
// This will throw exception if not valid.
$this->validate_minimum_order_amount( $order );
$request_details = $this->generate_payment_request( $order, $prepared_payment_method );
$endpoint = false !== $intent ? "payment_intents/$intent->id" : 'payment_intents';
$request = [
'payment_method' => $payment_method->id,
'payment_method_types' => array_values( $enabled_payment_methods ),
'amount' => WC_Stripe_Helper::get_stripe_amount( $order->get_total() ),
'currency' => strtolower( $order->get_currency() ),
'description' => $request_details['description'],
'metadata' => $request_details['metadata'],
'customer' => $payment_method->customer,
];
if ( false === $intent ) {
$request['capture_method'] = ( 'true' === $request_details['capture'] ) ? 'automatic' : 'manual';
$request['confirm'] = 'true';
}
// If order requires shipping, add the shipping address details to the payment intent request.
if ( method_exists( $order, 'get_shipping_postcode' ) && ! empty( $order->get_shipping_postcode() ) ) {
$request['shipping'] = $this->get_address_data_for_payment_request( $order );
}
if ( $this->has_subscription( $order_id ) ) {
$request['setup_future_usage'] = 'off_session';
}
// Run the necessary filter to make sure mandate information is added when it's required.
$request = apply_filters(
'wc_stripe_generate_create_intent_request',
$request,
$order,
null // $prepared_source parameter is not necessary for adding mandate information.
);
$intent = $this->stripe_request(
$endpoint,
$request,
$order
);
} else {
$endpoint = false !== $intent ? "setup_intents/$intent->id" : 'setup_intents';
$request = [
'payment_method' => $payment_method->id,
'payment_method_types' => array_values( $enabled_payment_methods ),
'customer' => $payment_method->customer,
];
if ( false === $intent ) {
$request['confirm'] = 'true';
// SEPA setup intents require mandate data.
if ( in_array( 'sepa_debit', array_values( $enabled_payment_methods ), true ) ) {
$request['mandate_data'] = [
'customer_acceptance' => [
'type' => 'online',
'online' => [
'ip_address' => WC_Geolocation::get_ip_address(),
'user_agent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '', // @codingStandardsIgnoreLine
],
],
];
}
}
$intent = $this->stripe_request( $endpoint, $request );
}
$this->save_intent_to_order( $order, $intent );
if ( ! empty( $intent->error ) ) {
$this->maybe_remove_non_existent_customer( $intent->error, $order );
// We want to retry (apparently).
if ( $this->is_retryable_error( $intent->error ) ) {
return $this->retry_after_error( $intent, $order, $can_retry );
}
$this->throw_localized_message( $intent, $order );
}
if ( 'requires_action' === $intent->status || 'requires_confirmation' === $intent->status ) {
if ( isset( $intent->next_action->type ) && 'redirect_to_url' === $intent->next_action->type && ! empty( $intent->next_action->redirect_to_url->url ) ) {
return [
'result' => 'success',
'redirect' => $intent->next_action->redirect_to_url->url,
];
} else {
return [
'result' => 'success',
// Include a new nonce for update_order_status to ensure the update order
// status call works when a guest user creates an account during checkout.
'redirect' => sprintf(
'#wc-stripe-confirm-%s:%s:%s:%s',
$payment_needed ? 'pi' : 'si',
$order_id,
$intent->client_secret,
wp_create_nonce( 'wc_stripe_update_order_status_nonce' )
),
];
}
}
list( $payment_method_type, $payment_method_details ) = $this->get_payment_method_data_from_intent( $intent );
if ( $payment_needed ) {
// Use the last charge within the intent to proceed.
$this->process_response( end( $intent->charges->data ), $order );
} else {
$order->payment_complete();
}
$this->set_payment_method_title_for_order( $order, $payment_method_type );
// Remove cart.
if ( isset( WC()->cart ) ) {
WC()->cart->empty_cart();
}
// Return thank you page redirect.
return [
'result' => 'success',
'redirect' => $this->get_return_url( $order ),
];
} catch ( WC_Stripe_Exception $e ) {
wc_add_notice( $e->getLocalizedMessage(), 'error' );
WC_Stripe_Logger::log( 'Error: ' . $e->getMessage() );
do_action( 'wc_gateway_stripe_process_payment_error', $e, $order );
/* translators: error message */
$order->update_status( 'failed' );
return [
'result' => 'fail',
'redirect' => '',
];
}
}
/**
* Check for a UPE redirect payment method on order received page or setup intent on payment methods page.
*
* @since 5.6.0
* @version 5.6.0
*/
public function maybe_process_upe_redirect() {
if ( $this->is_payment_methods_page() || $this->is_changing_payment_method_for_subscription() ) {
if ( $this->is_setup_intent_success_creation_redirection() ) {
if ( isset( $_GET['redirect_status'] ) && 'succeeded' === $_GET['redirect_status'] ) {
$user_id = wp_get_current_user()->ID;
$customer = new WC_Stripe_Customer( $user_id );
$customer->clear_cache();
wc_add_notice( __( 'Payment method successfully added.', 'woocommerce-gateway-stripe' ) );
// The newly created payment method does not inherit the customers' billing info, so we manually
// trigger an update; in case of failure we log the error and continue because the payment method's
// billing info will be updated when the customer makes a purchase anyway.
try {
$setup_intent_id = isset( $_GET['setup_intent'] ) ? wc_clean( wp_unslash( $_GET['setup_intent'] ) ) : '';
$setup_intent = $this->stripe_request( 'setup_intents/' . $setup_intent_id, [], null, 'GET' );
$customer_data = WC_Stripe_Customer::map_customer_data( null, new WC_Customer( $user_id ) );
$payment_method_object = $this->stripe_request(
'payment_methods/' . $setup_intent->payment_method,
[
'billing_details' => [
'name' => $customer_data['name'],
'email' => $customer_data['email'],
'phone' => $customer_data['phone'],
'address' => $customer_data['address'],
],
]
);
do_action( 'woocommerce_stripe_add_payment_method', $user_id, $payment_method_object );