Geolocation (optional)

https://github.com/magesuite/geolocation

The extension allows getting the current country ISO code based on the user's IP address.

 

Installation

This module is optional.

composer require "creativestyle/magesuite-geolocation" ^1.0.0

This extension requires a custom second extension that contains MaxMind GeoIP2 Country Database file.

We’re not able to provide such an extension because of the file licensing.

Such extension must implement \MageSuite\Geolocation\Model\Asset\DatabasePathResolverInterface interface that returns absolute file path to mmdb file, an example implementation below:

etc/di.xml:

<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <preference for="MageSuite\Geolocation\Model\Asset\DatabasePathResolverInterface" type="MageSuite\GeolocationDatabase\Model\Asset\DatabasePathResolver" /> </config>
<?php namespace MageSuite\GeolocationDatabase\Model\Asset; class DatabasePathResolver implements \MageSuite\Geolocation\Model\Asset\DatabasePathResolverInterface { /** * @inheritDoc */ public function getPath() { return realpath(__DIR__ . '/GeoLite2-Country.mmdb'); } }

Admin settings

There are no admin settings, the module is active when installed.

Backend

If geolocation is needed inside BE logic then \MageSuite\Geolocation\Service\CountryResolverInterface should be injected into class constructor.

It contains resolve method that will return two letter ISO country code of the current user. An empty string will be returned if it is not possible to GeoLocate a user based on his IP address.

A custom IP address can be passed to resolve method, otherwise, IP from server headers will be taken into account.

Frontend

Two-letter ISO country code of a user (or empty string when IP address location was not detected) can be fetched by javascript in the following way:

The frontend script first checks if ISO code is stored in sessionStorage under cachedCountryIso key. if not it makes the following request to graphql:

 

Testing

If you'd like to test integration with 3rd party code you can fake the country returned by the endpoint.

To do so create a cookie named COUNTRY_CODE with ISO code of the expected country as a value.

Keep in mind that javascript library caches returned country code, after each change to the cookie value browser's session storage must be cleared.