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
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();
}