Magento adding product to cart programatically results in empty cart

Posted on 2013-05-09
Last Modified: 2016-03-02
I'm trying to add a product to the Magento cart by SKU and this code works when the user is already logged in but if I login programatically, shows the cart as empty even though the getItemsCount() function returns 1:
$product_id = Mage::getModel("catalog/product")->getIdBySku("$sku");
if (!$product_id) {
    throw new Exception("Product not added, the SKU you entered ($sku) was not found.");
$product = Mage::getModel("catalog/product")->load($product_id);
$session = Mage::getSingleton("core/session", array("name" => "frontend"));
$cart    = Mage::helper("checkout/cart")->getCart();

fwrite($fp, "No. Items-before:". $cart->getItemsCount() . "\n"); // returns 0
    // $params defined like this:
    //     $params = array(
    //         "product"   => $product_id,
    //         "qty"       => $qty, 
    //         "price"     => $event_price
    //     );
    $cart->addProduct($product, $params);
fwrite($fp, "No. Items-after:". $cart->getItemsCount() . "\n"); // returns 1

Open in new window

This is how I'm logging in programatically:
include_once ("../app/Mage.php");

$sku              = $_POST["sku"];
$event_price      = $_POST["price"];
$qty              = 1;
$loggedIn = false;
$loginUser = (isset($_POST["Email"]) ? true : false);
if ($loginUser) {
    Mage::getSingleton("core/session", array("name" => "frontend"));
    require_once ($_SERVER['DOCUMENT_ROOT'] . "../lib/nusoap.php");
    $client = new nusoap_client(NA_SOAP_SERVER, 'wsdl', '', '', '', '', 1000, 1000);
    $client->soap_defencoding = 'utf-8';
    $err = $client->getError();
    $param = array();
    $param["Email"] = $_POST['Email'];
    // The SelectByEmail function below is a function in our 
    // webservice that looks up the user's Username and Password 
    // using the user's email address.
    $r = $client->call('SelectByEmail', array('parameters' => $param), '');
    if ($r) {
        $Username             = $r['SelectByEmailResult']['Username'];
        $Password             = $r['SelectByEmailResult']['Password']; 
        $lm = new Login_model();
        // The dual_login function below is the same function used when 
        // loggin in from our normal controls on the site.
        // If I check $ret['result'], it is coming back 'SUCCESS'
        // It would show 'FAILURE' if it failed and I was not logged in
        $ret = $lm ->dual_login($Username, $Password);
        if ($ret['result'] = 'SUCCESS') {
            $loggedIn = true;
// Code at top of post is what runs after the user is logged in.
// It is supposed to add the product to the cart and then echo
// SUCCESS back to the calling script(s), which then redirects
// to the cart. The cart is now showing empty, however.

Open in new window

I have already looked Googled the heck out of this and can't find a solution and am beginning to pull the last bit of my hair out trying to figure this thing out. Using Magento 1.4.0 (don't even ask to upgrade, we can't because contractor heavily modified core)

BTW, the quote as well as the quote items DO get created, however, the customer_email is NULL in the quote record, could it just be a timing issue?
Question by:EddieShipman
  • 2
LVL 58

Accepted Solution

Gary earned 500 total points
ID: 39154075
The only time I remember this kind of problem was due to session id's, in that parts of the cart were assigned to the session/user but other parts were not.
But I'm confused over your logic of programmatically logging in?
But as you say your contractor has changed core code - which he should never have done, Magento works on the basis of overriding core functionality with your own code in a separate file.
LVL 26

Author Comment

ID: 39154365
Believe me, you don't have to preach about modification of core files, that is why the contractor was fired and I was hired. The cart is actually a small part of an entire ExpressionEngine site and there are several places where we actually login programatically.

To be honest, when I was hired, I was wondering why they chose this sledge hammer to kill the flea that was their need for a shopping cart. I come from a Prestashop background an it would have been 10000 times easier to implement a cart into this existing site using Prestashop. We are currently undergoing a site rebuild using EE and BrilliantRetail, an EE plugin cart.

Our authentication must go through our webservice so we have an ExpressionEngine plugin that handles it and we just call the particular plugin functions to perform the login.

The plugin does work and has been working for over 2 yrs. It's just that when we added the capability to add a product by sku to also having a custom attribute, we've run into problems.

Do you have any other suggestions?
LVL 26

Author Closing Comment

ID: 39175352
@GaryC123 I actually went a different route and got it working.

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Mod_Rewrite, htaccess, opencart 4 87
hide a folder in a url with parameters in php using htaccess 14 85
payment system 2 32
Google adds suggestions 3 58
The aim of this article is to help you solve the error "Cannot insert the value NULL into column 'ShortDescription', table 'albert_store.dbo.Nop_Product'; column does not allow nulls. UPDATE fails." problem and allow you to continue updating your No…
Learn about the eCommerce marketing trends for the year ahead.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now