• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2431
  • Last Modified:

Magento adding product to cart programatically results in empty cart

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), 'http://tempuri.org/');
    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?
Eddie Shipman
Eddie Shipman
  • 2
1 Solution
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.
Eddie ShipmanAll-around developerAuthor Commented:
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?
Eddie ShipmanAll-around developerAuthor Commented:
@GaryC123 I actually went a different route and got it working.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now