Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

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

Admin settings

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

Backend

Backend helper

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

Frontend helper

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:

<script>
    require(["geolocation"], function(geolocation){
        geolocation.getCountryIso().then(function(countryIso) {
            console.log(countryIso);
        });
    });
</script>

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

  url: graphqlUrl,
  contentType: 'application/json',
  data: JSON.stringify({
      query: '{ countryGeoLocation { countryIso } }',
  }),

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.

  • No labels