Some time we needs to get customer id without session in magento 2. I am going to explain some simple steps to get customer id without session.
Before we start I assume, you have already a created custom module. If you don't have it or don't know how to create it then check out our other article How To Create a Magento 2 Module.
<?php
namespace Vendor\Module\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
/**
* @var \Magento\Framework\App\Helper\Context
*/
protected $userContext;
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Authorization\Model\UserContextInterface $userContext
)
{
$this->userContext = $userContext;
parent::__construct($context);
}
public function getCustomerId()
{
return $this->userContext->getUserId();
}
}
Thant's It!
I hope this Magento article helped you to find what you were looking for.