4

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?

1 Answer 1

8

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();
    }
20
  • where i need to add this code
    – User0434
    Commented Nov 15, 2016 at 9:50
  • need to add this code in observer @Prashant Valanda
    – User0434
    Commented Nov 15, 2016 at 9:52
  • @Nadh you can add it in block or where you want Commented Nov 15, 2016 at 10:01
  • what is $response['country_name'];
    – User0434
    Commented Nov 15, 2016 at 10:10
  • @ Prashant Valanda iam not getting
    – User0434
    Commented Nov 15, 2016 at 10:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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