0

I have created a custom add to cart section where a customer can customize their chosen configurable product for multi-options. It is a functionality where I will have to programmatically add to cart multiple configurable products based on the customers selection. It is working perfectly for logged in customers, but I am getting no clue how this might work for guest users. I used

\Magento\Quote\Api\GuestCartManagementInterface::createEmptyCart()

to create a cart for customer, add adding item using

\Magento\Quote\Api\GuestCartItemRepositoryInterface::save($cartItem)

The items are added properly, which I can see in quote tables in database, but in frontend the cart stays empty.

So Magento is maintaining a different guest session for frontend users, and the Repository add to cart calls apparently does not recognize that session, or using a different one, even if the calls are made from frontend itself, not any third party application like Postman.

Magento's default add to cart controller adds item to cart for both guest and logged in customer without any additional parameters.

I am not getting how Magento is maintaining a guest customer's session. If it is possible to reflect the added items in cart for frontend customer.

1 Answer 1

1

There are two key points to keep in mind: web sessions and web APIs.

  • For web sessions: Magento checks the cookies and uses the Checkout Session to store the quote for guest users.

  • For web APIs: Magento utilizes the masked_id from the quote_id_mask table, which is passed with each API call.

Based on your context, I assume you're using the web API layer logic. If you want to update the web quote session for a guest user, you'll need to assign the quote to the checkout session. For example,

use Magento\Checkout\Model\Cart as CartModel; ...... $this->cartmodel->setQuote($quote); 

You also need to trigger the frontend cart section to reload.

1
  • 1
    Worked perfectly! Thank you so much, such a simple and elegant solution, and yet it is not clearly mentioned anywhere. Used the following line at the end of my code $this->checkoutSession->setQuoteId($this->maskedQuoteIdToQuoteId->execute($customerQuoteId)); Commented Sep 18, 2024 at 5:41

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.