I am creating order pro-grammatically.
I have referred below code
https://www.rakeshjesadiya.com/how-to-create-order-programmatically-in-magento-2/
My requirement is to set discount amount for each cart item.
The discount amount is 5. This can be varied based the product id which i am fetching from external api
I tried below code for that.
$quote->setDiscountAmount(5); after the line
$quote->addProduct($product,$buyRequest); It is not working. Can anyone help me to achieve this functionality.
Thanks for your help
Update
As from Amit suggestion i used below code.
Vendor\Module\etc\sales.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Sales:etc/sales.xsd"> <section name="quote"> <group name="totals"> <item name="testdiscount" instance="Vendor\Module\Model\Quote\Discount" sort_order="500"/> </group> </section> Vendor\Module\Model\Quote\Discount.php
namespace X247commerce\CustomerService\Model\Quote; class Discount extends \Magento\Quote\Model\Quote\Address\Total\AbstractTotal { protected $_priceCurrency; public function __construct( \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency ){ $this->_priceCurrency = $priceCurrency; } public function collect( \Magento\Quote\Model\Quote $quote, \Magento\Quote\Api\Data\ShippingAssignmentInterface $shippingAssignment, \Magento\Quote\Model\Quote\Address\Total $total ) { parent::collect($quote, $shippingAssignment, $total); $baseDiscount = 10; $discount = $this->_priceCurrency->convert($baseDiscount); $total->addTotalAmount('customdiscount', -$discount); $total->addBaseTotalAmount('customdiscount', -$baseDiscount); $total->setBaseGrandTotal($total->getBaseGrandTotal() - $baseDiscount); $quote->setCustomDiscount(-$discount); $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $objectManager->get('Psr\Log\LoggerInterface')->info('discount'.$discount); $objectManager->get('Psr\Log\LoggerInterface')->info(json_encode($quote->getData())); return $this; } }