Magento 2, Magento Development, Customization, Extension Development and Integration, Optimization, SEO and Responsive Design

Magento 2, Magento Development, Customization, Extension Development and Integration, Optimization, SEO and Responsive Design

Magento login from external website

I needed a way for a user to login to a Magento shop from an external website. Let's see step by step how to do this.

Magento login from external website

Download code Demo

Step 1:
First off you'll need to create an API user. You can follow this tutorials to create an API user.
Make sure this user has access to at least "Customers->Retrieve customer info".

Step 2:
You'll obviously need a form on your external site for the customer to enter their login details. 
The following is just an example form to give you a rough idea.

Please note: You'll notice I've included an iframe pointing to the shops login page, this is important as it will create the required cookies for the customer to login. If you don't include this iframe any customer who is missing the required cookies won't be logged in.

Step 3:
We need create login page into external site, from where user can enter their login details to login to Magento site. Let's create a php file (externalLogin.php) for external site. Add following code to externalLogin.php file.

<iframe src="http://www.demo.com/customer/account/login/" style="position:absolute;height:1px;width:1px;top:-100px;left:-100px;"></iframe>
<form action="http://www.demo.com/externallogincheck.php" method="post">
    <div class="login_field">
        <label for="login_username">Username</label>
        <input id="login_username" type="text" value="" name="login[username]" />
    </div>
    <div class="login_field">
        <label for="login_password">Password</label>
        <input id="login_password" type="password" value="" name="login[password]" />
    </div>
    <div class="login_field">
        <input type="submit" value="Buy selected product" />
    </div>
</form>

Note: Change www.demo.com with your magento site url. Put this file in root of your external site.

Step 4:
Now we need to add a php file to magento root to check the details user posted from external site with above code is valid or not. Add a php file (externallogincheck.php) to root of your magento site and add following code.

function validatePassword($password, $hash) {
    $hashArr = explode(':', $hash);
    switch(count($hashArr)) {
        case 1:
            return md5($password) === $hash;
        case 2:
            return md5($hashArr[1].$password) === $hashArr[0];
    }
    return false;
}
$apiUrl = 'http://www.demo.com/api/?wsdl';
$apiUser = 'YOUR API USER';
$apiKey = 'API PASSWORD';
 
if(isset($_POST['login'])) {
    try {
        $client = new SoapClient($apiUrl);
        $session = $client->login($apiUser, $apiKey);
    } catch (Exception $e) {
        echo $e;
        exit;
    }
    
    
    //Lookup customer record
    list($customer) = $client->call(
        $session,
        'customer.list',
        array(
            array(
                'email' => addslashes($_POST['login']['username'])
            )
        )
    );
    if(is_array($customer)) {
        if(validatePassword($_POST['login']['password'], $customer['password_hash'])) {
            
            require_once 'app/Mage.php';
            umask(0);
            Mage::app()->setCurrentStore('default');

            Mage::getSingleton("core/session", array("name" => "frontend"));
            $session = Mage::getSingleton("customer/session");

            //Log out any existing sessions
            if(!$session->isLoggedIn()) {
                $session->logout();
            }
   
            //Log user in
            $login = Mage::getSingleton('core/app')->getRequest()->getPost('login');
            $session->login($login['username'], $login['password']);

            header('Location: http://www.demo.com/');
            exit;
            
            exit;
        } else {
            header('Location: http://www.externalsite.com/externalLogin.php?ref=invalid');
            exit;
        }
    } 
    else {
            header('Location: http://www.externalsite.com/externalLogin.php?ref=invalid');
            exit;
    }
}

Note: Change www.demo.com with your magento site url and www.externalsite.com with your external site url. Put this file in root of your magento site.

Download code Demo

