AnswerBun.com

Change Magento 2 website based on IP

Magento Asked on January 6, 2022

I have 3 websites in my current Magento installation and are as follows website1 Code: base, website2 Code: au, website3 Code: ca. Each website has one store and one store_view except for website3 which has 2 store-views.

I want the users to be automatically navigated to a specific website based on their country. For example, all users with the country code US to be navigated to website1.

I have checked that ipinfo.io provides country code through an API call as follow

# Get country ISO code as plaintext
$ curl ipinfo.io/8.8.8.8/country?token=$TOKEN
US

Can anyone help with its implementation for my Magento 2.2.6 instance?

One Answer

I've had the same issue, I'm using geoplugin to get the country of my customers ip address. I also have a cookie just in case the customer after being redirected to a store let's say in Portuguese actually prefers to use the English version, I store a value in the cookie so the customer doesn't get redirected back to the Portuguese version. Let me know if you need any further assistance and don't forget to upvote / mark as answer if this solved your problem :)

In your etcevents.xml

<event name="controller_action_postdispatch">
        <observer name="controller_action_postdispatch" instance="VendorModuleObserverPostDespatchEvent" />
    </event>

In your VendorModuleObserverPostDespatchEvent.php

<?php
namespace VendorModuleObserver;

use MagentoFrameworkEventObserverInterface;
use MagentoStoreModelStoreManagerInterface;
use MagentoFrameworkAppHelperAbstractHelper;
use MagentoFrameworkAppConfigScopeConfigInterface;
use MagentoFrameworkStdlibCookieCookieMetadataFactory;
use MagentoFrameworkStdlibCookieManagerInterface;
use MagentoFrameworkSessionSessionManagerInterface;

class PostDespatchEvent implements ObserverInterface
{  

    /**
     * Name of Cookie that holds private content version
     */
    CONST COOKIE_NAME = 'COOKIE_DEFAULT_LANG_CUSTOM';

    /**
     * Cookie life time
     */
    CONST COOKIE_LIFE = 3600;

    /**
     * @var MagentoFrameworkStdlibCookieManagerInterface
     */


    protected $_storeManager;
    protected $cookieManager;
    protected $cookieMetadataFactory;
    private   $scopeConfigInterface;

    protected $checkoutSession;
    protected $cart;
    protected $customerSession;
    
    public function __construct(
        StoreManagerInterface                           $storeManager,
        ScopeConfigInterface                            $scopeConfigInterface,
        CookieManagerInterface                          $cookieManager,
        CookieMetadataFactory                           $cookieMetadataFactory,
        SessionManagerInterface                         $sessionManager,
        MagentoCheckoutModelSession                 $checkoutSession,
        MagentoCheckoutModelCart                    $cart,
        MagentoCustomerModelSession                 $customerSession
        
    ) {
        $this->_storeManager = $storeManager;
        $this->scopeConfigInterface = $scopeConfigInterface;
        $this->cookieManager = $cookieManager;
        $this->cookieMetadataFactory = $cookieMetadataFactory;
        $this->sessionManager = $sessionManager;

        $this->checkoutSession = $checkoutSession;
        $this->cart            = $cart;
        $this->customerSession = $customerSession;
    }

    public function getCookie($name)
    {
        return $this->cookieManager->getCookie($name);
    }
    public function setCookie($value, $duration = 604800)
    {
        $metadata = $this->cookieMetadataFactory
            ->createPublicCookieMetadata()
            ->setDuration($duration)
            ->setPath($this->sessionManager->getCookiePath())
            ->setDomain($this->sessionManager->getCookieDomain());

        $this->cookieManager->setPublicCookie(self::COOKIE_NAME, $value, $metadata);

    }

