I'm trying to use the sales_order_place_after event to remove or add products to the order only after successful payment but facing a few different problems.
There are a few different solutions I could find, but every time I'm there is a different issue:
- Products I'm adding are not correctly deducted from the stock
- Cannot force that newly added product price is 0 when I'm adding more than one. Only the last one got 0.
- The new product must be listed separately on the order/invoice if this product already exists on the order.
I also need to remove some existing products from the order simultaneously and replace them with different ones at the same price.
As this will not affect the order total, so I think that order recalculation is unnecessary.
**** UPDATE ****
Here is one of many ways I was trying to achieve that. It is the closest to the desired result but added qty of product is not reduced from the stock.
public function execute (\Magento\Framework\Event\Observer $observer)
{
$order = $observer->getEvent()->getOrder();
$productId = 123;
$qty = 2;
$price = 0;
$product = $this->productRepository->getById($productId);
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$orderItem = $objectManager->create('Magento\Sales\Model\Order\Item');
$orderItem->setProductId($product->getId());
$orderItem->setSku($product->getSku());
$orderItem->setQtyOrdered($qty);
$orderItem->setQty($qty);
$orderItem->setBasePrice($price);
$orderItem->setPrice($price);
$orderItem->setRowTotal($price);
$orderItem->setOriginalPrice($price);
$orderItem->setName((string) __('%1 (Promo)', $product->getName()));
$order->addItem($orderItem);
try {
$this->orderResource->save($order);
}
catch (\Exception $e) {
throw new \Magento\Framework\Exception\LocalizedException(
__($e->getMessage() . " for order {$order->getIncrementId()}")
);
}
}
Unfortunately, I'm confused if I should still make those changes on the quote or already edit the order, so I would appreciate it if someone could tell me the correct way to do it, please?