Magento add product to cart from a external file doesn't work

本秂侑毒 提交于 2019-12-12 02:49:48

问题


i have a problem with Magento's addProduct() function. I have the following code:

<?php
// Mage init
include_once '../app/Mage.php'; 
umask(0);  
Mage::init('default');
Mage::getSingleton('core/session', array('name' => 'frontend'));
// Get customer session
$session = Mage::getSingleton('customer/session');     
// Get cart instance
$cart = Mage::getSingleton('checkout/cart'); 
$cart->init();    
// Add a product with custom options
$productId = 11348;
$productInstance = Mage::getModel('catalog/product')->load($productId);
$param = array(
    'product' => $productInstance->getId(),
    'qty' => 1,
    'options' => array(
        528 => '1756',   // Custom option with id: 528
        527 => '1753',   // Custom option with id: 527
        526 => '1751'   // Custom option with id: 526
    )
);
$request = new Varien_Object();
$request->setData($param);
$cart->addProduct($productInstance, $request);    
// update session
$session->setCartWasUpdated(true);    
// save the cart
$cart->save();     
?>

It worked yesterday so include and $param are rigth but now it doesn't work. You also can add this product to cart inside the shop so the product exist and it's in stock. This code doesn't seems to have any error but it doesn't add product to cart.

Thanks for help.


回答1:


<?php
require_once('app/Mage.php');    
umask(0);
Mage::app('admin');
$product_model = Mage::getModel('catalog/product');
$my_product_sku = 'test';        
$my_product_id  = $product_model->getIdBySku($my_product_sku);
$my_product     = $product_model->load($my_product_id);
$qty_value = 13;
$cart = Mage::getModel('checkout/cart');
$cart->init();
$cart->addProduct($my_product, array('qty' => $qty_value));
$cart->save();

Mage::getSingleton('checkout/session')->setCartWasUpdated(true); 
?>



回答2:


try with adding form key and uenc field

$param = array(
'product' => $productInstance->getId(),
'form_key'=>$form_key_put_here,
'uenc' =>Mage::app()->getRequest()->getParam('uenc', 1),
'qty' => 1,
'options' => array(
    528 => '1756',   // Custom option with id: 528
    527 => '1753',   // Custom option with id: 527
    526 => '1751'   // Custom option with id: 526
));

hope this will help.



来源:https://stackoverflow.com/questions/23264433/magento-add-product-to-cart-from-a-external-file-doesnt-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!