-
Notifications
You must be signed in to change notification settings - Fork 198
/
abstract-wc-stripe-payment-gateway.php
2021 lines (1723 loc) · 71.1 KB
/
abstract-wc-stripe-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;
}
// phpcs:disable WordPress.Files.FileName
/**
* Abstract class that will be inherited by all payment methods.
*
* @extends WC_Payment_Gateway_CC
*
* @since 4.0.0
*/
abstract class WC_Stripe_Payment_Gateway extends WC_Payment_Gateway_CC {
use WC_Stripe_Subscriptions_Trait;
use WC_Stripe_Pre_Orders_Trait;
/**
* The delay between retries.
*
* @var int
*/
protected $retry_interval = 1;
/**
* Fallback method to be inherited by all payment methods. Stripe UPE will override it.
*
* @return string[]
*/
public function get_upe_enabled_payment_method_ids() {
return [ 'card' ];
}
/**
* Fallback method to be inherited by all payment methods. Stripe UPE will override it.
*
* @return string[]
*/
public function get_upe_available_payment_methods() {
return [ 'card' ];
}
/**
* Checks whether the gateway is enabled.
*
* @return bool The result.
*/
public function is_enabled() {
return 'yes' === $this->get_option( 'enabled' );
}
/**
* Disables gateway.
*/
public function disable() {
$this->update_option( 'enabled', 'no' );
}
/**
* Enables gateway.
*/
public function enable() {
$this->update_option( 'enabled', 'yes' );
}
/**
* Displays the admin settings webhook description.
*
* @since 4.1.0
* @version 5.0.0
* @return mixed
*/
public function display_admin_settings_webhook_description() {
/* translators: 1) webhook url */
$description = sprintf( __( 'You must add the following webhook endpoint <strong style="background-color:#ddd;"> %s </strong> to your <a href="https://dashboard.stripe.com/account/webhooks" target="_blank">Stripe account settings</a> (if there isn\'t one already enabled). This will enable you to receive notifications on the charge statuses.', 'woocommerce-gateway-stripe' ), WC_Stripe_Helper::get_webhook_url() );
$webhook_status = WC_Stripe_Webhook_State::get_webhook_status_message();
return $description . '<br><br>' . $webhook_status;
}
/**
* Prints the admin options for the gateway.
* Inserts an empty placeholder div feature flag is enabled.
*/
public function admin_options() {
$form_fields = $this->get_form_fields();
echo '<h2>' . esc_html( $this->get_method_title() );
wc_back_link( __( 'Return to payments', 'woocommerce-gateway-stripe' ), admin_url( 'admin.php?page=wc-settings&tab=checkout' ) );
echo '</h2>';
$this->render_upe_settings();
}
/**
* Inserts an empty placeholder div for new account card when Stripe is not connected.
* Inserts an empty placeholder div for UPE opt-in banner within the existing form fields, otherwise.
*/
public function render_upe_settings() {
global $hide_save_button;
$hide_save_button = true;
$is_stripe_connected = woocommerce_gateway_stripe()->connect->is_connected();
echo $is_stripe_connected ? '<div id="wc-stripe-payment-gateway-container"></div>' : '<div id="wc-stripe-new-account-container"></div>';
}
/**
* Displays the save to account checkbox.
*
* @since 4.1.0
* @version 5.6.0
*/
public function save_payment_method_checkbox( $force_checked = false ) {
$id = 'wc-' . $this->id . '-new-payment-method';
?>
<fieldset <?php echo $force_checked ? '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_stripe_save_to_account_text', __( 'Save payment information to my account for future purchases.', 'woocommerce-gateway-stripe' ) ) ); ?>
</label>
</p>
</fieldset>
<?php
}
/**
* Checks to see if request is invalid and that
* they are worth retrying.
*
* @since 4.0.5
* @param object $error
*/
public function is_retryable_error( $error ) {
// We don't want to retry payments when a 3DS mandate is invalid; it doesn't make sense.
// Note that this check is required since the error type is 'invalid_request_error' which
// would otherwise return true.
if ( isset( $error->code ) && 'payment_intent_mandate_invalid' === $error->code ) {
return false;
}
return (
'invalid_request_error' === $error->type ||
'idempotency_error' === $error->type ||
'rate_limit_error' === $error->type ||
'api_connection_error' === $error->type ||
'api_error' === $error->type
);
}
/**
* Checks to see if error is of same idempotency key
* error due to retries with different parameters.
*
* @since 4.1.0
* @param object $error
*/
public function is_same_idempotency_error( $error ) {
return (
$error &&
'idempotency_error' === $error->type &&
preg_match( '/Keys for idempotent requests can only be used with the same parameters they were first used with./i', $error->message )
);
}
/**
* Checks to see if error is of invalid request
* error and it is no such customer.
*
* @since 4.1.0
* @param object $error
*/
public function is_no_such_customer_error( $error ) {
return (
$error &&
'invalid_request_error' === $error->type &&
preg_match( '/No such customer/i', $error->message )
);
}
/**
* Checks to see if error is of invalid request
* error and it is no such token.
*
* @since 4.1.0
* @param object $error
*/
public function is_no_such_token_error( $error ) {
return (
$error &&
'invalid_request_error' === $error->type &&
preg_match( '/No such token/i', $error->message )
);
}
/**
* Checks to see if error is of invalid request
* error and it is no such source.
*
* @since 4.1.0
* @param object $error
*/
public function is_no_such_source_error( $error ) {
return (
$error &&
'invalid_request_error' === $error->type &&
preg_match( '/No such (source|PaymentMethod)/i', $error->message )
);
}
/**
* Checks to see if error is of invalid request
* error and it is no such source linked to customer.
*
* @since 4.1.0
* @param object $error
*/
public function is_no_linked_source_error( $error ) {
return (
$error &&
'invalid_request_error' === $error->type &&
preg_match( '/does not have a linked source with ID/i', $error->message )
);
}
/**
* Check to see if we need to update the idempotency
* key to be different from previous charge request.
*
* @since 4.1.0
* @param object $source_object
* @param object $error
* @return bool
*/
public function need_update_idempotency_key( $source_object, $error ) {
return (
$error &&
1 < $this->retry_interval &&
! empty( $source_object ) &&
'chargeable' === $source_object->status &&
self::is_same_idempotency_error( $error )
);
}
/**
* Checks if keys are set and valid.
*
* @since 4.0.6
* @return bool True if the keys are set *and* valid, false otherwise (for example, if keys are empty or the secret key was pasted as publishable key).
*/
public function are_keys_set() {
// NOTE: updates to this function should be added to are_keys_set()
// in includes/payment-methods/class-wc-stripe-payment-request.php
if ( $this->testmode ) {
return preg_match( '/^pk_test_/', $this->publishable_key )
&& preg_match( '/^[rs]k_test_/', $this->secret_key );
} else {
return preg_match( '/^pk_live_/', $this->publishable_key )
&& preg_match( '/^[rs]k_live_/', $this->secret_key );
}
}
/**
* Check if we need to make gateways available.
*
* @since 4.1.3
* @return bool
*/
public function is_available() {
if ( 'yes' === $this->enabled ) {
// Not available if the keys aren't set.
if ( ! $this->are_keys_set() ) {
return false;
}
// Not available if using live mode without SSL.
if ( $this->needs_ssl_setup() ) {
return false;
}
return true;
}
return parent::is_available();
}
public function save_payment_method_requested() {
$payment_method = isset( $_POST['payment_method'] ) ? wc_clean( wp_unslash( $_POST['payment_method'] ) ) : 'stripe';
return isset( $_POST[ 'wc-' . $payment_method . '-new-payment-method' ] ) && ! empty( $_POST[ 'wc-' . $payment_method . '-new-payment-method' ] );
}
/**
* Customer param wrong? The user may have been deleted on stripe's end. Remove customer_id. Can be retried without.
*
* @since 4.2.0
* @param object $error The error that was returned from Stripe's API.
* @param WC_Order $order The order those payment is being processed.
* @return bool A flag that indicates that the customer does not exist and should be removed.
*/
public function maybe_remove_non_existent_customer( $error, $order ) {
if ( ! $this->is_no_such_customer_error( $error ) ) {
return false;
}
delete_user_option( $order->get_customer_id(), '_stripe_customer_id' );
$order->delete_meta_data( '_stripe_customer_id' );
$order->save();
return true;
}
/**
* All payment icons that work with Stripe. Some icons references
* WC core icons.
*
* @since 4.0.0
* @since 4.1.0 Changed to using img with svg (colored) instead of fonts.
* @return array
*/
public function payment_icons() {
return apply_filters(
'wc_stripe_payment_icons',
[
'alipay' => '<img src="' . WC_STRIPE_PLUGIN_URL . '/assets/images/alipay.svg" class="stripe-alipay-icon stripe-icon" alt="Alipay" />',
'wechat' => '<img src="' . WC_STRIPE_PLUGIN_URL . '/assets/images/wechat.svg" class="stripe-wechat-icon stripe-icon" alt="Wechat Pay" />',
'bancontact' => '<img src="' . WC_STRIPE_PLUGIN_URL . '/assets/images/bancontact.svg" class="stripe-bancontact-icon stripe-icon" alt="Bancontact" />',
'ideal' => '<img src="' . WC_STRIPE_PLUGIN_URL . '/assets/images/ideal.svg" class="stripe-ideal-icon stripe-icon" alt="iDEAL" />',
'p24' => '<img src="' . WC_STRIPE_PLUGIN_URL . '/assets/images/p24.svg" class="stripe-p24-icon stripe-icon" alt="P24" />',
'giropay' => '<img src="' . WC_STRIPE_PLUGIN_URL . '/assets/images/giropay.svg" class="stripe-giropay-icon stripe-icon" alt="giropay" />',
'eps' => '<img src="' . WC_STRIPE_PLUGIN_URL . '/assets/images/eps.svg" class="stripe-eps-icon stripe-icon" alt="EPS" />',
'multibanco' => '<img src="' . WC_STRIPE_PLUGIN_URL . '/assets/images/multibanco.svg" class="stripe-multibanco-icon stripe-icon" alt="Multibanco" />',
'sofort' => '<img src="' . WC_STRIPE_PLUGIN_URL . '/assets/images/sofort.svg" class="stripe-sofort-icon stripe-icon" alt="Sofort" />',
'sepa' => '<img src="' . WC_STRIPE_PLUGIN_URL . '/assets/images/sepa.svg" class="stripe-sepa-icon stripe-icon" alt="SEPA" />',
'boleto' => '<img src="' . WC_STRIPE_PLUGIN_URL . '/assets/images/boleto.svg" class="stripe-boleto-icon stripe-icon" alt="Boleto" />',
'oxxo' => '<img src="' . WC_STRIPE_PLUGIN_URL . '/assets/images/oxxo.svg" class="stripe-oxxo-icon stripe-icon" alt="OXXO" />',
]
);
}
/**
* Validates that the order meets the minimum order amount
* set by Stripe.
*
* @since 4.0.0
* @version 4.0.0
* @param object $order
*/
public function validate_minimum_order_amount( $order ) {
if ( $order->get_total() * 100 < WC_Stripe_Helper::get_minimum_amount() ) {
/* translators: 1) amount (including currency symbol) */
throw new WC_Stripe_Exception( 'Did not meet minimum amount', sprintf( __( 'Sorry, the minimum allowed order total is %1$s to use this payment method.', 'woocommerce-gateway-stripe' ), wc_price( WC_Stripe_Helper::get_minimum_amount() / 100 ) ) );
}
}
/**
* Gets the transaction URL linked to Stripe dashboard.
*
* @since 4.0.0
* @version 4.0.0
*/
public function get_transaction_url( $order ) {
if ( $this->testmode ) {
$this->view_transaction_url = 'https://dashboard.stripe.com/test/payments/%s';
} else {
$this->view_transaction_url = 'https://dashboard.stripe.com/payments/%s';
}
return parent::get_transaction_url( $order );
}
/**
* Gets the saved customer id if exists.
*
* @since 4.0.0
* @version 4.0.0
*/
public function get_stripe_customer_id( $order ) {
// Try to get it via the order first.
$customer = $order->get_meta( '_stripe_customer_id', true );
if ( empty( $customer ) ) {
$customer = get_user_option( '_stripe_customer_id', $order->get_customer_id() );
}
return $customer;
}
/**
* Builds the return URL from redirects.
*
* @since 4.0.0
* @version 4.0.0
* @param object $order
* @param int $id Stripe session id.
*/
public function get_stripe_return_url( $order = null, $id = null ) {
if ( is_object( $order ) ) {
if ( empty( $id ) ) {
$id = uniqid();
}
$order_id = $order->get_id();
$args = [
'utm_nooverride' => '1',
'order_id' => $order_id,
];
return wp_sanitize_redirect( esc_url_raw( add_query_arg( $args, $this->get_return_url( $order ) ) ) );
}
return wp_sanitize_redirect( esc_url_raw( add_query_arg( [ 'utm_nooverride' => '1' ], $this->get_return_url() ) ) );
}
/**
* Generate the request for the payment.
*
* @since 3.1.0
* @version 4.5.4
* @param WC_Order $order
* @param object $prepared_payment_method Stripe Payment Method or Source.
* @return array()
*/
public function generate_payment_request( $order, $prepared_payment_method ) {
$settings = get_option( 'woocommerce_stripe_settings', [] );
$statement_descriptor = ! empty( $settings['statement_descriptor'] ) ? str_replace( "'", '', $settings['statement_descriptor'] ) : '';
$short_statement_descriptor = ! empty( $settings['short_statement_descriptor'] ) ? str_replace( "'", '', $settings['short_statement_descriptor'] ) : '';
$is_short_statement_descriptor_enabled = ! empty( $settings['is_short_statement_descriptor_enabled'] ) && 'yes' === $settings['is_short_statement_descriptor_enabled'];
$capture = ! empty( $settings['capture'] ) && 'yes' === $settings['capture'] ? true : false;
$post_data = [];
$post_data['currency'] = strtolower( $order->get_currency() );
$post_data['amount'] = WC_Stripe_Helper::get_stripe_amount( $order->get_total(), $post_data['currency'] );
/* translators: 1) blog name 2) order number */
$post_data['description'] = sprintf( __( '%1$s - Order %2$s', 'woocommerce-gateway-stripe' ), wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ), $order->get_order_number() );
$billing_email = $order->get_billing_email();
$billing_first_name = $order->get_billing_first_name();
$billing_last_name = $order->get_billing_last_name();
if ( ! empty( $billing_email ) && apply_filters( 'wc_stripe_send_stripe_receipt', false ) ) {
$post_data['receipt_email'] = $billing_email;
}
switch ( $order->get_payment_method() ) {
case 'stripe':
if ( $is_short_statement_descriptor_enabled && ! ( empty( $short_statement_descriptor ) && empty( $statement_descriptor ) ) ) {
$post_data['statement_descriptor'] = WC_Stripe_Helper::get_dynamic_statement_descriptor( $short_statement_descriptor, $order, $statement_descriptor );
} elseif ( ! empty( $statement_descriptor ) ) {
$post_data['statement_descriptor'] = WC_Stripe_Helper::clean_statement_descriptor( $statement_descriptor );
}
$post_data['capture'] = $capture ? 'true' : 'false';
break;
case 'stripe_sepa':
if ( ! empty( $statement_descriptor ) ) {
$post_data['statement_descriptor'] = WC_Stripe_Helper::clean_statement_descriptor( $statement_descriptor );
}
// other payment methods error if we try to add a statement descriptor in the request
}
if ( method_exists( $order, 'get_shipping_postcode' ) && ! empty( $order->get_shipping_postcode() ) ) {
$post_data['shipping'] = [
'name' => trim( $order->get_shipping_first_name() . ' ' . $order->get_shipping_last_name() ),
'address' => [
'line1' => $order->get_shipping_address_1(),
'line2' => $order->get_shipping_address_2(),
'city' => $order->get_shipping_city(),
'country' => $order->get_shipping_country(),
'postal_code' => $order->get_shipping_postcode(),
'state' => $order->get_shipping_state(),
],
];
}
$post_data['expand[]'] = 'balance_transaction';
$metadata = [
__( 'customer_name', 'woocommerce-gateway-stripe' ) => sanitize_text_field( $billing_first_name ) . ' ' . sanitize_text_field( $billing_last_name ),
__( 'customer_email', 'woocommerce-gateway-stripe' ) => sanitize_email( $billing_email ),
'order_id' => $order->get_order_number(),
'site_url' => esc_url( get_site_url() ),
];
if ( $this->has_subscription( $order->get_id() ) ) {
$metadata += [
'payment_type' => 'recurring',
];
}
$post_data['metadata'] = apply_filters( 'wc_stripe_payment_metadata', $metadata, $order, $prepared_payment_method );
if ( $prepared_payment_method->customer ) {
$post_data['customer'] = $prepared_payment_method->customer;
}
if ( ! empty( $prepared_payment_method->source ) ) {
$post_data['source'] = $prepared_payment_method->source;
}
if ( ! empty( $prepared_payment_method->payment_method ) ) {
$post_data['payment_method'] = $prepared_payment_method->payment_method;
}
/**
* Filter the return value of the WC_Payment_Gateway_CC::generate_payment_request.
*
* @since 3.1.0
* @param array $post_data
* @param WC_Order $order
* @param object $source
*/
return apply_filters( 'wc_stripe_generate_payment_request', $post_data, $order, $prepared_payment_method );
}
/**
* Store extra meta data for an order from a Stripe Response.
*
* @throws WC_Stripe_Exception
*/
public function process_response( $response, $order ) {
WC_Stripe_Logger::log( 'Processing response: ' . print_r( $response, true ) );
$potential_order = WC_Stripe_Helper::get_order_by_charge_id( $response->id );
if ( $potential_order && $potential_order->get_id() !== $order->get_id() ) {
WC_Stripe_Logger::log( 'Aborting, transaction already consumed by another order.' );
$localized_message = __( 'Payment processing failed. Please retry.', 'woocommerce-gateway-stripe' );
throw new WC_Stripe_Exception( print_r( $response, true ), $localized_message );
}
$order_id = $order->get_id();
$captured = ( isset( $response->captured ) && $response->captured ) ? 'yes' : 'no';
// Store charge data.
$order->update_meta_data( '_stripe_charge_captured', $captured );
if ( isset( $response->balance_transaction ) ) {
$this->update_fees( $order, is_string( $response->balance_transaction ) ? $response->balance_transaction : $response->balance_transaction->id );
}
if ( isset( $response->payment_method_details->card->mandate ) ) {
$order->update_meta_data( '_stripe_mandate_id', $response->payment_method_details->card->mandate );
}
if ( 'yes' === $captured ) {
/**
* Charge can be captured but in a pending state. Payment methods
* that are asynchronous may take couple days to clear. Webhook will
* take care of the status changes.
*/
if ( 'pending' === $response->status ) {
$order_stock_reduced = $order->get_meta( '_order_stock_reduced', true );
if ( ! $order_stock_reduced ) {
wc_reduce_stock_levels( $order_id );
}
$order->set_transaction_id( $response->id );
/* translators: transaction id */
$order->update_status( 'on-hold', sprintf( __( 'Stripe charge awaiting payment: %s.', 'woocommerce-gateway-stripe' ), $response->id ) );
}
if ( 'succeeded' === $response->status ) {
$order->payment_complete( $response->id );
/* translators: transaction id */
$message = sprintf( __( 'Stripe charge complete (Charge ID: %s)', 'woocommerce-gateway-stripe' ), $response->id );
$order->add_order_note( $message );
}
if ( 'failed' === $response->status ) {
$localized_message = __( 'Payment processing failed. Please retry.', 'woocommerce-gateway-stripe' );
$order->add_order_note( $localized_message );
throw new WC_Stripe_Exception( print_r( $response, true ), $localized_message );
}
} else {
$order->set_transaction_id( $response->id );
if ( $order->has_status( [ 'pending', 'failed' ] ) ) {
wc_reduce_stock_levels( $order_id );
}
/* translators: transaction id */
$order->update_status( 'on-hold', sprintf( __( 'Stripe charge authorized (Charge ID: %s). Process order to take payment, or cancel to remove the pre-authorization. Attempting to refund the order in part or in full will release the authorization and cancel the payment.', 'woocommerce-gateway-stripe' ), $response->id ) );
}
if ( is_callable( [ $order, 'save' ] ) ) {
$order->save();
}
do_action( 'wc_gateway_stripe_process_response', $response, $order );
return $response;
}
/**
* Sends the failed order email to admin.
*
* @since 3.1.0
* @version 4.0.0
* @param int $order_id
* @return null
*/
public function send_failed_order_email( $order_id ) {
$emails = WC()->mailer()->get_emails();
if ( ! empty( $emails ) && ! empty( $order_id ) ) {
$emails['WC_Email_Failed_Order']->trigger( $order_id );
}
}
/**
* Get owner details.
*
* @since 4.0.0
* @version 4.0.0
* @param object $order
* @return object $details
*/
public function get_owner_details( $order ) {
$billing_first_name = $order->get_billing_first_name();
$billing_last_name = $order->get_billing_last_name();
$details = [];
$name = $billing_first_name . ' ' . $billing_last_name;
$email = $order->get_billing_email();
$phone = $order->get_billing_phone();
if ( ! empty( $phone ) ) {
$details['phone'] = $phone;
}
if ( ! empty( $name ) ) {
$details['name'] = $name;
}
if ( ! empty( $email ) ) {
$details['email'] = $email;
}
$details['address']['line1'] = $order->get_billing_address_1();
$details['address']['line2'] = $order->get_billing_address_2();
$details['address']['state'] = $order->get_billing_state();
$details['address']['city'] = $order->get_billing_city();
$details['address']['postal_code'] = $order->get_billing_postcode();
$details['address']['country'] = $order->get_billing_country();
return (object) apply_filters( 'wc_stripe_owner_details', $details, $order );
}
/**
* Get source object by source ID.
*
* @since 4.0.3
* @param string $source_id The source ID to get source object for.
*
* @throws WC_Stripe_Exception Error while retrieving source object.
* @return string|object
*/
public function get_source_object( $source_id = '' ) {
if ( empty( $source_id ) ) {
return '';
}
$source_object = WC_Stripe_API::get_payment_method( $source_id );
if ( ! empty( $source_object->error ) ) {
throw new WC_Stripe_Exception( print_r( $source_object, true ), $source_object->error->message );
}
return $source_object;
}
/**
* Get charge object by charge ID.
*
* @since 7.0.2
* @param string $charge_id The charge ID to get charge object for.
* @param array $params The parameters to pass to the request.
*
* @throws WC_Stripe_Exception Error while retrieving charge object.
* @return string|object
*/
public function get_charge_object( $charge_id = '', $params = [] ) {
if ( empty( $charge_id ) ) {
return '';
}
$charge_object = WC_Stripe_API::request( $params, 'charges/' . $charge_id, 'GET' );
if ( ! empty( $charge_object->error ) ) {
throw new WC_Stripe_Exception( print_r( $charge_object, true ), $charge_object->error->message );
}
return $charge_object;
}
/**
* Get latest charge object from payment intent.
*
* Since API version 2022-11-15, the `charges` property was replaced with `latest_charge`.
* We can remove this method once we drop support for API versions prior to 2022-11-15.
*
* @since 7.0.2
* @param object $intent Stripe API Payment Intent object response.
*
* @return object
*/
public function get_latest_charge_from_intent( $intent ) {
if ( ! empty( $intent->charges->data ) ) {
return end( $intent->charges->data );
} else {
return $this->get_charge_object( $intent->latest_charge );
}
}
/**
* Checks if card is a prepaid card.
*
* @since 4.0.6
* @param object $source_object
* @return bool
*/
public function is_prepaid_card( $source_object ) {
return (
$source_object
&& in_array( $source_object->object, [ 'token', 'source', 'payment_method' ], true )
&& 'prepaid' === $source_object->card->funding
);
}
/**
* Checks if a payment method object represents a prepaid credit card and
* throws an exception if it is one, but that is not allowed.
*
* @since 4.2.0
* @param object $prepared_source The object with source details.
* @throws WC_Stripe_Exception An exception if the card is prepaid, but prepaid cards are not allowed.
*/
public function maybe_disallow_prepaid_card( $payment_method ) {
// Check if we don't allow prepaid credit cards.
if ( apply_filters( 'wc_stripe_allow_prepaid_card', true ) || ! $this->is_prepaid_card( $payment_method ) ) {
return;
}
$localized_message = __( 'Sorry, we\'re not accepting prepaid cards at this time. Your credit card has not been charged. Please try with alternative payment method.', 'woocommerce-gateway-stripe' );
throw new WC_Stripe_Exception( print_r( $payment_method, true ), $localized_message );
}
/**
* Checks if source is of legacy type card.
*
* @since 4.0.8
* @param string $source_id
* @return bool
*/
public function is_type_legacy_card( $source_id ) {
return ( preg_match( '/^card_/', $source_id ) );
}
/**
* Checks if source is payment method (pm_).
*
* @since 5.6.0
* @param string $source_id
* @return bool
*/
public function is_type_payment_method( $source_id ) {
return ( preg_match( '/^pm_/', $source_id ) );
}
/**
* Checks if payment is via saved payment source.
*
* @since 4.1.0
* @return bool
*/
public function is_using_saved_payment_method() {
$payment_method = isset( $_POST['payment_method'] ) ? wc_clean( wp_unslash( $_POST['payment_method'] ) ) : 'stripe';
return ( isset( $_POST[ 'wc-' . $payment_method . '-payment-token' ] ) && 'new' !== $_POST[ 'wc-' . $payment_method . '-payment-token' ] );
}
/**
* Get payment source. This can be a new token/source or existing WC token.
* If user is logged in and/or has WC account, create an account on Stripe.
* This way we can attribute the payment to the user to better fight fraud.
*
* @since 3.1.0
* @version 4.0.0
* @param string $user_id
* @param bool $force_save_source Should we force save payment source.
*
* @throws Exception When card was not added or for and invalid card.
* @return object
*/
public function prepare_source( $user_id, $force_save_source = false, $existing_customer_id = null ) {
$customer = new WC_Stripe_Customer( $user_id );
if ( ! empty( $existing_customer_id ) ) {
$customer->set_id( $existing_customer_id );
}
$force_save_source = apply_filters( 'wc_stripe_force_save_source', $force_save_source, $customer );
$source_object = '';
$source_id = '';
$wc_token_id = false;
$payment_method = isset( $_POST['payment_method'] ) ? wc_clean( wp_unslash( $_POST['payment_method'] ) ) : 'stripe';
$is_token = false;
// New CC info was entered and we have a new source to process.
if ( ! empty( $_POST['stripe_source'] ) ) {
$source_object = self::get_source_object( wc_clean( wp_unslash( $_POST['stripe_source'] ) ) );
$source_id = $source_object->id;
// This checks to see if customer opted to save the payment method to file.
$maybe_saved_card = isset( $_POST[ 'wc-' . $payment_method . '-new-payment-method' ] ) && ! empty( $_POST[ 'wc-' . $payment_method . '-new-payment-method' ] );
/**
* This is true if the user wants to store the card to their account.
* Criteria to save to file is they are logged in, they opted to save or product requirements and the source is
* actually reusable. Either that or force_save_source is true.
*/
if ( ( $user_id && $this->saved_cards && $maybe_saved_card && WC_Stripe_Helper::is_reusable_payment_method( $source_object ) ) || $force_save_source ) {
$response = $customer->attach_source( $source_object->id );
if ( ! empty( $response->error ) ) {
throw new WC_Stripe_Exception( print_r( $response, true ), $this->get_localized_error_message_from_response( $response ) );
}
if ( is_wp_error( $response ) ) {
throw new WC_Stripe_Exception( $response->get_error_message(), $response->get_error_message() );
}
}
} elseif ( $this->is_using_saved_payment_method() ) {
// Use an existing token, and then process the payment.
$wc_token_id = isset( $_POST[ 'wc-' . $payment_method . '-payment-token' ] ) ? wc_clean( wp_unslash( $_POST[ 'wc-' . $payment_method . '-payment-token' ] ) ) : '';
$wc_token = WC_Payment_Tokens::get( $wc_token_id );
if ( ! $wc_token || $wc_token->get_user_id() !== get_current_user_id() ) {
WC()->session->set( 'refresh_totals', true );
throw new WC_Stripe_Exception( 'Invalid payment method', __( 'Invalid payment method. Please input a new card number.', 'woocommerce-gateway-stripe' ) );
}
$source_id = $wc_token->get_token();
if ( $this->is_type_legacy_card( $source_id ) || $this->is_type_payment_method( $source_id ) ) {
$is_token = true;
}
} elseif ( isset( $_POST['stripe_token'] ) && 'new' !== $_POST['stripe_token'] ) {
$stripe_token = wc_clean( wp_unslash( $_POST['stripe_token'] ) );
$maybe_saved_card = isset( $_POST[ 'wc-' . $payment_method . '-new-payment-method' ] ) && ! empty( $_POST[ 'wc-' . $payment_method . '-new-payment-method' ] );
// This is true if the user wants to store the card to their account.
if ( ( $user_id && $this->saved_cards && $maybe_saved_card ) || $force_save_source ) {
$response = $customer->attach_source( $stripe_token );
if ( ! empty( $response->error ) ) {
throw new WC_Stripe_Exception( print_r( $response, true ), $response->error->message );
}
if ( is_wp_error( $response ) ) {
throw new WC_Stripe_Exception( $response->get_error_message(), $response->get_error_message() );
}
$source_id = $response->id;
} else {
$source_id = $stripe_token;
$is_token = true;
}
}
$customer_id = $customer->get_id();
if ( ! $customer_id ) {
$customer->set_id( $customer->create_customer() );
$customer_id = $customer->get_id();
} else {
$customer_id = $customer->update_customer();
}
if ( empty( $source_object ) && ! $is_token ) {
$source_object = self::get_source_object( $source_id );
}
return (object) [
'token_id' => $wc_token_id,
'customer' => $customer_id,
'source' => $source_id,
'source_object' => $source_object,
'payment_method' => null,
];
}
/**
* Get payment source from an order. This could be used in the future for
* a subscription as an example, therefore using the current user ID would
* not work - the customer won't be logged in :)
*
* Not using 2.6 tokens for this part since we need a customer AND a card
* token, and not just one.
*
* @since 3.1.0
* @version 4.0.0
* @param object $order
* @return object
*/
public function prepare_order_source( $order = null ) {
$stripe_customer = new WC_Stripe_Customer();
$stripe_source = false;
$token_id = false;
$source_object = false;
if ( $order ) {
$stripe_customer_id = $this->get_stripe_customer_id( $order );
if ( $stripe_customer_id ) {
$stripe_customer->set_id( $stripe_customer_id );
}
$source_id = $order->get_meta( '_stripe_source_id', true );
// Since 4.0.0, we changed card to source so we need to account for that.
if ( empty( $source_id ) ) {
$source_id = $order->get_meta( '_stripe_card_id', true );
// Take this opportunity to update the key name.
$order->update_meta_data( '_stripe_source_id', $source_id );
if ( is_callable( [ $order, 'save' ] ) ) {
$order->save();
}
}
if ( $source_id ) {
$stripe_source = $source_id;
$source_object = WC_Stripe_API::get_payment_method( $source_id );
} elseif ( apply_filters( 'wc_stripe_use_default_customer_source', true ) ) {
/*
* We can attempt to charge the customer's default source
* by sending empty source id.
*/
$stripe_source = '';
}
}
return (object) [
'token_id' => $token_id,
'customer' => $stripe_customer ? $stripe_customer->get_id() : false,
'source' => $stripe_source,
'source_object' => $source_object,
'payment_method' => null,
];
}
/**
* Checks whether a source exists.
*
* @since 4.2.0
* @param object $prepared_source The source that should be verified.
* @throws WC_Stripe_Exception An exception if the source ID is missing.
*/
public function check_source( $prepared_source ) {
if ( empty( $prepared_source->source ) ) {
$localized_message = __( 'Payment processing failed. Please retry.', 'woocommerce-gateway-stripe' );
throw new WC_Stripe_Exception( print_r( $prepared_source, true ), $localized_message );
}
}
/**
* Save source to order.
*
* @since 3.1.0
* @version 4.0.0
* @param WC_Order $order For to which the source applies.
* @param stdClass $source Source information.
*/
public function save_source_to_order( $order, $source ) {
// Store source in the order.
if ( $source->customer ) {
$order->update_meta_data( '_stripe_customer_id', $source->customer );
}
if ( $source->source ) {
$order->update_meta_data( '_stripe_source_id', $source->source );
}
if ( is_callable( [ $order, 'save' ] ) ) {
$order->save();
}
$this->maybe_update_source_on_subscription_order( $order, $source );
}
/**
* Updates Stripe fees/net.
* e.g usage would be after a refund.
*
* @since 4.0.0
* @version 4.0.6
* @param object $order The order object