Magento – Magento 2 + How to share cart for guest users between multi websites

customer-sessionmagento2.2.3multi-websiteshopping-cart

I have a magento 2 website where I want to share cart between websites (for logged in users and guest users). For ex. guest user added product1 to the cart from website1 and now user switches to website2 then user would be able to see the same product to cart already.

magento is only providing cart sharing between stores not websites. Also I've tried couple of the multiple store cart sharing settings but no luck till now. However, I would love to hear solution for multiple websites.

Best Answer

To share cart among websites you have to do two things.

  1. Make Magento 2 read cart quote id from a single session key.

    class Session extends \Magento\Checkout\Model\Session
    {
        /**
         * @return string
         */
        protected function _getQuoteIdKey()
        {
            return 'quote_id_1';
        }
    }
    
  2. Make Magento consider all stores when loading quote

    class QuoteRepository extends \Magento\Quote\Model\QuoteRepository
    {
        /**
         * Load quote with different methods
         * Will consider all stores valid, quote can be shared among all stores.
         *
         * @param string $loadMethod
         * @param string $loadField
         * @param int $identifier
         * @param int[] $sharedStoreIds
         * @throws NoSuchEntityException
         * @return Quote
         */
        protected function loadQuote($loadMethod, $loadField, $identifier, array $sharedStoreIds = [])
        {
            $sharedStoreIds = $this->getStoreIds();
    
            /** @var Quote $quote */
            $quote = $this->quoteFactory->create();
            if ($sharedStoreIds) {
                $quote->setSharedStoreIds($sharedStoreIds);
            }
            $quote->setStoreId($this->storeManager->getStore()->getId())->$loadMethod($identifier);
            $quote->setStoreId($this->storeManager->getStore()->getId())->load($identifier);
            if (!$quote->getId()) {
                throw NoSuchEntityException::singleField($loadField, $identifier);
            }
            return $quote;
        }
    
    
        /**
         * @return int[]
         */
        protected function getStoreIds()
        {
            $storeIds = [];
            $stores = $this->storeManager->getStores();
    
            foreach ($stores as $storeId => $store) {
                $storeIds[] = $storeId;
            }
    
            return $storeIds;
        }
    }
    
Related Topic