Magento 2 – Get Customer ID of Logged In User with Cache Enabled

block-cachecustomer-sessionmagento2

I need to get the customer id of the user that is logged in. Using the following code it works fine for blocks where cache is disabled. But when there's a cached block on the page, it's null. Even if the customer is logged in. It is intended behavior for the customersession to be cleared when caching is active on a page but I need the customer id to show customer specific prices (B2B).

$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if(!$customerSession->isLoggedIn()) {
    $customerId = $customerSession->getCustomer()->getId();
}

I need to be able to get the customer id on all pages where prices are displayed for products. So, for example, the category list/grid page and the product details page.

I have read countless of bug reports on github but they all get closed by Magento as if it's no issue.

Best Answer

I have updated my response. In my previous answer, I had a block cacheable=false. This is incorrect because it do the page is not cacheable.

For knowing if the customer is logged or not, you must do the next:

Namespace/Modulename/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Customer\Model\Session">
         <plugin name="namespace_module_customer_plugin_session" type="Namespace\Modulename\Plugin\Customer\Model\Session"/>
    </type>
</config>

Namespace/Modulename/Plugin/Customer/Model/Session.php

<?php    
namespace Namespace\Modulename\Plugin\Customer\Model;

use Magento\Customer\Model\Context as CustomerContext;
use Magento\Customer\Model\Session as CustomerSession;
use Magento\Framework\App\Http\Context;

/**
 * Class Session
 */
class Session
{

    /**
     * @var Context
     */
    private $httpContext;

    /**
     * Session constructor.
     *
     * @param Context $context
     */
    public function __construct(
        Context $context
    ) {
        $this->httpContext = $context;
    }

    /**
     * Check http context to know if user is really logged in
     *
     * @param CustomerSession $subject
     * @param bool $isLoggedIn
     * @return bool
     */
    public function afterIsLoggedIn(CustomerSession $subject, $isLoggedIn)
    {
        return $isLoggedIn ?: $this->httpContext->getValue(CustomerContext::CONTEXT_AUTH);
    }
}

When you do $customerSession->isLoggedIn(), it will return the correct value.

To retrieve the id of the customer, the best way is how says @SohelRana in its comment, using ajax or private cache. https://devdocs.magento.com/guides/v2.2/extension-dev-guide/cache/page-caching/private-content.html

Related Topic