Magento | 我如何在自定义模块中的购物车中添加产品?

Flo*_*low 5 php rest magento

我目前正在开发Magento 1.9上的管理模块Cart

我坚持在我的购物车上添加一个产品(我尝试了很多不同的东西),这就是我征求你帮助的原因.

我的模块扩展了magento的其余API,我已经管理了对我的购物车的更新(产品数量),但现在我希望通过POST方法添加新产品.当然我是以客户身份登录的.我定义了此角色的创建权限.(我可以毫无问题地进行更新)

这是我的代码:

protected function _create(array $data){

    $store = $this->_getStore();
    Mage::app()->setCurrentStore($store->getId());

    $cart = Mage::getModel('checkout/cart');
    $cart->init();

    $productCollection = Mage::getModel('catalog/product')->load(4);


    // Add product to cart
    $cart->addProduct($productCollection,
        array(
            'product_id' => $productCollection->getId(),
            'qty' => '1'
        )
    );
    // Save cart
    $cart->save();

}
Run Code Online (Sandbox Code Playgroud)

在这个简单的例子中,我尝试在数量1中添加产品ID 4.我的问题是我在日志中没有错误,一切似乎已经过去了.但是当我拿到购物车时,没有产品可以添加...

作为回报,我有一个代码200 OK

你有什么建议可以帮到我吗?

非常感谢你的帮助

问候

Flo*_*low 3

经过整个互联网的探索,我终于找到了解决方案;)

事实上,当你想在结帐前到达购物车时,magento 使用“报价”定义...对于 Magento 的初学者来说不容易理解...所以为了方便那些像我一样遇到麻烦的人进行研究,这是我在购物车中添加新产品的代码(结帐前):

//$data['entity_id'] = The id of the product you want to add to the cart
//$data['qty'] = The quantity you want to specify

protected function _create(array $data)
{
    $store = $this->_getStore();
    Mage::app()->setCurrentStore($store->getId());

    // Get Customer's ID
    $customerID = $this->getApiUser()->getUserId();

    // Load quote by Customer
    $quote = Mage::getModel('sales/quote')
             ->loadByCustomer($customerID);

    $product = Mage::getModel('catalog/product')
                         // set the current store ID
                         ->setStoreId(Mage::app()->getStore()->getId())
                         // load the product object
                         ->load($data['entity_id']);

    // Add Product to Quote
    $quote->addProduct($product,$data['qty']);

    try {
        // Calculate the new Cart total and Save Quote
        $quote->collectTotals()->save();
    } catch (Mage_Core_Exception $e) {
        $this->_error($e->getMessage(),Mage_Api2_Model_Server::HTTP_INTERNAL_ERROR);
    }

}
Run Code Online (Sandbox Code Playgroud)

我希望这可以帮助某人

问候

卡尼弗莱克斯