Magento 2 default currency based on country

1.1k Views Asked by At

in my website i have 2 currency & user can. One is USD and other is Riyal. Default currency is USD . There is drop down in near to our logo in which customer can change the currency to Riyal and USD. Default option is USD

What i want is, any customer taking our website from Saudi Arabia we have to show them riyal currency for all other country we have to show them USD Curreny .

How can i do this ? Please help.

1

There are 1 best solutions below

3
Debajit Guha On BEST ANSWER

For this work, you need to check your ip from $_SERVER['REMOTE_ADDR'] and find the country code from MaxMind’s GeoIP2 database(https://dev.maxmind.com/geoip/geoip2/geolite2/).

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

After that, you need to use event observer controller_action_predispatch in your module in app/code/your_vendor/your_module/etc/frontend/events.xml

 <?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>

In the your_vendor\your_module\Observer\PreDispatchObserver.php file you need to add:

<?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();
    }
}