1

I need to find the customer data in custom rest api model I think magento very the customer token from the header as bearer token so i need to get from the customer token.

1 Answer 1

3
I Got the below solution for the same.


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.


   <?php
namespace Prince\RestApi\Model\Customer;

class Token
{
    /**
     *
     * @var \Magento\Authorization\Model\CompositeUserContext
     */
    protected $userContext;
    
    /**
     * 
     * @param \Magento\Authorization\Model\CompositeUserContext $userContext
     */
    public function __construct(
        \Magento\Authorization\Model\CompositeUserContext $userContext
    ) {
        $this->userContext = $userContext;
    }
    
    /**
     * 
     * @return int
     */
    public function getCustomerId()
    {
        return $customerId = $this->userContext->getUserId();
    }
}

With $this->userContext->getUserId(); you will get the customer id.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.