7

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();


?>
  • Where/how is $product defined? – pspahn Aug 22 '14 at 19:54
  • i have edit the question and product definition is at top, i have also tried $productInstance which is up there too but still no dice – ehmad11 Aug 22 '14 at 20:12
  • i have updated question with full code so far, its bit messy but you can get some idea what i am trying to do... – ehmad11 Aug 26 '14 at 9:57
  • 1
    can you tell why you clear cart in last step.. – Amit Bera Aug 26 '14 at 14:46
  • @AmitBera i have removed those lines... it was somehow helpful too.. – ehmad11 Aug 28 '14 at 11:20
27
+50

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.

  • 1
    i am getting this: Fatal error: Uncaught exception 'Varien_Exception' with message 'Invalid method Mage_Checkout_Model_Session::addProduct(Array ( [0] => Mage_Catalog_Model_Product Object...... probably there is no method addProduct here $quote = Mage::getSingleton('checkout/session'); $quote->addProduct($product, $qty); – ehmad11 Aug 26 '14 at 9:08
  • secondly i am using onepage checkout! – ehmad11 Aug 26 '14 at 9:34
  • $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(); – ehmad11 Aug 26 '14 at 9:34
  • 1
    i am trying this on fresh installation without any theme or module... – ehmad11 Aug 26 '14 at 15:23
  • 1
    hey @philwinkle thanks .. The code $quote->collectTotals()->save(); save my one month works – Amit Bera Nov 6 '16 at 16:32
3

Here we add the product to cart using external script

<?php
include 'app/Mage.php';
Mage::app();
// Need for start the session
Mage::getSingleton('core/session', array('name' => 'frontend'));
try {
    $product_id = '52'; // Replace id with your product id
    $qty = '4'; // Replace qty with your qty
    $product = Mage::getModel('catalog/product')->load($product_id);
    $cart = Mage::getModel('checkout/cart');
    $cart->init();
    $cart->addProduct($product, array('qty' => $qty));
    $cart->save();
    Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
    Mage::getSingleton('core/session')->addSuccess('Product added successfully');
    header('Location: ' . 'index.php/checkout/cart/');
} catch (Exception $e) {
    echo $e->getMessage();
}
?>

Note:- here 52 is the simple product-id and 4 is the quantity value, you can replace with your quantity.

  • I want to first clear cart and than add to cart. How can i do – ND17 Jun 10 '15 at 13:00
0

I had this problem before. In my task, I needed to add product on specific quote.Below code helped me to accomplish this:

$quoteModel = Mage::getModel('sales/quote')->load($quoteId);
$cartModel = Mage::getModel('checkout/cart');
$cartModel->setData('quote', $quoteModel);
$cartModel->init();
$cartModel->addProduct(productId, array('qty'=>5));
$cartModel->save();

Hope that wil help you in this case.

0

Here is the easy way to add product to cart/quote:

$customer = Mage::getModel('customer/customer')->load($customerId);
$product = Mage::getModel('catalog/product')->load($productId);
// load quote by customer and store...
$quote = Mage::getModel('sales/quote')->setStore($storeId)->loadByCustomer($customerId);
$quote->addProduct($product, 1);
$quote->setIsActive(1);
$quote->collectTotals()->save();
0

Here is the working code to add product to Cart:

$customer = Mage::getModel('customer/customer')->load($customerId);
$product = Mage::getModel('catalog/product')->load($productId);
// load quote by customer and store...
$quote = Mage::getModel('sales/quote')->setStore($storeId)->loadByCustomer($customerId);
$quote->addProduct($product, 1);
$quote->setIsActive(1);
$quote->collectTotals()->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.