Magento – how to login customer programmatically in checkout magento

billingmagento-1.8onepage-checkouttax

I will explain step by step.

1.I selected checkout method as register.

2.So in billing information i get extra two fields password and confirm password.
and I have added extra customer type field.based on selection of customer type the tax should calculate in order review tab.

so normally the entire check out steps will temporarely store in quote object.But I want to store customer register information(in billing tab) permanently .because it should reflect in order review tab in order to tax sholud calculate based on customer type.
for that i created one observer

3.If i click continue button one event will trigger .it will save customer information in db permanently.

4.using above customer register information to login I placed following code below save functionality.

but its not working.I mean If i click continue button in billing tab it saving the data in db.but not login.

<?php
class Exinent_Billingtax_Model_Observer {
    public function autoRegisterBilling($evt){
        if(!Mage::helper('customer')->isLoggedIn()){
            $data = $evt->getEvent()->getControllerAction()->getRequest()->getPost('billing', array());
            //echo "<pre>";
            //print_r($data);
            $customer = Mage::getModel("customer/customer");
            $email = $data['email'];
            $group_id=$data['group_id'];
            $websiteId = Mage::app()->getWebsite()->getId();
            $store = Mage::app()->getStore();
            $pwd = $data['customer_password'];
            $customer->setWebsiteId(Mage::app()->getStore()->getWebsiteId())->loadByEmail($email);

            if (!$customer->getId()) {
                 //Code begins here for new customer registration
                $customer->website_id = $websiteId;
                $customer->setStore($store);
                $customer->firstname = $data['firstname'];
                $customer->lastname = $data['lastname'];
                $customer->setEmail($email);
                $customer->setGroupId($group_id);
                $customer->setPassword($pwd);
                $customer->sendNewAccountEmail('confirmed');  
                $customer->save();
                   }

            Mage::getSingleton('customer/session')->loginById($customer->getId()); // to login that customer.
        /*if($customer->getId()>0){
            $userSession = Mage::getSingleton('customer/session');
            $userSession->setCustomer($customer);
            Mage::dispatchEvent('customer_login', array('customer'=>$customer));
            Mage::app()->getResponse()->setRedirect(Mage::getUrl('checkout/onepage'))->sendResponse();
            exit;
            }*/
           }
    }

} 

Best Answer

Perhaps try

$customer->loadByEmail($email);
$session = Mage::getSingleton("customer/session");
$session->loginById($customer->getId());
$session->setCustomerAsLoggedIn($customer);
Related Topic