-
Notifications
You must be signed in to change notification settings - Fork 69
/
MultiCurrency.php
1717 lines (1487 loc) · 56.7 KB
/
MultiCurrency.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Class MultiCurrency
*
* @package WooCommerce\Payments\MultiCurrency
*/
namespace WCPay\MultiCurrency;
use WCPay\MultiCurrency\Exceptions\InvalidCurrencyException;
use WCPay\MultiCurrency\Exceptions\InvalidCurrencyRateException;
use WCPay\MultiCurrency\Interfaces\MultiCurrencyAccountInterface;
use WCPay\MultiCurrency\Interfaces\MultiCurrencyApiClientInterface;
use WCPay\MultiCurrency\Interfaces\MultiCurrencyCacheInterface;
use WCPay\MultiCurrency\Interfaces\MultiCurrencyLocalizationInterface;
use WCPay\MultiCurrency\Interfaces\MultiCurrencySettingsInterface;
use WCPay\MultiCurrency\Logger;
use WCPay\MultiCurrency\Notes\NoteMultiCurrencyAvailable;
use WCPay\MultiCurrency\Utils;
defined( 'ABSPATH' ) || exit;
/**
* Class that controls Multi-Currency functionality.
*/
class MultiCurrency {
const CURRENCY_SESSION_KEY = 'wcpay_currency';
const CURRENCY_META_KEY = 'wcpay_currency';
const FILTER_PREFIX = 'wcpay_multi_currency_';
const CUSTOMER_CURRENCIES_KEY = 'wcpay_multi_currency_stored_customer_currencies';
/**
* The plugin's ID.
*
* @var string
*/
public $id = 'wcpay_multi_currency';
/**
* Static flag to show if the currencies initialization has been completed
*
* @var bool
*/
protected static $is_initialized = false;
/**
* Compatibility instance.
*
* @var Compatibility
*/
protected $compatibility;
/**
* Geolocation instance.
*
* @var Geolocation
*/
protected $geolocation;
/**
* The Currency Switcher Widget instance.
*
* @var null|CurrencySwitcherWidget
*/
protected $currency_switcher_widget;
/**
* Gutenberg Block implementation of the Currency Switcher Widget instance.
*
* @var CurrencySwitcherBlock
*/
protected $currency_switcher_block;
/**
* Utils instance.
*
* @var Utils
*/
protected $utils;
/**
* FrontendPrices instance.
*
* @var FrontendPrices
*/
protected $frontend_prices;
/**
* FrontendCurrencies instance.
*
* @var FrontendCurrencies
*/
protected $frontend_currencies;
/**
* BackendCurrencies instance.
*
* @var BackendCurrencies
*/
protected $backend_currencies;
/**
* StorefrontIntegration instance.
*
* @var StorefrontIntegration
*/
protected $storefront_integration;
/**
* The available currencies.
*
* @var Currency[]|null
*/
protected $available_currencies;
/**
* The default currency.
*
* @var Currency|null
*/
protected $default_currency;
/**
* The enabled currencies.
*
* @var Currency[]|null
*/
protected $enabled_currencies;
/**
* Instance of MultiCurrencySettingsInterface.
*
* @var MultiCurrencySettingsInterface
*/
private $settings_service;
/**
* Client for making requests to the API
*
* @var MultiCurrencyApiClientInterface
*/
private $payments_api_client;
/**
* Instance of MultiCurrencyAccountInterface.
*
* @var MultiCurrencyAccountInterface
*/
private $payments_account;
/**
* Instance of MultiCurrencyLocalizationInterface.
*
* @var MultiCurrencyLocalizationInterface
*/
private $localization_service;
/**
* Instance of MultiCurrencyCacheInterface.
*
* @var MultiCurrencyCacheInterface
*/
private $cache;
/**
* Tracking instance.
*
* @var Tracking
*/
protected $tracking;
/**
* Simulation variables array.
*
* @var array
*/
protected $simulation_params = [];
/**
* Class constructor.
*
* @param MultiCurrencySettingsInterface $settings_service Settings service.
* @param MultiCurrencyApiClientInterface $payments_api_client Payments API client.
* @param MultiCurrencyAccountInterface $payments_account Payments Account instance.
* @param MultiCurrencyLocalizationInterface $localization_service Localization Service instance.
* @param MultiCurrencyCacheInterface $cache Cache instance.
* @param Utils|null $utils Optional Utils instance.
*/
public function __construct( MultiCurrencySettingsInterface $settings_service, MultiCurrencyApiClientInterface $payments_api_client, MultiCurrencyAccountInterface $payments_account, MultiCurrencyLocalizationInterface $localization_service, MultiCurrencyCacheInterface $cache, Utils $utils = null ) {
$this->settings_service = $settings_service;
$this->payments_api_client = $payments_api_client;
$this->payments_account = $payments_account;
$this->localization_service = $localization_service;
$this->cache = $cache;
// If a Utils instance is not passed as argument, initialize it. This allows to mock it in tests.
$this->utils = $utils ?? new Utils();
$this->geolocation = new Geolocation( $this->localization_service );
$this->compatibility = new Compatibility( $this, $this->utils );
$this->currency_switcher_block = new CurrencySwitcherBlock( $this, $this->compatibility );
}
/**
* Backwards compatibility for the old `instance()` static method.
*
* We need to use this as some plugins still call `MultiCurrency::instance()` directly.
*
* @return null|MultiCurrency - Main instance.
*/
public static function instance() {
if ( function_exists( 'WC_Payments_Multi_Currency' ) ) {
return WC_Payments_Multi_Currency();
}
}
/**
* Initializes this class' WP hooks.
*
* @return void
*/
public function init_hooks() {
if ( is_admin() && current_user_can( 'manage_woocommerce' ) ) {
add_filter( 'woocommerce_get_settings_pages', [ $this, 'init_settings_pages' ] );
// Enqueue the scripts after the main WC_Payments_Admin does.
add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_scripts' ], 20 );
add_action( 'admin_head', [ $this, 'set_client_format_and_rounding_precision' ] );
}
add_action( 'init', [ $this, 'init' ] );
add_action( 'rest_api_init', [ $this, 'init_rest_api' ] );
add_action( 'widgets_init', [ $this, 'init_widgets' ] );
$is_frontend_request = ! is_admin() && ! defined( 'DOING_CRON' ) && ! Utils::is_admin_api_request();
if ( $is_frontend_request || Utils::is_store_api_request() ) {
// Make sure that this runs after the main init function.
add_action( 'init', [ $this, 'update_selected_currency_by_url' ], 11 );
add_action( 'init', [ $this, 'update_selected_currency_by_geolocation' ], 12 );
add_action( 'init', [ $this, 'possible_simulation_activation' ], 13 );
add_action( 'woocommerce_created_customer', [ $this, 'set_new_customer_currency_meta' ] );
}
if ( ! Utils::is_store_batch_request() && ! Utils::is_store_api_request() && WC()->is_rest_api_request() ) {
if ( isset( $_GET['currency'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
$get_currency_from_query_param = function () {
$currency = sanitize_text_field( wp_unslash( $_GET['currency'] ) ); // phpcs:ignore WordPress.Security.NonceVerification
return strtoupper( $currency );
};
add_filter( self::FILTER_PREFIX . 'override_selected_currency', $get_currency_from_query_param );
} else {
// If the request is a REST API request, ensure we default to the store currency and leave price as-is.
add_filter( self::FILTER_PREFIX . 'should_return_store_currency', '__return_true' );
add_filter( self::FILTER_PREFIX . 'should_convert_product_price', '__return_false' );
$get_default_currency_code = function () {
return $this->get_default_currency()->get_code();
};
add_filter( self::FILTER_PREFIX . 'override_selected_currency', $get_default_currency_code );
}
}
add_filter( 'wcpay_payment_fields_js_config', [ $this, 'add_props_to_wcpay_js_config' ] );
$this->currency_switcher_block->init_hooks();
}
/**
* Called after the WooCommerce session has been initialized. Initialises the available currencies,
* default currency and enabled currencies for the Multi-Currency plugin.
*
* @return void
*/
public function init() {
$store_currency_updated = $this->check_store_currency_for_change();
// If the store currency has been updated, clear the cache to make sure we fetch fresh rates from the server.
if ( $store_currency_updated ) {
$this->clear_cache();
}
$this->initialize_available_currencies();
$this->set_default_currency();
$this->initialize_enabled_currencies();
// If the store currency has been updated, we need to update the notice that will display any manual currencies.
if ( $store_currency_updated ) {
$this->update_manual_rate_currencies_notice_option();
}
$admin_notices = new AdminNotices();
$user_settings = new UserSettings( $this );
new Analytics( $this, $this->settings_service );
$this->frontend_prices = new FrontendPrices( $this, $this->compatibility );
$this->frontend_currencies = new FrontendCurrencies( $this, $this->localization_service, $this->utils, $this->compatibility );
$this->backend_currencies = new BackendCurrencies( $this, $this->localization_service );
$this->tracking = new Tracking( $this );
// Init all of the hooks.
$admin_notices->init_hooks();
$user_settings->init_hooks();
$this->frontend_prices->init_hooks();
$this->frontend_currencies->init_hooks();
$this->backend_currencies->init_hooks();
$this->tracking->init_hooks();
add_action( 'woocommerce_order_refunded', [ $this, 'add_order_meta_on_refund' ], 50, 2 );
// Check to make sure there are enabled currencies, then for Storefront being active, and then load the integration.
$theme = wp_get_theme();
if ( 'storefront' === $theme->get_stylesheet() || 'storefront' === $theme->get_template() ) {
$this->storefront_integration = new StorefrontIntegration( $this );
}
if ( is_admin() ) {
add_action( 'admin_init', [ $this, 'add_woo_admin_notes' ] );
}
// Update the customer currencies option after an order status change.
add_action( 'woocommerce_order_status_changed', [ $this, 'maybe_update_customer_currencies_option' ] );
static::$is_initialized = true;
}
/**
* Initialize the REST API controller.
*
* @return void
*/
public function init_rest_api() {
// Ensures we are not initializing our REST during `rest_preload_api_request`.
// When constructors signature changes, in manual update scenarios we were run into fatals.
// Those fatals are not critical, but it causes hickups in release process as catches unnecessary attention.
if ( function_exists( 'get_current_screen' ) && get_current_screen() ) {
return;
}
$api_controller = new RestController( $this );
$api_controller->register_routes();
}
/**
* Initialize the legacy widgets.
*
* @return void
*/
public function init_widgets() {
// Register the legacy widget.
$this->currency_switcher_widget = new CurrencySwitcherWidget( $this, $this->compatibility );
register_widget( $this->currency_switcher_widget );
}
/**
* Initialize the Settings Pages.
*
* @param array $settings_pages The settings pages.
*
* @return array The new settings pages.
*/
public function init_settings_pages( $settings_pages ): array {
// We don't need to check if the payment provider is connected for the
// Settings page generation on the incoming CLI and async job calls.
if ( ( defined( 'WP_CLI' ) && WP_CLI ) || ( defined( 'WPCOM_JOBS' ) && WPCOM_JOBS ) ) {
return $settings_pages;
}
// Due to autoloader limitations, we shouldn't initiate MCCY settings if the plugin was just upgraded: https://github.com/Automattic/woocommerce-payments/issues/9676.
if ( did_action( 'upgrader_process_complete' ) ) {
return $settings_pages;
}
if ( $this->payments_account->is_provider_connected() ) {
$settings = new Settings( $this );
$settings->init_hooks();
$settings_pages[] = $settings;
} else {
$settings_onboard_cta = new SettingsOnboardCta( $this, $this->payments_account );
$settings_onboard_cta->init_hooks();
$settings_pages[] = $settings_onboard_cta;
}
return $settings_pages;
}
/**
* Load the admin assets.
*
* @return void
*/
public function enqueue_admin_scripts() {
global $current_tab;
// Enqueue the settings JS and CSS only on the WCPay multi-currency settings page.
if ( 'wcpay_multi_currency' !== $current_tab ) {
return;
}
$this->register_admin_scripts();
wp_enqueue_script( 'WCPAY_MULTI_CURRENCY_SETTINGS' );
wp_enqueue_style( 'WCPAY_MULTI_CURRENCY_SETTINGS' );
}
/**
* Add multi-currency specific props to the WCPay JS config.
*
* @param array $config The JS config that will be loaded on the frontend.
*
* @return array The updated JS config.
*/
public function add_props_to_wcpay_js_config( $config ) {
$config['isMultiCurrencyEnabled'] = true;
return $config;
}
/**
* Wipes the cached currency data option, forcing to re-fetch the data from WPCOM.
*
* @return void
*/
public function clear_cache() {
Logger::debug( 'Clearing the cache to force new rates to be fetched from the server.' );
$this->cache->delete( MultiCurrencyCacheInterface::CURRENCIES_KEY );
}
/**
* Gets and caches the data for the currency rates from the server.
* Will be returned as an array with three keys, 'currencies' (the currencies), 'expires' (the expiry time)
* and 'updated' (when this data was fetched from the API).
*
* @return ?array
*/
public function get_cached_currencies() {
$cached_data = $this->cache->get( MultiCurrencyCacheInterface::CURRENCIES_KEY );
// If connection to server cannot be established, or if payment provider is not connected, or if the account is rejected, return expired data or null.
if ( ! $this->payments_api_client->is_server_connected() || ! $this->payments_account->is_provider_connected() || $this->payments_account->is_account_rejected() ) {
return $cached_data ?? null;
}
return $this->cache->get_or_add(
MultiCurrencyCacheInterface::CURRENCIES_KEY,
function () {
try {
$currency_data = $this->payments_api_client->get_currency_rates( strtolower( get_woocommerce_currency() ) );
return [
'currencies' => $currency_data,
'updated' => time(),
];
} catch ( \Exception $e ) {
return null;
}
},
function ( $data ) {
return is_array( $data ) && isset( $data['currencies'], $data['updated'] );
}
);
}
/**
* Returns the Compatibility instance.
*
* @return Compatibility
*/
public function get_compatibility() {
return $this->compatibility;
}
/**
* Returns the Currency Switcher Widget instance.
*
* @return CurrencySwitcherWidget|null
*/
public function get_currency_switcher_widget() {
return $this->currency_switcher_widget;
}
/**
* Returns the FrontendPrices instance.
*
* @return FrontendPrices
*/
public function get_frontend_prices(): FrontendPrices {
return $this->frontend_prices;
}
/**
* Returns the FrontendCurrencies instance.
*
* @return FrontendCurrencies
*/
public function get_frontend_currencies(): FrontendCurrencies {
return $this->frontend_currencies;
}
/**
* Returns the StorefrontIntegration instance.
*
* @return StorefrontIntegration|null
*/
public function get_storefront_integration() {
return $this->storefront_integration;
}
/**
* Generates the switcher widget markup.
*
* @param array $instance The widget's instance settings.
* @param array $args The widget's arguments.
*
* @return string The widget markup.
*/
public function get_switcher_widget_markup( array $instance = [], array $args = [] ): string {
/**
* The spl_object_hash function is used here due to we register the widget with an instance of the widget and
* not the class name of the widget. WordPress core takes the instance and passes it through spl_object_hash
* to get a hash and adds that as the widget's name in the $wp_widget_factory->widgets[] array. In order to
* call the_widget, you need to have the name of the widget, so we get the instance and hash to use.
*/
ob_start();
the_widget(
spl_object_hash( $this->get_currency_switcher_widget() ),
apply_filters( self::FILTER_PREFIX . 'theme_widget_instance', $instance ),
apply_filters( self::FILTER_PREFIX . 'theme_widget_args', $args )
);
return ob_get_clean();
}
/**
* Returns the store's current available, enabled, and default currencies.
*
* @return array
*/
public function get_store_currencies(): array {
return [
'available' => $this->get_available_currencies(),
'enabled' => $this->get_enabled_currencies(),
'default' => $this->get_default_currency(),
];
}
/**
* Gets the currency settings for a single currency.
*
* @param string $currency_code The currency code to get settings for.
*
* @return array The currency's settings.
*
* @throws InvalidCurrencyException
*/
public function get_single_currency_settings( string $currency_code ): array {
// Confirm the currency code is valid before trying to get the settings.
if ( ! array_key_exists( strtoupper( $currency_code ), $this->get_available_currencies() ) ) {
$this->log_and_throw_invalid_currency_exception( __FUNCTION__, $currency_code );
}
$currency_code = strtolower( $currency_code );
return [
'exchange_rate_type' => get_option( 'wcpay_multi_currency_exchange_rate_' . $currency_code, 'automatic' ),
'manual_rate' => get_option( 'wcpay_multi_currency_manual_rate_' . $currency_code, null ),
'price_rounding' => get_option( 'wcpay_multi_currency_price_rounding_' . $currency_code, null ),
'price_charm' => get_option( 'wcpay_multi_currency_price_charm_' . $currency_code, null ),
];
}
/**
* Updates the currency settings for a single currency.
*
* @param string $currency_code The single currency code to be updated.
* @param string $exchange_rate_type The exchange rate type setting.
* @param float $price_rounding The price rounding setting.
* @param float $price_charm The price charm setting.
* @param ?float $manual_rate The manual rate setting, or null.
*
* @return void
*
* @throws InvalidCurrencyException
* @throws InvalidCurrencyRateException
*/
public function update_single_currency_settings( string $currency_code, string $exchange_rate_type, float $price_rounding, float $price_charm, $manual_rate = null ) {
// Confirm the currency code is valid before trying to update the settings.
if ( ! array_key_exists( strtoupper( $currency_code ), $this->get_available_currencies() ) ) {
$this->log_and_throw_invalid_currency_exception( __FUNCTION__, $currency_code );
}
$currency_code = strtolower( $currency_code );
if ( 'manual' === $exchange_rate_type && ! is_null( $manual_rate ) ) {
if ( ! is_numeric( $manual_rate ) || 0 >= $manual_rate ) {
$message = 'Invalid manual currency rate passed to update_single_currency_settings: ' . $manual_rate;
Logger::error( $message );
throw new InvalidCurrencyRateException( esc_html( $message ), 500 );
}
update_option( 'wcpay_multi_currency_manual_rate_' . $currency_code, $manual_rate );
}
update_option( 'wcpay_multi_currency_price_rounding_' . $currency_code, $price_rounding );
update_option( 'wcpay_multi_currency_price_charm_' . $currency_code, $price_charm );
if ( in_array( $exchange_rate_type, [ 'automatic', 'manual' ], true ) ) {
update_option( 'wcpay_multi_currency_exchange_rate_' . $currency_code, esc_attr( $exchange_rate_type ) );
}
}
/**
* Updates the customer currencies option.
*
* @param int $order_id The order ID.
*
* @return void
*/
public function maybe_update_customer_currencies_option( $order_id ) {
$order = wc_get_order( $order_id );
if ( ! $order ) {
return;
}
$currency = strtoupper( $order->get_currency() );
$currencies = self::get_all_customer_currencies();
// Skip if the currency is already in the list.
if ( in_array( $currency, $currencies, true ) ) {
return;
}
$currencies[] = $currency;
update_option( self::CUSTOMER_CURRENCIES_KEY, $currencies );
}
/**
* Gets the currencies available. Initializes it if needed.
*
* @return Currency[] Array of Currency objects.
*/
public function get_available_currencies(): array {
if ( null === $this->available_currencies ) {
$this->init();
}
return $this->available_currencies ?? [];
}
/**
* Gets the store base currency. Initializes it if needed.
*
* @return Currency The store base currency.
*/
public function get_default_currency(): Currency {
if ( null === $this->default_currency ) {
$this->init();
}
return $this->default_currency ?? new Currency( $this->localization_service, get_woocommerce_currency() );
}
/**
* Gets the currently enabled currencies. Initializes it if needed.
*
* @return Currency[] Array of Currency objects.
*/
public function get_enabled_currencies(): array {
if ( null === $this->enabled_currencies ) {
$this->init();
}
return $this->enabled_currencies ?? [];
}
/**
* Sets the enabled currencies for the store.
*
* @param string[] $currencies Array of currency codes to be enabled.
*
* @return void
*
* @throws InvalidCurrencyException
*/
public function set_enabled_currencies( $currencies = [] ) {
// If curriencies is not an array, or if there are no currencies, just exit.
if ( ! is_array( $currencies ) || 0 === count( $currencies ) ) {
return;
}
// Confirm the currencies submitted are available/valid currencies.
$invalid_currencies = array_diff( $currencies, array_keys( $this->get_available_currencies() ) );
if ( 0 < count( $invalid_currencies ) ) {
$this->log_and_throw_invalid_currency_exception( __FUNCTION__, implode( ', ', $invalid_currencies ) );
}
// Get the currencies that were removed before they are updated.
$removed_currencies = array_diff( array_keys( $this->get_enabled_currencies() ), $currencies );
// Update the enabled currencies and reinitialize.
update_option( $this->id . '_enabled_currencies', $currencies );
$this->initialize_enabled_currencies();
Logger::debug(
'Enabled currencies updated: '
. var_export( $currencies, true ) // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export
);
// Now remove the removed currencies settings.
if ( 0 < count( $removed_currencies ) ) {
$this->remove_currencies_settings( $removed_currencies );
}
}
/**
* Gets the user selected currency, or `$default_currency` if is not set.
*
* @return Currency
*/
public function get_selected_currency(): Currency {
$multi_currency_code = $this->compatibility->override_selected_currency();
$currency_code = $multi_currency_code ? $multi_currency_code : $this->get_stored_currency_code();
return $this->get_enabled_currencies()[ $currency_code ] ?? $this->get_default_currency();
}
/**
* Update the selected currency from a currency code.
*
* @param string $currency_code Three letter currency code.
* @param bool $persist_change Set true to store the change in the session cookie if it doesn't exist yet.
*
* @return void
*/
public function update_selected_currency( string $currency_code, bool $persist_change = true ) {
$code = strtoupper( $currency_code );
$user_id = get_current_user_id();
$currency = $this->get_enabled_currencies()[ $code ] ?? null;
if ( null === $currency ) {
return;
}
// We discard the cache for the front-end.
$this->frontend_currencies->selected_currency_changed();
// initializing the session (useful for Store API),
// so that the selected currency (set as query string parameter) can be correctly set.
if ( ! isset( WC()->session ) ) {
WC()->initialize_session();
}
if ( 0 === $user_id && WC()->session ) {
WC()->session->set( self::CURRENCY_SESSION_KEY, $currency->get_code() );
// Set the session cookie if is not yet to persist the selected currency.
if ( ! WC()->session->has_session() && ! headers_sent() && $persist_change ) {
$this->utils->set_customer_session_cookie( true );
}
} elseif ( $user_id ) {
update_user_meta( $user_id, self::CURRENCY_META_KEY, $currency->get_code() );
}
// Recalculate cart when currency changes.
if ( did_action( 'wp_loaded' ) ) {
$this->recalculate_cart();
} else {
add_action( 'wp_loaded', [ $this, 'recalculate_cart' ] );
}
}
/**
* Update the selected currency from url param `currency`.
*
* @return void
*/
public function update_selected_currency_by_url() {
if ( ! isset( $_GET['currency'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
return;
}
$this->update_selected_currency( sanitize_text_field( wp_unslash( $_GET['currency'] ) ) ); // phpcs:ignore WordPress.Security.NonceVerification
}
/**
* Update the selected currency from the user's geolocation country.
*
* @return void
*/
public function update_selected_currency_by_geolocation() {
// We only want to automatically set the currency if the option is enabled and it shouldn't be disabled for any reason.
if ( ! $this->is_using_auto_currency_switching() || $this->compatibility->should_disable_currency_switching() ) {
return;
}
// Display notice, prevent duplicates in simulation.
if ( ! has_action( 'wp_footer', [ $this, 'display_geolocation_currency_update_notice' ] ) ) {
add_action( 'wp_footer', [ $this, 'display_geolocation_currency_update_notice' ] );
}
// Update currency only if it's already not set.
if ( $this->get_stored_currency_code() ) {
return;
}
$currency = $this->geolocation->get_currency_by_customer_location();
if ( empty( $this->get_enabled_currencies()[ $currency ] ) ) {
return;
}
$this->update_selected_currency( $currency, false );
}
/**
* Gets the configured value for apply charm pricing only to products.
*
* @return mixed The configured value.
*/
public function get_apply_charm_only_to_products() {
return apply_filters( self::FILTER_PREFIX . 'apply_charm_only_to_products', true );
}
/**
* Gets the converted price using the current currency with the rounding and charm pricing settings.
*
* @param mixed $price The price to be converted.
* @param string $type The type of price being converted. One of 'product', 'shipping', 'tax', 'coupon', or 'exchange_rate'.
*
* @return float The converted price.
*/
public function get_price( $price, string $type ): float {
$supported_types = [ 'product', 'shipping', 'tax', 'coupon', 'exchange_rate' ];
$currency = $this->get_selected_currency();
if ( ! in_array( $type, $supported_types, true ) || $currency->get_is_default() ) {
return (float) $price;
}
$converted_price = ( (float) $price ) * $currency->get_rate();
if ( 'tax' === $type || 'coupon' === $type || 'exchange_rate' === $type ) {
return $converted_price;
}
$charm_compatible_types = [ 'product', 'shipping' ];
$apply_charm_pricing = $this->get_apply_charm_only_to_products()
? 'product' === $type
: in_array( $type, $charm_compatible_types, true );
return $this->get_adjusted_price( $converted_price, $apply_charm_pricing, $currency );
}
/**
* Gets a raw converted amount based on the amount and currency codes passed.
* This is a helper method for external conversions, if needed.
*
* @param float $amount The amount to be converted.
* @param string $to_currency The 3 letter currency code to convert the amount to.
* @param string $from_currency The 3 letter currency code to convert the amount from.
*
* @return float The converted amount.
*
* @throws InvalidCurrencyException
* @throws InvalidCurrencyRateException
*/
public function get_raw_conversion( float $amount, string $to_currency, string $from_currency = '' ): float {
$enabled_currencies = $this->get_enabled_currencies();
// If the from_currency is not set, use the store currency.
if ( '' === $from_currency ) {
$from_currency = $this->get_default_currency()->get_code();
}
// We throw an exception if either of the currencies are not enabled.
$to_currency = strtoupper( $to_currency );
$from_currency = strtoupper( $from_currency );
foreach ( [ $to_currency, $from_currency ] as $code ) {
if ( ! isset( $enabled_currencies[ $code ] ) ) {
$this->log_and_throw_invalid_currency_exception( __FUNCTION__, $code );
}
}
// Get the rates.
$to_currency_rate = $enabled_currencies[ $to_currency ]->get_rate();
$from_currency_rate = $enabled_currencies[ $from_currency ]->get_rate();
// Throw an exception in case from_currency_rate is less than or equal to 0.
if ( 0 >= $from_currency_rate ) {
$message = 'Invalid rate for from_currency in get_raw_conversion: ' . $from_currency_rate;
Logger::error( $message );
throw new InvalidCurrencyRateException( esc_html( $message ), 500 );
}
$amount = $amount * ( $to_currency_rate / $from_currency_rate );
return (float) $amount;
}
/**
* Recalculates WooCommerce cart totals.
*
* @return void
*/
public function recalculate_cart() {
if ( WC()->cart ) {
WC()->cart->calculate_totals();
}
}
/**
* When an order is refunded, a new psuedo order is created to represent the refund.
* We want to check if the original order was a multi-currency order, and if so, copy the meta data
* to the new order.
*
* @param int $order_id The order ID.
* @param int $refund_id The refund order ID.
*/
public function add_order_meta_on_refund( $order_id, $refund_id ) {
$default_currency = $this->get_default_currency();
$order = wc_get_order( $order_id );
$refund = wc_get_order( $refund_id );
// Do not add exchange rate if order was made in the store's default currency.
if ( ! $order || ! $refund || $default_currency->get_code() === $order->get_currency() ) {
return;
}
$order_exchange_rate = $order->get_meta( '_wcpay_multi_currency_order_exchange_rate', true );
$stripe_exchange_rate = $order->get_meta( '_wcpay_multi_currency_stripe_exchange_rate', true );
$order_default_currency = $order->get_meta( '_wcpay_multi_currency_order_default_currency', true );
$refund->update_meta_data( '_wcpay_multi_currency_order_exchange_rate', $order_exchange_rate );
$refund->update_meta_data( '_wcpay_multi_currency_order_default_currency', $order_default_currency );
if ( $stripe_exchange_rate ) {
$refund->update_meta_data( '_wcpay_multi_currency_stripe_exchange_rate', $stripe_exchange_rate );
}
$refund->save_meta_data();
}
/**
* Displays a notice on the frontend informing the customer of the
* automatic currency switch.
*/
public function display_geolocation_currency_update_notice() {
$current_currency = $this->get_selected_currency();
$store_currency = get_option( 'woocommerce_currency' );
$country = $this->geolocation->get_country_by_customer_location();
$geolocated_currency = $this->geolocation->get_currency_by_customer_location();
$currencies = get_woocommerce_currencies();
// Don't run next checks if simulation is enabled.
if ( ! $this->is_simulation_enabled() ) {
// Do not display notice if using the store's default currency.
if ( $store_currency === $current_currency->get_code() ) {
return;
}
// Do not display notice for other currencies than geolocated.
if ( $current_currency->get_code() !== $geolocated_currency ) {
return;
}
}
$message = sprintf(
/* translators: %1 User's country, %2 Selected currency name, %3 Default store currency name, %4 Link to switch currency */
__( 'We noticed you\'re visiting from %1$s. We\'ve updated our prices to %2$s for your shopping convenience. <a href="%4$s">Use %3$s instead.</a>', 'woocommerce-payments' ),
apply_filters( self::FILTER_PREFIX . 'override_notice_country', WC()->countries->countries[ $country ] ),
apply_filters( self::FILTER_PREFIX . 'override_notice_currency_name', $current_currency->get_name() ),
esc_html( $currencies[ $store_currency ] ),
esc_url( '?currency=' . $store_currency )
);
$notice_id = md5( $message );
echo '<p class="woocommerce-store-notice demo_store" data-notice-id="' . esc_attr( $notice_id . 2 ) . '" style="display:none;">';
// No need to escape here as the contents of $message is already escaped.
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
echo $message;
echo ' <a href="#" class="woocommerce-store-notice__dismiss-link">' . esc_html__( 'Dismiss', 'woocommerce-payments' ) . '</a></p>';
}
/**
* Sets a new customer's currency meta to what's in their session.
* This is needed for when a new user/customer is created during the checkout process.
*
* @param int $customer_id The user/customer id.
*
* @return void
*/
public function set_new_customer_currency_meta( $customer_id ) {
$code = 0 !== $customer_id && WC()->session ? WC()->session->get( self::CURRENCY_SESSION_KEY ) : false;
if ( $code ) {
update_user_meta( $customer_id, self::CURRENCY_META_KEY, $code );
}
}
/**
* Adds Multi-Currency notes to the WC-Admin inbox.
*
* @return void
*/
public function add_woo_admin_notes() {
// Do not try to add notes on ajax requests to improve their performance.