Using GeoIP in Magento. Store switcher based on customer location

There is no doubt that determining customers location can be quite useful. However, Magento doesn’t have such functionality so far. In this post we decided to show you an example of GeoIP integration into Magento. Moreover, we will use customer location for redirection to a proper store.

Actually, GeoIP integration is already done by Tim Bezhashvyly in GeoIP extension. It connects MaxMind’s GeoIP Lite database to Magento. That is why let’s start from installing it – we prefer to use Modman for installation:

modman clone https://github.com/tim-bezhashvyly/Sandfox_GeoIP

Now, you should have an option to synchronize IP database under System Configuration->General->Countries Options:

GeoIP database synchronisation settings

Note that extension is not doing anything itself, but it has some useful methods implemented which we will use later.

Let’s imagine that we have three different stores: English, French, German (like in fresh Magento installation with sample data). And our goal is to redirect a customer automatically to a specific store, basing on his location.

So, create own module, in our case, it is Atwix_Ipstoreswitcher and then create the helper class. Here we define a method that uses country to store relation to return a store view name:

/* app/code/local/Atwix/Ipstoreswitcher/Helper/Data.php */
class Atwix_Ipstoreswitcher_Helper_Data extends Mage_Core_Helper_Abstract
{
    const DEFAULT_STORE = 'English';

    /**
     * countries to store relation
     * default is English
     * @var array
     */
    protected $_countryToStore = array(
        'FR' => 'French',
        'BE' => 'French',
        'CH' => 'French',
        'DE' => 'German',
        'AT' => 'German',
        'UK' => 'English',
        'US' => 'English',
        'UA' => 'English',
        'CN' => 'English',
        'JP' => 'English'
    );

    /**
     * get store view name by country
     * @param $country
     * @return bool
     */
    public function getStoreByCountry($country)
    {
        if (isset($this->_countryToStore[$country])) {
            return $this->_countryToStore[$country];
        }
        return self::DEFAULT_STORE;
    }
}

We still want to let the customers choose the store they want, so we will redirect a customer only on the first visit. And we are going to use cookies for this purpose. Therefore, create an observer for controller_action_postdispatch event:

<?xml version="1.0"?>
<!--app/code/local/Atwix/Ipstoreswitcher/etc/config.xml-->        
<config>
 ...
    <global>
    ...
    </global>
    <frontend>
        <events>
            <controller_action_postdispatch>
                <observers>
                    <atwix_ipstoreswitcher>
                        <class>atwix_ipstoreswitcher/observer</class>
                        <method>controllerActionPostdispatch</method>
                    </atwix_ipstoreswitcher>
                </observers>
            </controller_action_postdispatch>
        </events>
    </frontend>
</config>
/* app/code/local/Atwix/Ipstoreswitcher/Model/Observer.php */

class Atwix_Ipstoreswitcher_Model_Observer
{
    /**
     * redirects customer to store view based on GeoIP
     * @param $event
     */
    public function controllerActionPostdispatch($event)
    {
        $cookie = Mage::getSingleton('core/cookie');
        if ($cookie->get('geoip_processed') != 1) {
            $geoIPCountry = Mage::getSingleton('geoip/country');
            $countryCode = $geoIPCountry->getCountry();
            if ($countryCode) {
                $storeName = Mage::helper('atwix_ipstoreswitcher')->getStoreByCountry($countryCode);
                if ($storeName) {
                    $store = Mage::getModel('core/store')->load($storeName, 'name');
                    if ($store->getName() != Mage::app()->getStore()->getName()) {
                        $event->getControllerAction()->getResponse()->setRedirect($store->getCurrentUrl(false));
                    }
                }
            }
            $cookie->set('geoip_processed', '1', time() + 86400, '/');
        }
    }
}

As you can see, in controllerActionPostdispatch method first of all we check if a customer hasn’t been already redirected, then determine country by IP, check country to store relation and redirect to a store if it is not the current store. Finally, we set cookie to prevent further checks.

That is it, we are ready to make a test and ensure that it works. Also, the complete code you can find on GitHub. You are welcome to share your experience with GeoIP in the comments below.

You may also want to read: