Magento Multisite Domain Switching – Automatically Switch Customers to Different Website

customermagento-1.7session

In a multi-site instance where each website is assigned specific domain name, I currently have a requirement to automatically switch customers to specific website. Please see example scenarios below…

Customer_A is in USA
Customer_B is in France

Here are three websites in the multi-site..
Website_1 (website.com)
Website_2 (website.com.au)
Website_3 (website.fr)

So if customer_A visits ‘website.com.au’, I want to automatically redirect him/her to ‘website.com’ while preserving his/her session.

Similarly if customer_B visits ‘website.com’, I want to automatically redirect him/her to ‘website.fr’ while preserving his/her session.

I’m able to detect and automatically reassign some locale parameters such as currency, language and store but the main challenge is where/when/how to redirect between websites while preserving customer session.

The multisite is set up without separate folders – as in here… https://www.magentocommerce.com/knowledge-base/entry/tutorial-multi-site-multi-domain-setup

Thanks for your help.

Best Answer

First you need to find a way to identify "preferred" website of the customer. The one you need to redirect to.
You can do that by adding a dropdown customer attribute that has options the websites, or use the customer attribute website_id.
Let's use the website_id attribute for now.

You need an observer on the event controller_action_predispatch for frontend. This is dispatched for every page.
Your observer method should look something like this:

public function redirectToPrefferedStore($observer){
    $customer = Mage::getSingleton('customer/session')->getCustomer();
    if (!$customer->getId()) { //if the customer is not logged in, do nothing
        return $this;
    }
    $wesbiteId = $customer->getWebsiteId(); 
    //if the customer is associated to the admin website he should not even be able to login
    //but let's be paranoid and do stop it here in case he was able to login by some magic.
    if ($websiteId == 0) {
        return $this;
    }
    //get the website object
    $website = Mage::getModel('core/website')->load($websiteId);
    //if the website does not exist anymore do nothing
    if (!$website->getId()){ 
        return $this;
    }
    //get the website default store view
    $store = $website->getDefaultStore();
    //redirect to store view
    //you can replace the first parameter of the getUrl with a specific page. `customer/account` for example 
    $url = Mage::getUrl('', array('_store'=>$store->getId()));
    //set the redirect
    Mage::app()->getResponse()->setRedirect($url);
    return $this;
}

Now all you need to do is to allow the customers to keep the session between sites.
You can do that from System->Configuration->Web->Session Validation Settings. Set the field Use SID on Frontend to Yes.
Save and clear the cache just in case.

Related Topic