magento 2 : Get country from IP address

The question:

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?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Use below code:

    protected $logger;

    protected $objectManager;

    protected $_curl;

    public function __construct(
    PsrLogLoggerInterface $logger, 
    MagentoFrameworkObjectManagerInterface $objectManager,
    MagentoFrameworkHTTPClientCurl $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('MagentoFrameworkHTTPPhpEnvironmentRemoteAddress');
        return $remoteAddress->getRemoteAddress();
    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment