Solved

Magento adding product to cart programatically results in empty cart

Posted on 2013-05-09
3
2,049 Views
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);
    $session->setLastAddedProductId($product_id);
    $session->setCartWasUpdated(true);
    $cart->save();
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");
Mage::app();

$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?
0
Comment
Question by:EddieShipman
  • 2
3 Comments
 
LVL 58

Accepted Solution

by:
Gary earned 500 total points
Comment Utility
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.
0
 
LVL 26

Author Comment

by:EddieShipman
Comment Utility
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?
0
 
LVL 26

Author Closing Comment

by:EddieShipman
Comment Utility
@GaryC123 I actually went a different route and got it working.
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Are you using email marketing software? If not, you're missing out on effortless marketing and the reaching of desired conversion rates through email marketing software.
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.
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…

744 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

9 Experts available now in Live!

Get 1:1 Help Now