2

I want to set currentstore according to geoip of customer.for that i have tried below code:

MagentoDir/app/code/Shasha/Geoip/Observer/Redirect.php

<?php 

namespace Shasha\Geoip\Observer;

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

    protected $_objectManager;

    protected $_storeManager;

    protected $_curl;

    /**
     * @var \Magento\Framework\App\ResponseFactory
     */
    private $responseFactory;

    /**
     * @var \Magento\Framework\UrlInterface
     */
    private $_urlInterface;

    protected $_session;

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

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $isChangeStore    = $this->_session->getCustomRedirection();
        if(!($isChangeStore)){
            $visitorIp    = $this->getVisitorIp();
            $visitorIp        = '158.69.121.179';  // for canada
            $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'){
                $this->_session->setCustomRedirection(true);
                $this->_storeManager->setCurrentStore(2);

            }
        }
    }

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

}

but unfortunately it not works throughout the site it only change on the home page. now i am stuck how can i proceed?

Any helps??

Thanks in advance..!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.