Magento Multiple Website Store – Login

In this tutorial, we will see how to setup common login in a magento multiple website setup.

Problem Case:

The problem we are trying to solve here is, suppose you have multiple magento website setup on different domains on the same magento instance, and you want that if a customer login’s on any one our your site he is gets logged into all other sites as well.

Solution:

The solution for this is simple, whenever a user logs in on a website ‘A’, a script needs to notify website ‘B’,'C’, etc that user has logged in and then login needs to be performed in ‘B’,'C’, etc as well. This cannot be handled automatically because session is not shared across domains so this feature is not there by default. The solution for this is to use JSONP and perform a cross domain ajax request with the session id so that session gets shared accross domains.
Attached is the source code of the module
Module Name: Multiple Website Login

Implementation

First Step: Magento has a default configuration option called Share Customer Accounts located at System -> Configuration -> Customer Configuration -> Account Sharing Options, change this to Global. What this means is that when a customer creates his new account, is shared for all your websites.
Second Step:
Next we need to write code to make the JSONP calls. We are using JSONP, since normal cross domain ajax calls are not allowed. For this we are using JQuery library , details of JSONP can be found here.

So below is the codes:

Step1: Include jQuery in Magento

First download jQuery and then place it inside /js/jquery folder, so path would be /js/jquery/jquery.js. Next create a javascript file called noconflict.js in the jquery folder (/js/jquery/noconflict.js) jQuery Folder Structure. Write this code inside noconflict.js file

jQuery.noConflict();

Next open that page.xml layout file in your theme folder [app/design/frontend/default/YOUR_THEME/layout/page.xml or in your default magento theme] and place this code inside tag

<reference name="head">
        	<action method="addItem"><type>js</type><name>jquery/jquery-1.6.4.min.js</name></action>
        	<action method="addItem"><type>js</type><name>jquery/noconflict.js</name></action>
</reference>

Now open home page in your magento, and through firebug or chrome inspector, see if these two jquery files are included in your page.

Step2: Crossdomain ajax call

Next we need to write ajax call. The code for this should be written in header.phtml. You need to rewrite the base header.phtml in your theme [app/design/frontend/default/YOUR_THEME/page/html/header.phtml]
Here’s the added code for header.phtml

<?php
$allStores=Mage::app()->getStores(); //get list of all stores,websites
	
	foreach ($allStores as $_eachStoreId => $val)
	  {
		$_storeId = Mage::app()->getStore($_eachStoreId)->getId();
		 $urls= Mage::app()->getStore($_storeId)->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB); //get url using store id
		
		 $cururl=Mage::getStoreConfig('web/unsecure/base_url'); //get current domain url
		if($cururl!=$urls)
		{ 
			 $url=$urls;
			
		 if ($this->helper('customer')->isLoggedIn()){
		  if(Mage::getSingleton('core/session')->getLogincd()==1){ ?>
			<script type="text/javascript">
			jQuery(document).ready(function() {
			var url="<?php echo $url;?>customer/account/logincd?SID=";
			
			url = url+'<?php echo Mage::getModel("core/session")->getEncryptedSessionId(); ?>'+"&callback=?";
			var userid=<?php echo Mage::getSingleton('customer/session')->getCustomer()->getId();?>;
			jQuery.ajax({
			url: url,
			crossDomain: true,
			dataType: 'jsonp',
			success: function(data) {
				//console.log("success");
			}
			});
		});
		</script>
		<?php 
		
		}
		Mage::getSingleton('core/session')->setLogincd(0);
		 }else{
		Mage::getSingleton('core/session')->setLogincd(1);
		 }
		}
	
	}

	?>

Here first we are getting all stores, then in a foreach loop we are getting the domain url of each store. Then we are checking if the current domain is not equal to the fetched url. Then we perform the jsonp call which will go to the other domain logincd Action and login the customer on the other domain. For this we are sharing the customer session id i.e. SID with other domains. We get the session id of the logged in customer with the code

Mage::getModel("core/session")->getEncryptedSessionId();

