Magento – How to set custom tax price during add to cart in Magento 2

addtocartmagento2pricetax

I am adding product to cart using ajax call.

Here is my controller code.

use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
class AddItems extends \Magento\Framework\App\Action\Action
{

 protected $formKey;   
 protected $cart;
 protected $product;
 protected $_resource;
 protected $checkoutSession;
 protected $_taxCalculationService;
 protected $quoteRepository;

public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Data\Form\FormKey $formKey,
\Magento\Checkout\Model\Cart $cart,
\Magento\Catalog\Model\ProductFactory $product,
\Magento\Framework\App\ResourceConnection $resource,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Tax\Api\TaxCalculationInterface $taxCalculationService,
\Magento\Quote\Api\CartRepositoryInterface $quoteRepository,
  array $data = []
) {
   $this->formKey = $formKey;
   $this->cart = $cart;
   $this->product = $product;     
   $this->_resource = $resource;
   $this->checkoutSession = $checkoutSession;  
   $this->_taxCalculationService = $taxCalculationService; 
   $this->quoteRepository = $quoteRepository;
    parent::__construct($context);
 }

 public function execute()
{ 

 try{
   $productId = 10;
    $params = array(
        'form_key' => $this->formKey->getFormKey(),
        'product_id' => $productId, //product Id
        'qty'   =>1 //quantity of product                
    );
    $_product = $this->product->create()->load($productId);       
     $item = $this->cart->getQuote()->getItemByProduct($_product );
    if($item){          
        $quote = $this->cart->getQuote();                   
        $quote->updateItem($item->getId(), array( 'qty' => 1));
        $quote->save();
    }else{                  
        $this->cart->addProduct($_product , $params);
    }
  $customPrice = 1000;
  $grossAmt = 550;

  $productTaxClassId = $_product->getTaxClassId();
  $customerId = $this->getCustomerId();
  $storeId = $this->_storeManager->getStore()->getId();
  $productRates = $this->_taxCalculationService->getCalculatedRate($productTaxClassId, $customerId, $storeId);

  $taxAmount = ((1 * $grossAmt * $productRates) / 100);

  $quote = $this->cart->getQuote();
  $quoteId = $quote->getId();   
  $productItem = $this->getProductQuote($_product );                
  $productItem->setCustomPrice($customPrice);
  $productItem->setOriginalCustomPrice($customPrice);
  $productItem->getProduct()->setIsSuperMode(true);   
  $this->cart->save(); 

   $productItem->setTaxAmount($taxAmount)->setBaseTaxAmount($taxAmount)->save(); 
    $quote = $this->checkoutSession->getQuote();
    $quote->collectTotals();
    //$quote->save(); 
    $this->quoteRepository->save($quote);
   }
 }

public function getProductQuote($product) {
    $quote = $this->checkoutSession->getQuote();        
    $cartItems = $quote->getItemByProduct($product);        
    return $cartItems;
}
 public function getCustomerId(){
    $customerId =  $this->customerSession->getCustomer()->getId();
    if ($this->customerSession->isLoggedIn()) {
        return $this->customerSession->getCustomer()->getId();
    }
    return 0;
    }
}     

Using above code, I am able to add product to cart with custom price.

I need to add custom tax price also upon adding the product to cart. Right now tax is not getting applied.

How can I set custom tax price for the product added to cart.

Can anyone help me please, custom tax price I have got in variable, $taxAmount

This code save the data to "tax_amount" and "base_tax_amount" fields in quote_item table but when navigated to cart page, tax is showing as 0 and in table values are restored to 0.

$productItem->setTaxAmount($taxAmount)->setBaseTaxAmount($taxAmount)->save(); 
             $quote = $this->checkoutSession->getQuote();
             $quote->collectTotals();
             $this->quoteRepository->save($quote);
            // $quote->save();

Please share the ideas where I am doing wrong here. Thanks in advance

Best Answer

capture event: sales_quote_add_item

You can set tax price for item on this event.