Magento 2 – Customer Session for Logged In Customer with Token-Based Authentication

apicustomermagento2restsession

We are using token based authentication over rest api from that resource

/rest/V1/integration/customer/token?username=USER_NAME&password=P@$$WORD

to consume magento rest api web services.

We get tokens and return customer details successfully form that resource

/rest/V1/customers/me

I need to get the customer ID from his session but I can not because user always considered not logged in, despite working fine for web scenario below is the code snippet I use.

   public function __construct(\Magento\Customer\Model\Session $session){

    parent::__construct($context);
    $this->customerSession = $session;
}

I am facing that problem inside my custom offline payment method defined in custom extension, I need to know the customer ID in order to determine if the customer can use that payment method or not.

Even if I tried to use the checkoutSession, still can not get the customerId.

$om = \Magento\Framework\App\ObjectManager::getInstance();
    $checkoutSession = $om->get('\Magento\Checkout\Model\Session');
    exit(var_dump($checkoutSession->getQuote()->getCustomer()->getId())); //return NULL

The custom extension works fine when viewing the store from the browser.

Can you please help me what is wrong here?

Thanks in advance

Best Answer

Try Below Code To get a customer id

<?php
    $obm = \Magento\Framework\App\ObjectManager::getInstance();
    $context = $obm->get('Magento\Framework\App\Http\Context');

    $isLoggedIn = $context->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
    if($isLoggedIn){ 
      $om = \Magento\Framework\App\ObjectManager::getInstance();
      $customerSession = $om->create('Magento\Customer\Model\Session');
         //get a customer id       
      $customerId = $customerSession->getCustomer()->getId();

      }
?>