In magento2 how to change store according to country using geoip location..
1 Answer
Create an event in:
Vendor/Module/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='store_redirect_location_based' instance='Vendor\Module\Observer\Redirect' />
</event>
</config>
Then create a php class:
Vendor/Module/Observer/Redirect.php
<?php
namespace Vendor\Module\Observer;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\HTTP\Client\Curl;
use Magento\Framework\Session\SessionManagerInterface;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
class Redirect implements ObserverInterface
{
protected $storeManager;
protected $curl;
protected $session;
protected $remoteAddress;
public function __construct(
StoreManagerInterface $storeManager,
Curl $curl,
SessionManagerInterface $session,
RemoteAddress $remoteAddress
) {
$this->storeManager = $storeManager;
$this->curl = $curl;
$this->session = $session;
$this->remoteAddress = $remoteAddress;
}
public function execute(Observer $observer)
{
$redirectStore = $this->session->getCustomRedirection();
if(!($redirectStore)){
$visitorIp = $this->getVisitorIp();
$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 == 'IN'){
$redirectionUrl = $baseUrl."stores/store/redirect/?___store=english_in";
$this->session->setCustomRedirection(true);
$observer->getControllerAction()->getResponse()->setRedirect($redirectionUrl);
}
}
}
public function getVisitorIp()
{
$remoteAddress = $this->remoteAddress->getRemoteAddress();
return $remoteAddress;
}
}