Link to home
Start Free TrialLog in
Avatar of Eddie Shipman
Eddie ShipmanFlag for United States of America

asked on

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), '');
    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?
Avatar of Gary
Flag of Ireland image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Eddie Shipman


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?
@GaryC123 I actually went a different route and got it working.