2

How to get the name of the country from the ip address in magento 2. I think it will require me to use geoip, but I don't know how to do it. Any help?

6

Use below code:

    protected $logger;

    protected $objectManager;

    protected $_curl;

    public function __construct(
    \Psr\Log\LoggerInterface $logger, 
    \Magento\Framework\ObjectManagerInterface $objectManager,
    \Magento\Framework\HTTP\Client\Curl $curl) {
        $this->logger = $logger;
        $this->_curl = $curl;
        $this->objectManager = $objectManager;
    }

    public function getCountryName() {
        $visitorIp = $this->getVisitorIp();
        $url = "freegeoip.net/json/".$visitorIp;
        $this->_curl->get($url);
        $response = json_decode($this->_curl->getBody(), true);
        $countryName = $response['country_name'];
        $stateName = $response['region_name'];
       return $stateName;        
    }

    function getVisitorIp() {       
        $remoteAddress = $this->objectManager->create('Magento\Framework\HTTP\PhpEnvironment\RemoteAddress');
        return $remoteAddress->getRemoteAddress();
    }
  • where i need to add this code – Nadh Nov 15 '16 at 9:50
  • need to add this code in observer @Prashant Valanda – Nadh Nov 15 '16 at 9:52
  • @Nadh you can add it in block or where you want – Prashant Valanda Nov 15 '16 at 10:01
  • what is $response['country_name']; – Nadh Nov 15 '16 at 10:10
  • @ Prashant Valanda iam not getting – Nadh Nov 15 '16 at 10:17

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.