Skip to content

Magento 2 – how to create order programmatically with custom price AND tax amount for each line item (not percent)

I created a module that creates an order programmatically and I can also set the custom price. This is part of my code:

        foreach($orderData['products'] as $product)
        {
            try
            {
                $quoteProduct = $this->productRepository->get($product['sku']);
                $this->logger->info(sprintf("Adding product to quote, id: %d, sku: %s, qty: %d", $quoteProduct->getId(), $quoteProduct->getSku(), $product['qty']));
                $quoteItem = $quote->addProduct(
                    $quoteProduct, 
                    intval($product['qty'])
                );
                $quoteItem->setCustomPrice($product['amountPaid']);
                $quoteItem->setOriginalCustomPrice($product['amountPaid']);
                $quoteItem->getProduct()->setIsSuperMode(true);
            }
            catch(Exception $e)
            {
                $orderResult->errorMessage = sprintf("ERROR: %s, failed to add product to quote, sku: %s, qty: %d. Check saleable quantity, product may be out of stock.", $e->getMessage(), $product['sku'], $product['qty']);
                $this->logger->critical($orderResult->errorMessage);
                return $orderResult;
            }
        }

I would like to set the custom tax amount just like I am setting the custom price. Can this be done?

To clarify: I don’t want Magento to calculate and apply the tax for the product. I want to override its default behavior and set the line item tax amount manually.

enter image description here