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.
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.
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;
}