Please support us, Like us on Facebook.

  1. Your post urges me to create a business website, of course I will free download magento as soon as possible. Magento is truly the best platform ever. Its extensions is also awesome. Thank you.

    ReplyDelete
  2. Very Nice Posting thanks for sharing. i waiting for your next posting.

    ASP.NET MVC3 Development | Magento Extension Development Company

    ReplyDelete
  3. I am looking for a plugin to enable social login and sharing at my magento webstore
    Magento Store Permissions

    ReplyDelete
  4. I am looking for External login and automatic login to magento website to. I downloaded the above mentioned code, looks fine but i am not able to implement. Can you please how lookup customer records work. In my case it is checking only upto api user login.

    ReplyDelete
  5. I am looking for external magento login and auto login in magento to. Above mentioned demo looks fine for the requirement but when I tried not able to login, redirecting and it is just showing white page. When i tried to debug I am not getting customer array lookup records how to solve this.
    Thank You for the above post. Awaiting for the reply.

    ReplyDelete
    Replies
    1. Hello,
      Did you check all step and also you need to create API user.
      Make sure this user has access to at least "Customers->Retrieve customer info".

      Delete
    2. Thank you for the post, finally started working after this modification: $apiUrl = 'http://www.demo.com/index.php/api/?wsdl';

      I am using customer approval extension for magento (https://github.com/Vinai/customer-activation). Afer registration admin needs to approve then only user will be able to login. If I do login from external site even if customer is not activated then also able to login magento. How to validate this and use extension for external login?

      Delete
    3. You need to prevent observer in that extension.
      I didn't checked in details but perhaps you may check in observer file of that extension.

      Delete
    4. Thank You for the reply.
      I have already gone through that file. But I am not getting how to make the condition so that the external login will validate for customer approval. Can you help me to make the solution.

      Delete
    5. Hello Hardik,

      I figured out the customer approval issue, validate customer details and proceed for login.

      But again I am facing one more issue with the login to mutli store:
      External login is working fine but only with default store. I tried to modify this Mage::app()->setCurrentStore('default') with Mage::app()->setCurrentStore('storeview2'), I am able to login and show user as logged in magento website only for first time in private window(incognito window to login) without any issues, means I have to login in fresh page without any cache then only first login will work after that no.

      Let me know, if any other things I have to add to make login for multi website from external site.

      Delete
    6. Try to set your store like
      Mage::app()->setCurrentStore($store_id);
      May be it can help you.

      Thanks,

      Delete
    7. Thank You for the reply.
      I already did but no result. Same issue facing here also (Login for first no isssues, if I do logout and login then customer is not logged in magento).

      I added below mentioned code:
      $store_id = '2';
      Mage::app()->setCurrentStore($store_id);

      Let me know, if any other changes to solve.

      Delete
    8. Hardik,
      One more thing I found: Login to magento from external site and Try login again from external site then this particular login is making logout the previous login.

      Delete
    9. You can add check to prevent login if customer is already logged in.
      Just get logged in user email and check if email is same with new login email. If so just redirect to mangeto site without being login.

      Delete
    10. But Hardik, Even if we do logout and trying to login again then also same issue. I think it's not because of existing session. I am not sure. Can you also please check from your end?
      But for default store there is no issue only for multi store.

      Delete
    11. Hello Hardik,
      I added a check to prevent login if customer is already logged in.
      There is one more case where I am facing same issue: after login do logout and try login again from external site (here user is not logged in because of existing cookie ,if I delete that particular cookie from browser and login then no issues).

      Login to magento website without deleting cookie also works. (issue only from external site)

      These steps are working for multi store:
      1. Login(External / Magento) and Do logout.
      2. Delete cookie from browser.
      3. Login again from external site.

      So I tried deleting cookie from extenallogincheck.php file like this (able to get default store cookie path but not multi store ):
      $cookies = Mage::getModel('core/cookie')->get();
      foreach($cookies as $cookie) {
      $name = Mage::getModel('core/cookie')->get($cookie);
      $path = Mage::getModel('core/cookie')->getPath($cookie);
      $lifetime = Mage::getModel('core/cookie')->getLifetime($cookie);
      Mage::getModel('core/cookie')->delete($name, $path, $lifetime);
      }

      Let me know if you any suggestions for me.

      Delete
    12. Hello Hardik,

      Actually multi store cookie path is like /store1, /store2 ... and default is /. So I modified cookie path for all stores as "/". Finally issue is solved.

      Still I have to do more testings on this external login. if any issues , I will let you know.

      Thank you for the post and quick replies.

      Thanks,
      Himaja

      Delete
    13. Hello Hardik,
      After testing I found one more issue with externallogin to magento. If multiple users are accesing external website and click on a button(same time) which redirects to magento then it is showing white page.
      How to solve this issue?

      Thanks,
      Himaja

      Delete
  6. Yes, I created and with full permissions as admin. Still not working. Is there any restriction for login regarding cookie transfer in between different domains? Because I am able to modify products, create and login but not able to make auto login in magento. Let me know about this and any suggestions also great for me to proceed further.

    ReplyDelete
  7. i am doing the same thing and login by external but the user not logged in it showing for sign in again why?

    ReplyDelete
  8. Hello Hardik, first of all, thank you very much for this tutorial. I tell you that a while ago I made an external login for my website work, and it worked perfectly.
    It turns out that now I throw this error:

    SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://.../public_html/api/?wsdl' : failed to load external entity "http://.../public_html/api/?wsdl" in /var/www/html/.../externallogincheck.php:26 Stack trace: #0 /var/www/html/.../externallogincheck.php(26): SoapClient->SoapClient('http://...') #1 {main}

    What can it be? Could you help me?

    Thank you very much!

    ReplyDelete

 

Copyright @ 2017 HKBlog.