Magento 2基于国家/地区的默认货币

问题描述

在我的网站上,我有2种货币和用户可以使用的货币。一个是美元,另一个是里亚尔。认货币为USD。在我们的徽标附近有一个下拉菜单,客户可以在其中将货币更改为Riyal和USD。认选项为美元

我想要的是,从沙特阿拉伯访问我们网站的任何客户,我们都必须向他们显示所有其他国家的里亚尔汇率,我们必须向他们显示美元库里尼。

我该怎么做?请帮忙。

解决方法

为此,您需要从$ _SERVER ['REMOTE_ADDR']中检查IP,并从MaxMind的GeoIP2数据库(https://dev.maxmind.com/geoip/geoip2/geolite2/)中找到国家/地区代码。

参考:https://www.w3resource.com/php-exercises/php-basic-exercise-5.php

之后,您需要在app / code / your_vendor / your_module / etc / frontend / events.xml中的模块中使用事件观察器controller_action_predispatch

 <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/events.xsd">
        <event name="controller_action_predispatch">
            <observer name="currency_init_for_country" instance="your_vendor\your_module\Observer\PreDispatchObserver" shared="false" />
        </event>
    </config>

需要在your_vendor \ your_module \ Observer \ PreDispatchObserver.php文件中添加:

<?php

namespace your_vendor\your_module\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class PreDispatchObserver implements ObserverInterface
{
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    private $storeManager;

    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager
    ) {
        $this->storeManager = $storeManager;
    }

    /**
     * @inheritDoc
     */
    public function execute(Observer $observer)
    {
        // logic for taking current country from $_SERVER['REMOTE_ADDR'] and checking from maxmind database and find the country code.then you can add a if else condition for currecny here based on country code.
        $currency = 'USD';

        if ($this->getStoreCurrency() !== $currency) {
            $this->storeManager->getStore()->setCurrentCurrencyCode($currency);
        }
    }

    private function getStoreCurrency()
    {
        return $this->storeManager->getStore()->getCurrentCurrencyCode();
    }
}