In REST API integration, we can retrieve customer token from calling /V1/integration/customer/token API. Later this token is passed as a bearer token in Postman or we can pass in the api_key text field on the top of the page in the user interface for swagger. Sometime we may need to get the customer id from the token.
We need to inject the object for class \Magento\Authorization\Model\CompositeUserContext in __construct() method of your class. CompositeUserContext class has getUserId() method that will retrieve the CustomerId for generated token.
<!-- wp:code {"hasCustomCSS":true} -->
<pre class="wp-block-code"><code>/**
*
<!-- wp:paragraph -->
<p>class Token<br>{<br>/**<br>*<br>* @var \Magento\Authorization\Model\CompositeUserContext<br>*/<br>protected $userContext;</p>
<!-- /wp:paragraph -->
* @param \Magento\Authorization\Model\CompositeUserContext $userContext
*/
public function __construct(
\Magento\Authorization\Model\CompositeUserContext $userContext
) {
$this-&gt;userContext = $userContext;
}
/**
*
* @return int
*/
public function getCustomerId()
{
return $customerId = $this-&gt;userContext-&gt;getUserId();
}</code></pre>
<!-- /wp:code -->
<!-- wp:heading {"level":4} -->
<h4>With $this->userContext->getUserId();</h4>
<!-- /wp:heading -->
Hey there! Do you use Twitter? I’d like to follow you if that
would be ok. I’m definitely enjoying your blog and look forward to new updates.
Hello, everything is going fine here and ofcourse every one is sharing data, that’s
really excellent, keep up writing.