We are appending session id in the url and this will be set in other domain and the customer will be logged in.
Now let us see how ‘jsonp’ request is different from normal ajax request.

 url: "http://domain1.excellencetenchnologies.co.in/logincd/?SID=hjdsk3242shjhs&callback=?",

In this line we we are appending the session id of the customer session of the current domain, and a ‘callback’ parameter which will be generated by jQuery.
It is a unique callback name for this request (something like json1268267816). It will be received at the other domain and it will treat the request as jsonp.

Mage::getSingleton(‘core/session’)->getLogincd() parameter is set so that this jsonp call is done only once and not every time a page is opened.

Step3: Overwrite the AccountController.php of Mage/Customer/controllers/

Next we need to overwrite AccountController.php file in our module [app/code/local/YOUR_NAMESPACE/MODULE_NAME/controllers/AccountController.php]. The AccountController.php file will have an action ‘logincd’ which will receive the ajax call and then do all the work required to make customer login in the domain. Here’s the code for AccountController.php

<?php
require_once 'Mage/Customer/controllers/AccountController.php';
	
class Excellence_Logincd_AccountController extends Mage_Customer_AccountController
{
    public function logincdAction()
    {
	$this->getResponse()->setHeader('Content-Type', 'application/json; charset=utf-8');
       	$data = array('success'=>1);
    	echo $_GET['callback'] . '('.json_encode($data).')';
     }
   
}

This line designates the content to be in json format, encoded in the UTF-8 character encoding.

this->getResponse()->setHeader('Content-Type', 'application/json; charset=utf-8');

And then the success message has been set and sent back to the calling function.

echo $_GET['callback'] . '('.json_encode($data).')';

this will send back the response to the requesting ajax call as jsonp.




This is all that is required to make cross domain login work. The cross domain logout will work automatically in the current case.

  • jaimin

    Thanks manish,
    excellent post once again and really very glad to see you after very long time.we are eagerly waiting for your new post.

    • Manish Prakash

      Thanks Jaimin. I will be coming soon with more interesting posts..

  • Shawn

    Hi Manish,

    really excited to see your new blog after very long
    long time, hope there is more coming soon, ^.^. again, appreciate your
    effort.

  • http://www.facebook.com/hugues.masy Hugues Masy

    Many Thanks Manish, Once again, it is a great pleasure to read your blog !
    Just a small remark: i
    n the source code file, I did not find the phtml file, nor a “design” folder… ;-)

  • Magento Tutorial

    Hi manish,
    It’s glad to see you come back. your post is so great. Hope to see your next post!

    _______
    http://magentotutorial.net

  • carlosalvet

    Hi, your articles are great! congratulations!, but the problem is that I
    downloaded the example an install in my magento store, then copy the
    code in the header.phtml.

    I be sure it will be working, i have to
    websites (url/default and url/webistes/edomexI, and uncomment the
    consol.log(“success”) and it shows “success” on firebug console
    correctly.

    I log in in default store and when change to edomex store, the edomex store doesn’t log in, and i don’t know why.

  • Archana

    Hello,

    sorry for posting my question, not related to above article. please consider.

    I tried to get article for integration of Bill Me Later in magento
    But i didn’t find any related article not even API integration.
    It would be great if you help for this. or suggest something regarding this so that i can do this.

    I have your module that is custom payment method, but here i don’t have api detail for Bill Me Later .Patel

    So please help as soon as possible..

  • Jed Lagunday

    I got this error when I did the above procedures, I also downloaded the files and apply it to our website: “NetworkError: 404 Not Found – http://IP_ADDRESS/website2_name/customer/account/logincd?SID=ffl3np86tf125c8lrv9opql1m5&callback=jQuery17108839576495694071_1361183466628&_=1361183467539“. Please help. What is causing the error?

    • Jed Lagunday

      Got this error on firebug console after logging in.

    • Jed Lagunday

      Please help I am using Magento 1.7

  • clkurtz

    Excellent job. Thank you very much Manish!