0

My requirement is when user comes from and external php website via url they will pass the email id in web url request. I need to catch that email and start the magento2 customer session. I searched in google and placed my code as follows.

    $data=$this->getRequest()->getParams();

    if(isset($data['email'])){

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    // Load customer By Email

    $customer = $objectManager->create('Magento\Customer\Model\Customer')->setWebsiteId(1)->loadByEmail($data['email']);
    // Create customer session
    echo $customer->getId();
    $customerSession = $objectManager->create('Magento\Customer\Model\Session');
    $customerSession->setCustomerAsLoggedIn($customer);
    if($customerSession->isLoggedIn()) {
       echo "Customer Logged in";
    }else{
       echo "customer is Not Logged in";
    }

    // $customerSession->setCustomerDataAsLoggedIn($customer);
    $customerSession->regenerateId();

    }

I placed this in header.phtml file. Why because this file must be included everywhere. So when email presented in URL i am doing autologin. But session is not creating for user. When i click on any link called as "My Account" it is asking me to login again. enter image description here

1 Answer 1

0

first of all you don't need to call this on all pages. when you redirected from any third-party website just check you back URL and call login function or override login method.

But be sure that email id must be registered with your website else first you have to register that user using email and other required information which you may get from your third-party website.

After that you can login to your current website by just using core login function.

13
  • Yes but why my code is not working here?
    – Dinesh
    Commented Nov 4, 2019 at 9:50
  • when you call this function at first time, are you sure you were logged in? Commented Nov 4, 2019 at 9:53
  • it is displaying text as "Customer Loggedin" but when i refresh the same page it is not showing LOGOUT button in my header menu.
    – Dinesh
    Commented Nov 4, 2019 at 10:21
  • that means you are not logged in Commented Nov 4, 2019 at 12:30
  • ya thats why i posted question here... whats wrong with my code.
    – Dinesh
    Commented Nov 4, 2019 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.