微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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();
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。