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

Magento 2基于国家/地区的默认货币,magento,magento2,magento-1.7,Magento,Magento2,Magento 1.7,在我的网站上,我有两个货币和用户可以。一种是美元,另一种是里亚尔。默认货币为美元。在我们的徽标附近有一个下拉列表,客户可以在其中将货币更改为里亚尔和美元。默认选项为美元 我想要的是,任何从沙特阿拉伯访问我们网站的客户,我们必须向他们展示所有其他国家的里亚尔货币,我们必须向他们展示美元货币 我该怎么做?请提供帮助。对于这项工作,您需要从$\u服务器['REMOTE\u ADDR']检查您的ip,并从MaxMind的GeoIP2数据库()中查找国家代码 参考: 之后,您需要在app/code/you

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

我想要的是,任何从沙特阿拉伯访问我们网站的客户,我们必须向他们展示所有其他国家的里亚尔货币,我们必须向他们展示美元货币


我该怎么做?请提供帮助。

对于这项工作,您需要从$\u服务器['REMOTE\u ADDR']检查您的ip,并从MaxMind的GeoIP2数据库()中查找国家代码

参考:

之后,您需要在app/code/your_vendor/your_module/etc/frontend/events.xml中的模块中使用事件观察者控制器_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\u vendor\your\u 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();
    }
}

我可以将其写入任何其他文件而不是创建新模块吗?请查收。我不想安装任何新模块。新模块不是必需的。我想,你会有一些现有的模块。您只需在etc/frontend/events.xml文件中的任何现有模块中添加事件观察者。此外,如果您的网站被重定向到基于国家的特定网站,那么您也不需要基于ip的数据库搜索。只需要使用$this->\u storeManager->getStore()->getCode()检查当前的网站代码,并相应地设置货币。现在我有了另一个疑问。我为此提出了一个新问题。你能查一下吗