I'm working on a task that need an API endpoint for adding product to cart in Magento 2.
My code do the job "add product to cart" properly (it add product to cart and when I go to .../checkout/cart I can see it.
$params = array('product' => $cardId, 'qty' => 1);
$product = $this->productRepository->getById($cardId);
$this->cart->addProduct($product, $params);
$this->cart->save();
But I need to update the mini cart also. I searched google and this is the best solution that I found:
Create file etc/frontend/sections.xml:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
<action name="rest/V1/badgemakerapi/addToCart">
<section name="cart"/>
</action>
</config>
In the tutorial, the part
name="rest/V1/badgemakerapi/addToCart"
is actually
name="frontname/controller/action"
but because I don't have controller, I have to change it to API route
I noticed that in Checkout module, magento 2 core team does the same thing:
<action name="rest/*/V1/carts/*/payment-information">
<section name="cart"/>
<section name="checkout-data"/>
<section name="last-ordered-items"/>
</action>
<action name="rest/*/V1/guest-carts/*/payment-information">
<section name="cart"/>
<section name="checkout-data"/>
</action>
<action name="rest/*/V1/guest-carts/*/selected-payment-method">
<section name="cart"/>
<section name="checkout-data"/>
</action>
<action name="rest/*/V1/carts/*/selected-payment-method">
<section name="cart"/>
<section name="checkout-data"/>
</action>
The problem is I can not update mini cart using this method.
Anyone has any idea?
Thank you very much.
addToCart
API call from the client's web page, and you want to update the minicart badge and items without reloading the page? Or is the issue that even after reloading the page, the minicart still isn't updated?