blob: 7666dcb9866fecddf464a649fdfae0410c4d207b [file] [log] [blame]
swissChilif0cbdc32023-01-05 17:21:38 -05001<?php
2if ( ! defined( 'ABSPATH' ) ) {
3 exit;
4}
5
6/**
7 * WC_Stripe_Customer class.
8 *
9 * Represents a Stripe Customer.
10 */
11class WC_Stripe_Customer {
12
13 /**
14 * String prefix for Stripe payment methods request transient.
15 */
16 const PAYMENT_METHODS_TRANSIENT_KEY = 'stripe_payment_methods_';
17
18 /**
19 * Queryable Stripe payment method types.
20 */
21 const STRIPE_PAYMENT_METHODS = [
22 WC_Stripe_UPE_Payment_Method_CC::STRIPE_ID,
23 WC_Stripe_UPE_Payment_Method_Sepa::STRIPE_ID,
24 ];
25
26 /**
27 * Stripe customer ID
28 *
29 * @var string
30 */
31 private $id = '';
32
33 /**
34 * WP User ID
35 *
36 * @var integer
37 */
38 private $user_id = 0;
39
40 /**
41 * Data from API
42 *
43 * @var array
44 */
45 private $customer_data = [];
46
47 /**
48 * Constructor
49 *
50 * @param int $user_id The WP user ID
51 */
52 public function __construct( $user_id = 0 ) {
53 if ( $user_id ) {
54 $this->set_user_id( $user_id );
55 $this->set_id( $this->get_id_from_meta( $user_id ) );
56 }
57 }
58
59 /**
60 * Get Stripe customer ID.
61 *
62 * @return string
63 */
64 public function get_id() {
65 return $this->id;
66 }
67
68 /**
69 * Set Stripe customer ID.
70 *
71 * @param [type] $id [description]
72 */
73 public function set_id( $id ) {
74 // Backwards compat for customer ID stored in array format. (Pre 3.0)
75 if ( is_array( $id ) && isset( $id['customer_id'] ) ) {
76 $id = $id['customer_id'];
77
78 $this->update_id_in_meta( $id );
79 }
80
81 $this->id = wc_clean( $id );
82 }
83
84 /**
85 * User ID in WordPress.
86 *
87 * @return int
88 */
89 public function get_user_id() {
90 return absint( $this->user_id );
91 }
92
93 /**
94 * Set User ID used by WordPress.
95 *
96 * @param int $user_id
97 */
98 public function set_user_id( $user_id ) {
99 $this->user_id = absint( $user_id );
100 }
101
102 /**
103 * Get user object.
104 *
105 * @return WP_User
106 */
107 protected function get_user() {
108 return $this->get_user_id() ? get_user_by( 'id', $this->get_user_id() ) : false;
109 }
110
111 /**
112 * Store data from the Stripe API about this customer
113 */
114 public function set_customer_data( $data ) {
115 $this->customer_data = $data;
116 }
117
118 /**
119 * Generates the customer request, used for both creating and updating customers.
120 *
121 * @param array $args Additional arguments (optional).
122 * @return array
123 */
124 protected function generate_customer_request( $args = [] ) {
125 $billing_email = isset( $_POST['billing_email'] ) ? filter_var( wp_unslash( $_POST['billing_email'] ), FILTER_SANITIZE_EMAIL ) : '';
126 $user = $this->get_user();
127
128 if ( $user ) {
129 $billing_first_name = get_user_meta( $user->ID, 'billing_first_name', true );
130 $billing_last_name = get_user_meta( $user->ID, 'billing_last_name', true );
131
132 // If billing first name does not exists try the user first name.
133 if ( empty( $billing_first_name ) ) {
134 $billing_first_name = get_user_meta( $user->ID, 'first_name', true );
135 }
136
137 // If billing last name does not exists try the user last name.
138 if ( empty( $billing_last_name ) ) {
139 $billing_last_name = get_user_meta( $user->ID, 'last_name', true );
140 }
141
142 // translators: %1$s First name, %2$s Second name, %3$s Username.
143 $description = sprintf( __( 'Name: %1$s %2$s, Username: %3$s', 'woocommerce-gateway-stripe' ), $billing_first_name, $billing_last_name, $user->user_login );
144
145 $defaults = [
146 'email' => $user->user_email,
147 'description' => $description,
148 ];
149
150 $billing_full_name = trim( $billing_first_name . ' ' . $billing_last_name );
151 if ( ! empty( $billing_full_name ) ) {
152 $defaults['name'] = $billing_full_name;
153 }
154 } else {
155 $billing_first_name = isset( $_POST['billing_first_name'] ) ? filter_var( wp_unslash( $_POST['billing_first_name'] ), FILTER_SANITIZE_STRING ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
156 $billing_last_name = isset( $_POST['billing_last_name'] ) ? filter_var( wp_unslash( $_POST['billing_last_name'] ), FILTER_SANITIZE_STRING ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
157
158 // translators: %1$s First name, %2$s Second name.
159 $description = sprintf( __( 'Name: %1$s %2$s, Guest', 'woocommerce-gateway-stripe' ), $billing_first_name, $billing_last_name );
160
161 $defaults = [
162 'email' => $billing_email,
163 'description' => $description,
164 ];
165
166 $billing_full_name = trim( $billing_first_name . ' ' . $billing_last_name );
167 if ( ! empty( $billing_full_name ) ) {
168 $defaults['name'] = $billing_full_name;
169 }
170 }
171
172 $metadata = [];
173 $defaults['metadata'] = apply_filters( 'wc_stripe_customer_metadata', $metadata, $user );
174 $defaults['preferred_locales'] = $this->get_customer_preferred_locale( $user );
175
176 return wp_parse_args( $args, $defaults );
177 }
178
179 /**
180 * Create a customer via API.
181 *
182 * @param array $args
183 * @return WP_Error|int
184 */
185 public function create_customer( $args = [] ) {
186 $args = $this->generate_customer_request( $args );
187 $response = WC_Stripe_API::request( apply_filters( 'wc_stripe_create_customer_args', $args ), 'customers' );
188
189 if ( ! empty( $response->error ) ) {
190 throw new WC_Stripe_Exception( print_r( $response, true ), $response->error->message );
191 }
192
193 $this->set_id( $response->id );
194 $this->clear_cache();
195 $this->set_customer_data( $response );
196
197 if ( $this->get_user_id() ) {
198 $this->update_id_in_meta( $response->id );
199 }
200
201 do_action( 'woocommerce_stripe_add_customer', $args, $response );
202
203 return $response->id;
204 }
205
206 /**
207 * Updates the Stripe customer through the API.
208 *
209 * @param array $args Additional arguments for the request (optional).
210 * @param bool $is_retry Whether the current call is a retry (optional, defaults to false). If true, then an exception will be thrown instead of further retries on error.
211 *
212 * @return string Customer ID
213 *
214 * @throws WC_Stripe_Exception
215 */
216 public function update_customer( $args = [], $is_retry = false ) {
217 if ( empty( $this->get_id() ) ) {
218 throw new WC_Stripe_Exception( 'id_required_to_update_user', __( 'Attempting to update a Stripe customer without a customer ID.', 'woocommerce-gateway-stripe' ) );
219 }
220
221 $args = $this->generate_customer_request( $args );
222 $args = apply_filters( 'wc_stripe_update_customer_args', $args );
223 $response = WC_Stripe_API::request( $args, 'customers/' . $this->get_id() );
224
225 if ( ! empty( $response->error ) ) {
226 if ( $this->is_no_such_customer_error( $response->error ) && ! $is_retry ) {
227 // This can happen when switching the main Stripe account or importing users from another site.
228 // If not already retrying, recreate the customer and then try updating it again.
229 $this->recreate_customer();
230 return $this->update_customer( $args, true );
231 }
232
233 throw new WC_Stripe_Exception( print_r( $response, true ), $response->error->message );
234 }
235
236 $this->clear_cache();
237 $this->set_customer_data( $response );
238
239 do_action( 'woocommerce_stripe_update_customer', $args, $response );
240
241 return $this->get_id();
242 }
243
244 /**
245 * Updates existing Stripe customer or creates new customer for User through API.
246 *
247 * @param array $args Additional arguments for the request (optional).
248 * @param bool $is_retry Whether the current call is a retry (optional, defaults to false). If true, then an exception will be thrown instead of further retries on error.
249 *
250 * @return string Customer ID
251 *
252 * @throws WC_Stripe_Exception
253 */
254 public function update_or_create_customer( $args = [], $is_retry = false ) {
255 if ( empty( $this->get_id() ) ) {
256 return $this->recreate_customer();
257 } else {
258 return $this->update_customer( $args, true );
259 }
260 }
261
262 /**
263 * Checks to see if error is of invalid request
264 * error and it is no such customer.
265 *
266 * @since 4.1.2
267 * @param array $error
268 */
269 public function is_no_such_customer_error( $error ) {
270 return (
271 $error &&
272 'invalid_request_error' === $error->type &&
273 preg_match( '/No such customer/i', $error->message )
274 );
275 }
276
277 /**
278 * Checks to see if error is of invalid request
279 * error and it is no such customer.
280 *
281 * @since 4.5.6
282 * @param array $error
283 * @return bool
284 */
285 public function is_source_already_attached_error( $error ) {
286 return (
287 $error &&
288 'invalid_request_error' === $error->type &&
289 preg_match( '/already been attached to a customer/i', $error->message )
290 );
291 }
292
293 /**
294 * Add a source for this stripe customer.
295 *
296 * @param string $source_id
297 * @return WP_Error|int
298 */
299 public function add_source( $source_id ) {
300 $response = WC_Stripe_API::retrieve( 'sources/' . $source_id );
301
302 if ( ! empty( $response->error ) || is_wp_error( $response ) ) {
303 return $response;
304 }
305
306 // Add token to WooCommerce.
307 $wc_token = false;
308
309 if ( $this->get_user_id() && class_exists( 'WC_Payment_Token_CC' ) ) {
310 if ( ! empty( $response->type ) ) {
311 switch ( $response->type ) {
312 case 'alipay':
313 break;
314 case 'sepa_debit':
315 $wc_token = new WC_Payment_Token_SEPA();
316 $wc_token->set_token( $response->id );
317 $wc_token->set_gateway_id( 'stripe_sepa' );
318 $wc_token->set_last4( $response->sepa_debit->last4 );
319 break;
320 default:
321 if ( 'source' === $response->object && 'card' === $response->type ) {
322 $wc_token = new WC_Payment_Token_CC();
323 $wc_token->set_token( $response->id );
324 $wc_token->set_gateway_id( 'stripe' );
325 $wc_token->set_card_type( strtolower( $response->card->brand ) );
326 $wc_token->set_last4( $response->card->last4 );
327 $wc_token->set_expiry_month( $response->card->exp_month );
328 $wc_token->set_expiry_year( $response->card->exp_year );
329 }
330 break;
331 }
332 } else {
333 // Legacy.
334 $wc_token = new WC_Payment_Token_CC();
335 $wc_token->set_token( $response->id );
336 $wc_token->set_gateway_id( 'stripe' );
337 $wc_token->set_card_type( strtolower( $response->brand ) );
338 $wc_token->set_last4( $response->last4 );
339 $wc_token->set_expiry_month( $response->exp_month );
340 $wc_token->set_expiry_year( $response->exp_year );
341 }
342
343 $wc_token->set_user_id( $this->get_user_id() );
344 $wc_token->save();
345 }
346
347 $this->clear_cache();
348
349 do_action( 'woocommerce_stripe_add_source', $this->get_id(), $wc_token, $response, $source_id );
350
351 return $response->id;
352 }
353
354 /**
355 * Attaches a source to the Stripe customer.
356 *
357 * @param string $source_id The ID of the new source.
358 * @return object|WP_Error Either a source object, or a WP error.
359 */
360 public function attach_source( $source_id ) {
361 if ( ! $this->get_id() ) {
362 $this->set_id( $this->create_customer() );
363 }
364
365 $response = WC_Stripe_API::request(
366 [
367 'source' => $source_id,
368 ],
369 'customers/' . $this->get_id() . '/sources'
370 );
371
372 if ( ! empty( $response->error ) ) {
373 // It is possible the WC user once was linked to a customer on Stripe
374 // but no longer exists. Instead of failing, lets try to create a
375 // new customer.
376 if ( $this->is_no_such_customer_error( $response->error ) ) {
377 $this->recreate_customer();
378 return $this->attach_source( $source_id );
379 } elseif ( $this->is_source_already_attached_error( $response->error ) ) {
380 return WC_Stripe_API::request( [], 'sources/' . $source_id, 'GET' );
381 } else {
382 return $response;
383 }
384 } elseif ( empty( $response->id ) ) {
385 return new WP_Error( 'error', __( 'Unable to add payment source.', 'woocommerce-gateway-stripe' ) );
386 } else {
387 return $response;
388 }
389 }
390
391 /**
392 * Get a customers saved sources using their Stripe ID.
393 *
394 * @param string $customer_id
395 * @return array
396 */
397 public function get_sources() {
398 if ( ! $this->get_id() ) {
399 return [];
400 }
401
402 $sources = get_transient( 'stripe_sources_' . $this->get_id() );
403
404 if ( false === $sources ) {
405 $response = WC_Stripe_API::request(
406 [
407 'limit' => 100,
408 ],
409 'customers/' . $this->get_id() . '/sources',
410 'GET'
411 );
412
413 if ( ! empty( $response->error ) ) {
414 return [];
415 }
416
417 if ( is_array( $response->data ) ) {
418 $sources = $response->data;
419 }
420
421 set_transient( 'stripe_sources_' . $this->get_id(), $sources, DAY_IN_SECONDS );
422 }
423
424 return empty( $sources ) ? [] : $sources;
425 }
426
427 /**
428 * Gets saved payment methods for a customer using Intentions API.
429 *
430 * @param string $payment_method_type Stripe ID of payment method type
431 *
432 * @return array
433 */
434 public function get_payment_methods( $payment_method_type ) {
435 if ( ! $this->get_id() ) {
436 return [];
437 }
438
439 $payment_methods = get_transient( self::PAYMENT_METHODS_TRANSIENT_KEY . $payment_method_type . $this->get_id() );
440
441 if ( false === $payment_methods ) {
442 $params = WC_Stripe_UPE_Payment_Method_Sepa::STRIPE_ID === $payment_method_type ? '?expand[]=data.sepa_debit.generated_from.charge&expand[]=data.sepa_debit.generated_from.setup_attempt' : '';
443 $response = WC_Stripe_API::request(
444 [
445 'customer' => $this->get_id(),
446 'type' => $payment_method_type,
447 'limit' => 100, // Maximum allowed value.
448 ],
449 'payment_methods' . $params,
450 'GET'
451 );
452
453 if ( ! empty( $response->error ) ) {
454 return [];
455 }
456
457 if ( is_array( $response->data ) ) {
458 $payment_methods = $response->data;
459 }
460
461 set_transient( self::PAYMENT_METHODS_TRANSIENT_KEY . $payment_method_type . $this->get_id(), $payment_methods, DAY_IN_SECONDS );
462 }
463
464 return empty( $payment_methods ) ? [] : $payment_methods;
465 }
466
467 /**
468 * Delete a source from stripe.
469 *
470 * @param string $source_id
471 */
472 public function delete_source( $source_id ) {
473 if ( ! $this->get_id() ) {
474 return false;
475 }
476
477 $response = WC_Stripe_API::request( [], 'customers/' . $this->get_id() . '/sources/' . sanitize_text_field( $source_id ), 'DELETE' );
478
479 $this->clear_cache();
480
481 if ( empty( $response->error ) ) {
482 do_action( 'wc_stripe_delete_source', $this->get_id(), $response );
483
484 return true;
485 }
486
487 return false;
488 }
489
490 /**
491 * Detach a payment method from stripe.
492 *
493 * @param string $payment_method_id
494 */
495 public function detach_payment_method( $payment_method_id ) {
496 if ( ! $this->get_id() ) {
497 return false;
498 }
499
500 $response = WC_Stripe_API::request( [], "payment_methods/$payment_method_id/detach", 'POST' );
501
502 $this->clear_cache();
503
504 if ( empty( $response->error ) ) {
505 do_action( 'wc_stripe_detach_payment_method', $this->get_id(), $response );
506
507 return true;
508 }
509
510 return false;
511 }
512
513 /**
514 * Set default source in Stripe
515 *
516 * @param string $source_id
517 */
518 public function set_default_source( $source_id ) {
519 $response = WC_Stripe_API::request(
520 [
521 'default_source' => sanitize_text_field( $source_id ),
522 ],
523 'customers/' . $this->get_id(),
524 'POST'
525 );
526
527 $this->clear_cache();
528
529 if ( empty( $response->error ) ) {
530 do_action( 'wc_stripe_set_default_source', $this->get_id(), $response );
531
532 return true;
533 }
534
535 return false;
536 }
537
538 /**
539 * Set default payment method in Stripe
540 *
541 * @param string $payment_method_id
542 */
543 public function set_default_payment_method( $payment_method_id ) {
544 $response = WC_Stripe_API::request(
545 [
546 'invoice_settings' => [
547 'default_payment_method' => sanitize_text_field( $payment_method_id ),
548 ],
549 ],
550 'customers/' . $this->get_id(),
551 'POST'
552 );
553
554 $this->clear_cache();
555
556 if ( empty( $response->error ) ) {
557 do_action( 'wc_stripe_set_default_payment_method', $this->get_id(), $response );
558
559 return true;
560 }
561
562 return false;
563 }
564
565 /**
566 * Deletes caches for this users cards.
567 */
568 public function clear_cache() {
569 delete_transient( 'stripe_sources_' . $this->get_id() );
570 delete_transient( 'stripe_customer_' . $this->get_id() );
571 foreach ( self::STRIPE_PAYMENT_METHODS as $payment_method_type ) {
572 delete_transient( self::PAYMENT_METHODS_TRANSIENT_KEY . $payment_method_type . $this->get_id() );
573 }
574 $this->customer_data = [];
575 }
576
577 /**
578 * Retrieves the Stripe Customer ID from the user meta.
579 *
580 * @param int $user_id The ID of the WordPress user.
581 * @return string|bool Either the Stripe ID or false.
582 */
583 public function get_id_from_meta( $user_id ) {
584 return get_user_option( '_stripe_customer_id', $user_id );
585 }
586
587 /**
588 * Updates the current user with the right Stripe ID in the meta table.
589 *
590 * @param string $id The Stripe customer ID.
591 */
592 public function update_id_in_meta( $id ) {
593 update_user_option( $this->get_user_id(), '_stripe_customer_id', $id, false );
594 }
595
596 /**
597 * Deletes the user ID from the meta table with the right key.
598 */
599 public function delete_id_from_meta() {
600 delete_user_option( $this->get_user_id(), '_stripe_customer_id', false );
601 }
602
603 /**
604 * Recreates the customer for this user.
605 *
606 * @return string ID of the new Customer object.
607 */
608 private function recreate_customer() {
609 $this->delete_id_from_meta();
610 return $this->create_customer();
611 }
612
613 /**
614 * Get the customer's preferred locale based on the user or site setting.
615 *
616 * @param object $user The user being created/modified.
617 * @return array The matched locale string wrapped in an array, or empty default.
618 */
619 public function get_customer_preferred_locale( $user ) {
620 $locale = $this->get_customer_locale( $user );
621
622 // Options based on Stripe locales.
623 // https://support.stripe.com/questions/language-options-for-customer-emails
624 $stripe_locales = [
625 'ar' => 'ar-AR',
626 'da_DK' => 'da-DK',
627 'de_DE' => 'de-DE',
628 'en' => 'en-US',
629 'es_ES' => 'es-ES',
630 'es_CL' => 'es-419',
631 'es_AR' => 'es-419',
632 'es_CO' => 'es-419',
633 'es_PE' => 'es-419',
634 'es_UY' => 'es-419',
635 'es_PR' => 'es-419',
636 'es_GT' => 'es-419',
637 'es_EC' => 'es-419',
638 'es_MX' => 'es-419',
639 'es_VE' => 'es-419',
640 'es_CR' => 'es-419',
641 'fi' => 'fi-FI',
642 'fr_FR' => 'fr-FR',
643 'he_IL' => 'he-IL',
644 'it_IT' => 'it-IT',
645 'ja' => 'ja-JP',
646 'nl_NL' => 'nl-NL',
647 'nn_NO' => 'no-NO',
648 'pt_BR' => 'pt-BR',
649 'sv_SE' => 'sv-SE',
650 ];
651
652 $preferred = isset( $stripe_locales[ $locale ] ) ? $stripe_locales[ $locale ] : 'en-US';
653 return [ $preferred ];
654 }
655
656 /**
657 * Gets the customer's locale/language based on their setting or the site settings.
658 *
659 * @param object $user The user we're wanting to get the locale for.
660 * @return string The locale/language set in the user profile or the site itself.
661 */
662 public function get_customer_locale( $user ) {
663 // If we have a user, get their locale with a site fallback.
664 return ( $user ) ? get_user_locale( $user->ID ) : get_locale();
665 }
666
667 /**
668 * Given a WC_Order or WC_Customer, returns an array representing a Stripe customer object.
669 * At least one parameter has to not be null.
670 *
671 * @param WC_Order $wc_order The Woo order to parse.
672 * @param WC_Customer $wc_customer The Woo customer to parse.
673 *
674 * @return array Customer data.
675 */
676 public static function map_customer_data( WC_Order $wc_order = null, WC_Customer $wc_customer = null ) {
677 if ( null === $wc_customer && null === $wc_order ) {
678 return [];
679 }
680
681 // Where available, the order data takes precedence over the customer.
682 $object_to_parse = isset( $wc_order ) ? $wc_order : $wc_customer;
683 $name = $object_to_parse->get_billing_first_name() . ' ' . $object_to_parse->get_billing_last_name();
684 $description = '';
685 if ( null !== $wc_customer && ! empty( $wc_customer->get_username() ) ) {
686 // We have a logged in user, so add their username to the customer description.
687 // translators: %1$s Name, %2$s Username.
688 $description = sprintf( __( 'Name: %1$s, Username: %2$s', 'woocommerce-gateway-stripe' ), $name, $wc_customer->get_username() );
689 } else {
690 // Current user is not logged in.
691 // translators: %1$s Name.
692 $description = sprintf( __( 'Name: %1$s, Guest', 'woocommerce-gateway-stripe' ), $name );
693 }
694
695 $data = [
696 'name' => $name,
697 'description' => $description,
698 'email' => $object_to_parse->get_billing_email(),
699 'phone' => $object_to_parse->get_billing_phone(),
700 'address' => [
701 'line1' => $object_to_parse->get_billing_address_1(),
702 'line2' => $object_to_parse->get_billing_address_2(),
703 'postal_code' => $object_to_parse->get_billing_postcode(),
704 'city' => $object_to_parse->get_billing_city(),
705 'state' => $object_to_parse->get_billing_state(),
706 'country' => $object_to_parse->get_billing_country(),
707 ],
708 ];
709
710 if ( ! empty( $object_to_parse->get_shipping_postcode() ) ) {
711 $data['shipping'] = [
712 'name' => $object_to_parse->get_shipping_first_name() . ' ' . $object_to_parse->get_shipping_last_name(),
713 'address' => [
714 'line1' => $object_to_parse->get_shipping_address_1(),
715 'line2' => $object_to_parse->get_shipping_address_2(),
716 'postal_code' => $object_to_parse->get_shipping_postcode(),
717 'city' => $object_to_parse->get_shipping_city(),
718 'state' => $object_to_parse->get_shipping_state(),
719 'country' => $object_to_parse->get_shipping_country(),
720 ],
721 ];
722 }
723
724 return $data;
725 }
726}