Magento – Adding Product to Cart Returns Empty Price

cartmagento-1.8PHPproduct

i have been trying to programmatically add a product to cart using following lines of code, it seems to work and successfully adds product but for some reason, the price of newly added product always sets to zero.. how can i prevent this and let the actual price of product to be set for cart?

<?php

 error_reporting(E_ALL);
 ini_set('display_errors', 1);

require_once("app/Mage.php");
umask(0);
Mage::app('default');



 function mres($value)
{
    $search = array("\\",  "\x00", "\n",  "\r",  "'",  '"', "\x1a");
    $replace = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z");

    return str_replace($search, $replace, $value);
}


echo "testing";
print_r($_POST);



$fname = mres( $_POST['fname'] );
$lname = mres( $_POST['lname'] );
$email = mres( $_POST['email'] );
$day = mres( $_POST['day'] );
$month = mres( $_POST['month'] );
$year = mres( $_POST['year'] );
$phone = mres( $_POST['phone'] );
$mobile = mres( $_POST['mobile'] );
$city = mres( $_POST['city'] );
$address = mres( $_POST['address'] );
$discount = mres( $_POST['discount'] );
$quantity = mres( $_POST['quantity'] );
$comments = mres( $_POST['comments'] );
$url = mres( $_POST['url'] );
$store = mres( $_POST['store'] );
$store_id = mres( $_POST['store_id'] );
$web_id = mres( $_POST['web_id'] );
$product_id = mres( $_POST['product_id'] );
$sku = mres( $_POST['sku'] );

setcookie('fname', $fname);
setcookie('lname', $lname);
setcookie('email', $email);
//setcookie('age', $age);
setcookie('phone', $phone);
setcookie('mobile', $mobile);
setcookie('city', $city);
setcookie('address', $address);



$customer = Mage::getModel('customer/customer');
//$customer  = new Mage_Customer_Model_Customer();
$password = substr(str_shuffle(md5(time())),0,8);;

$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);


//Zend_Debug::dump($customer->debug()); 

$isNew = 0;
if(!$customer->getId()) {
    $customer->setEmail($email);
    $customer->setFirstname($fname);
    $customer->setLastname($lname);
    $customer->setPassword($password);
    $isNew = 1;
}
try {
    $customer->save();
    $customer->setConfirmation(null);
    $customer->save();

    if($isNew)
    {
        $customer->sendNewAccountEmail();


        $ch = curl_init();

        //set the url, number of POST vars, POST data
        curl_setopt($ch,CURLOPT_URL, "//sameurl.php");
        curl_setopt($ch,CURLOPT_POST, count($_POST));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);

        //execute post
        $result = curl_exec($ch);

        //close connection
        curl_close($ch);


    }

    Mage::getSingleton('customer/session')->loginById($customer->getId());
}
catch (Exception $ex) {
    //Zend_Debug::dump($ex->getMessage());
}





//Build billing and shipping address for customer, for checkout
$_custom_address = array (
    'firstname' => $fname,
    'lastname' => $lname,
    'street' => array (
        '0' => $address,
        '1' => '',
    ),
    'city' => $city,
    'region_id' => '',
    'region' => '',
    'postcode' => '0000',
    'country_id' => 'PK',
    'telephone' => $phone . '-' . $mobile,
);
//$customAddress = Mage::getModel('customer/address')
$customAddress = new Mage_Customer_Model_Address();
$customAddress->setData($_custom_address)
            ->setCustomerId($customer->getId())
            ->setIsDefaultBilling('1')
            ->setIsDefaultShipping('1')
            ->setSaveInAddressBook('1');
try {
    $customAddress->save();


    Zend_Debug::dump($customAddress->debug()); 


}
catch (Exception $ex) {
    Zend_Debug::dump($ex->getMessage());
}
//Mage::getSingleton('checkout/session')->getQuote()->setBillingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress));


Mage::getSingleton('checkout/session')->getQuote()
->setBillingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress)) ->setShippingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress));

/*
$product = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToFilter('sku', $sku)
    ->addAttributeToSelect('*')
    ->getFirstItem();

$product->load($product_id);
$cart = Mage::getSingleton('checkout/cart');

$productInstance = Mage::getModel('catalog/product')->load($product_id);
$cart->truncate();
$cart->save();
$cart->getItems()->clear()->save();
try {
    //$cart->addProduct($product, array('options'=> array('some-custom-option-id-here' => 'Some value goes here');
    //$cart->addProduct($product, array('price' => 5000));
    //$cart->addProduct($productInstance, $param);
    //$cart->save();


    $cart->init();
    $cart->addProduct($product, array('qty' => $qty));
    $cart->save();
    Mage::getSingleton('checkout/session')->setCartWasUpdated(true);


}
catch (Exception $ex) {
    echo $ex->getMessage();
}
unset($product);
*/

$product = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToFilter('sku', $sku)
    ->addAttributeToSelect('*')
    ->getFirstItem();

$product->load($product_id);
$quote = Mage::getSingleton('checkout/session');
$quote->addProduct($product, $qty);

$quote->collectTotals()->save();


$storeId = $store_id;
$checkout = Mage::getSingleton('checkout/type_onepage');
$checkout->initCheckout();
$checkout->saveCheckoutMethod('register');
$checkout->saveShippingMethod('flatrate_flatrate');     
$checkout->savePayment(array('method'=>'free'));


try {
    $checkout->saveOrder();
}
catch (Exception $ex) {
    echo $ex->getMessage();
}
/* Clear the cart */
$cart->truncate();
$cart->save();
$cart->getItems()->clear()->save();
/* Logout the customer you created */
Mage::getSingleton('customer/session')->logout();


?>

Best Answer

There are many things wrong here and I feel compelled to do a code review with you. See the end for the correct approach.

Code review:


This line is loading a product with an undefined $sku var:

$product = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToFilter('sku', $sku)
    ->addAttributeToSelect('*')
    ->getFirstItem();

Now you're reloading the $product var with an undefined value, returns a blank model or null.

$product->load($product_id);

Getting the cart model (but not necessarily mine from my customer session):

$cart = Mage::getSingleton('checkout/cart');

Wait - now we're loading another instance of a blank object:

$productInstance = Mage::getModel('catalog/product')->load($product_id);

Clearing the brand new cart:

$cart->truncate();

Saving our empty cart:

$cart->save();

Getting all the items in our empty cart, clearing them, and saving again:

$cart->getItems()->clear()->save();

The right way:


All in all this code makes no sense. Some Google searching turns up the right way to add a product to the current user's cart with the correct price attached:

$quote = Mage::getSingleton('checkout/session')->getQuote();
$quote->addProduct($product, $qty);

$quote->collectTotals()->save();

Where $product and $qty are both defined, and $product is an instance of Mage_Catalog_Model_Product and $qty is an integer.

Related Topic