Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


Magento adding product to cart programatically results in empty cart

Posted on 2013-05-09
Medium Priority
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), '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?
Question by:Eddie Shipman
  • 2
LVL 58

Accepted Solution

Gary earned 2000 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

by:Eddie Shipman
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

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

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

Question has a verified solution.

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

Original post  on Monitis Blog. Web performance monitoring is broken into two camps: passive and active. Passive monitoring is defined as looking at real-world historical performance by monitoring actual log-ins, site hits, clicks, requests for …
While opting for any web-to-print solution, you need to discuss with your team and some of your end users and know their opinions about your decisions. In this article we list down some questions you need to ask yourself.
Viewers will get an overview of the benefits and risks of using Bitcoin to accept payments. What Bitcoin is: Legality: Risks: Benefits: Which businesses are best suited?: Other things you should know: How to get started:
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…
Suggested Courses

581 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