4

How can I add a product with a custom price to the cart, using the Magento API?

I found a solution where a special price is configured for one second, but this leaves the special price visible in the backend and this is not allowed.

  • @FabianBlechschmidt Reading the documentation and reading the source. – i.amniels Jul 2 '14 at 16:12
  • REST or SOAP API? – Pablo S. Benitez Jul 2 '14 at 17:53
  • @PabloS.Benitez I prefer SOAP. – i.amniels Jul 2 '14 at 19:23
2

The solution for me was to create a new API method, which allows to set the prices of the products in the cart. The function is based on the cart_product.remove function.

public function setCustomPrice($quoteId, $productsData, $store = null)
{
    $quote = $this->_getQuote($quoteId, $store);
    if (empty($store)) {
        $store = $quote->getStoreId();
    }

    $productsData = $this->_prepareProductsData($productsData);
    if (empty($productsData)) {
        $this->_fault('invalid_product_data');
    }

    $errors = array();
    foreach ($productsData as $productItem) {
        if (isset($productItem['product_id'])) {
            $productByItem = $this->_getProduct($productItem['product_id'], $store, "id");
        } else if (isset($productItem['sku'])) {
            $productByItem = $this->_getProduct($productItem['sku'], $store, "sku");
        } else {
            $errors[] = Mage::helper('checkout')->__("One item of products do not have identifier or sku");
            continue;
        }

        try {
            /** @var $quoteItem Mage_Sales_Model_Quote_Item */
            $quoteItem = $this->_getQuoteItemByProduct($quote, $productByItem,
                $this->_getProductRequest($productItem));
            if (is_null($quoteItem->getId())) {
                $errors[] = Mage::helper('checkout')->__("One item of products is not belong any of quote item");
                continue;
            }

            if(isset($productItem['price'])){
                $quoteItem->setCustomPrice($productItem['price']);
                $quoteItem->setOriginalCustomPrice($productItem['price']);
                $quoteItem->getProduct()->setIsSuperMode(true);
                $quoteItem->save();
            }

        } catch (Mage_Core_Exception $e) {
            $errors[] = $e->getMessage();
        }
    }

    if (!empty($errors)) {
        $this->_fault("remove_product_fault", implode(PHP_EOL, $errors));
    }

    try {
        $quote->collectTotals()->save();
    } catch (Exception $e) {
        $this->_fault("remove_product_quote_save_fault", $e->getMessage());
    }

    return true;
}
  • 3
    are you able to provide more information on how you added this new api method? Thanks :) – BrynJ Sep 3 '14 at 13:34

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.