Magento 2.3.5: Add product to cart with custom options and price

Hello guys,

unfortunately no one is willing to help me at Magento forum wherefore I would appreciate your help very much.

I have a simple product without options, price equals 0, etc. It’s not even visible in store because I just created it to refer to it when adding it to cart. I need to be able add the product to cart programmatically via Rest Api post request. Furthermore I need to add custom options with custom values and a custom price to it, so the options as well as the price will be visible in cart, in checkout and in order (user area & admin area).

My current code looks like this:

protected $_cart;
protected $_productFactory;

Constructor:

public function __construct(
MagentoCheckoutModelCart $cart,
MagentoCatalogModelProductFactory $productFactory
) {
$this->_cart = $cart;
$this->_productFactory = $productFactory;
}

Execute:

$product = $this->_productFactory->create()->load($product_id);
$params = array(
'qty' => 1,
'price' => 100,
'product' => $product_id,
'options' => array(
"test" => array(
'label' => 'Print Style',
'value' => 'Test'
)
)
);
$this->_cart->addProduct($product, $params);
$this->_cart->save();

The product will be added to the cart and the amount of products equals the quantity I stated in my array.

There are several problems though:

  1. The product is only visible in the cart after adding a different product to it via the regular add to cart button.
  2. The price is not adjusted. The normal price is used.
  3. The custom option isn’t visible. The custom option should be visible in the cart, at the checkout and in the order details.

I also found this article but it doesn’t allow to state completely custom options and values: https://devdocs.magento.com/guides/v2.3/rest/tutorials/orders/order-add-items.html

It’s really important for me to solve this problem. I appreciate your help.

Thanks.

Best.

submitted by /u/Goldkind47
[link] [comments]