We are using the code below to automatically log a user into Magento before adding a product to the cart.
On occasions, the code below works but the products are not being added to the cart because the login isn’t “sticking”. It seems that sessions are the issue. If we let our web server stay up without rebooting for extended periods of time, Magento seems to “forget” sessions it created and the code below fails because the product doesn’t add anything to the cart.
// This call is actually in a class called Login_model, function called dual_login
// It is shown below.
$lm = new Login_model();
$ret = $lm ->dual_login($Username, $Password);
if ($ret['result'] = 'SUCCESS') {
$product_id = Mage::getModel("catalog/product") -> getIdBySku("$sku");
$product = Mage::getModel("catalog/product") -> load($product_id);
$session = Mage::getSingleton("core/session", array("name" => "frontend"));
$cart = Mage::helper("checkout/cart") -> getCart();
$cart -> addProduct($product, 1);
$session -> setLastAddedProductId($product -> getId());
$session -> setCartWasUpdated(true);
$cart -> save();
$cart_url = $site_url_https . "store/checkout/cart";
header("Location: " . $cart_url);
}
//
// dual_login code below
//
Mage::getSingleton('core/session', array('name'=>'frontend'));
$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($Email);
$session = Mage::getSingleton('customer/session');
$session->login($Email,$Password);
$session->setCustomerAsLoggedIn($session->getCustomer());
//
// How can I determine here if the login was actually successful
// and the product can be added to the cart?
//
$ret['result'] = 'SUCCESS';
If I add a call to $session->isLoggedIn(), it returns true but the product is still not added to the cart.
What can cause Magento to do this and how would I be able to test for it so I can get notified that it is happening?
The only clue from your code is that you are populating the customer model, but you are not using that to populate the session singleton. Should you really do
and not
?