Question

How to set currency depending on country's IP, means if customer browse my site from us location then the current currecny and language should be USD & en_US or if customer browse my site from Canada location then it should be CAD & en_CA through out the site. My Default Currency is 'USD'.

Is there any free extension in magento 2?

How can i achieve this? Any ideas?

Thanks in advance...!!!

Was it helpful?

Solution

I got my answer following below code:

I have created observer for this.

MagentoDir/Shasha/Geoip/etc/frontend/events.xml

<config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='urn:magento:framework/Event/etc/events.xsd'>
    <event name='controller_action_predispatch'>
        <observer name='Shasha_Geoip_Redirect' instance='Shasha\Geoip\Observer\Redirect' />
    </event>
</config>

MagentoDir/Shasha/Geoip/Observer/Redirect.php

<?php 

namespace Shasha\Geoip\Observer;

use Magento\Framework\Controller\ResultFactory; 

class Redirect implements \Magento\Framework\Event\ObserverInterface
{

    protected $_storeManager;

    protected $_curl;

    protected $_session;

    protected $_objectManager;

    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\HTTP\Client\Curl $curl,
        \Magento\Framework\Session\SessionManagerInterface $session,
        \Magento\Framework\ObjectManagerInterface $objectManager
    ) {
        $this->_storeManager   = $storeManager;
        $this->_curl           = $curl;
        $this->_session        = $session;
        $this->_objectManager  = $objectManager;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $isChangeStore    = $this->_session->getCustomRedirection();
        if(!($isChangeStore)){
            $visitorIp        = $this->getVisitorIp();
            //$visitorIp        = '158.69.121.179';  // for canada
            $baseUrl          = $this->_storeManager->getStore()->getBaseUrl();
            $apiUrl           = "http://www.geoplugin.net/json.gp?ip=".$visitorIp;
            $this->_curl->get($apiUrl);
            $response         = json_decode($this->_curl->getBody(), true);
            $countryCode      = $response['geoplugin_countryCode'];
            if($countryCode != null && $countryCode == 'CA'){
                $redirectionUrl  = $baseUrl."stores/store/redirect/?___store=english_ca&___from_store=us_english"; 
                $this->_session->setCustomRedirection(true);  
                $observer->getControllerAction()->getResponse()->setRedirect($redirectionUrl);
            }
        }
    }

    function getVisitorIp()
    {
        $remoteAddress = $this->_objectManager->create('Magento\Framework\HTTP\PhpEnvironment\RemoteAddress');
        return $remoteAddress->getRemoteAddress();
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top