    public function execute(MagentoFrameworkEventObserver $observer)
    {

        $cookie = self::getCookie(SELF::COOKIE_NAME);
        if(!isset( $cookie))
        {
            $countryCode = SELF::ip_info("Visitor", "Country Code"); 

            if($countryCode == 'PT')
            {            
                $this->_storeManager->setCurrentStore('default');                
            }
            else
            {
                if($countryCode == 'DE')
                {            
                    $this->_storeManager->setCurrentStore('DE');
                }
                else
                {
                    $this->_storeManager->setCurrentStore('EN');
                }
           }

             self::setCookie( SELF::COOKIE_NAME);
        }
    }

    public static function ip_info($ip = NULL, $purpose = "location", $deep_detect = TRUE) {
        $output = NULL;
        if (filter_var($ip, FILTER_VALIDATE_IP) === FALSE) {
            $ip = $_SERVER["REMOTE_ADDR"];
            if ($deep_detect) {
                if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP))
                    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
                if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP))
                    $ip = $_SERVER['HTTP_CLIENT_IP'];
            }
        }
        $purpose    = str_replace(array("name", "n", "t", " ", "-", "_"), NULL, strtolower(trim($purpose)));
        $support    = array("country", "countrycode", "state", "region", "city", "location", "address");
        $continents = array(
            "AF" => "Africa",
            "AN" => "Antarctica",
            "AS" => "Asia",
            "EU" => "Europe",
            "OC" => "Australia (Oceania)",
            "NA" => "North America",
            "SA" => "South America"
        );
        if (filter_var($ip, FILTER_VALIDATE_IP) && in_array($purpose, $support)) {
            $ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp"));
            if (@strlen(trim($ipdat->geoplugin_countryCode)) == 2) {
                switch ($purpose) {
                    case "location":
                        $output = array(
                            "city"           => @$ipdat->geoplugin_city,
                            "state"          => @$ipdat->geoplugin_regionName,
                            "country"        => @$ipdat->geoplugin_countryName,
                            "country_code"   => @$ipdat->geoplugin_countryCode,
                            "continent"      => @$continents[strtoupper($ipdat->geoplugin_continentCode)],
                            "continent_code" => @$ipdat->geoplugin_continentCode
                        );
                        break;
                    case "address":
                        $address = array($ipdat->geoplugin_countryName);
                        if (@strlen($ipdat->geoplugin_regionName) >= 1)
                            $address[] = $ipdat->geoplugin_regionName;
                        if (@strlen($ipdat->geoplugin_city) >= 1)
                            $address[] = $ipdat->geoplugin_city;
                        $output = implode(", ", array_reverse($address));
                        break;
                    case "city":
                        $output = @$ipdat->geoplugin_city;
                        break;
                    case "state":
                        $output = @$ipdat->geoplugin_regionName;
                        break;
                    case "region":
                        $output = @$ipdat->geoplugin_regionName;
                        break;
                    case "country":
                        $output = @$ipdat->geoplugin_countryName;
                        break;
                    case "countrycode":
                        $output = @$ipdat->geoplugin_countryCode;
                        break;
                }
            }
        }
        return $output;
    }
}


?>

Answered by Joao71 on January 6, 2022

Add your own answers!

Related Questions

Send email to a friend is not working

2  Asked on December 26, 2020 by bineesh

     

How in Block a productcollection of template render?

2  Asked on December 24, 2020 by andrej-wasemiller

     

Magento 2 Sort order on catalogue widget

0  Asked on December 23, 2020 by carter

   

MAC OS Magento 2.4.1. PWA Studio 8.0.0 Local Setup Steps and Bugfix

0  Asked on December 19, 2020 by rishimukesh

   

Overriding Helper

2  Asked on December 19, 2020 by myron

   

Magento emails are not going

1  Asked on December 18, 2020 by user00247

   

Problem with payment,

1  Asked on December 16, 2020 by mariam-todadze

     

Special Price Not Applying in Magento2 Cart

2  Asked on December 14, 2020 by dinesh

       

Ask a Question

Get help from others!

© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP