How To Get Access Token Of Logged In Customer In Magento 2
The post shows the programmatic method to get access token of logged in customer in Magento 2.
You can use this method when, for example, you want to improve the login method for customers and allowing them to login via Facebook or Google.
The developer must give the access token to make a web Magento 2 API call from a client such as a mobile application. This token serves as an electronic key to access the API.
Method to get access token of logged in customer in Magento 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
use Magento\Customer\Model\Session; use Magento\Framework\App\Action\Context; use Magento\Integration\Model\Oauth\TokenFactory; protected $customerSession; protected $tokenModelFactory; public function __construct( Session $customerSession, TokenFactory $tokenModelFactory ) { $this->customerSession = $customerSession; $this->tokenModelFactory = $tokenModelFactory; } public function getToken(){ $customerId = $this->customerSession->getCustomer()->getId(); $customerToken = $this->tokenModelFactory->create(); return $customerToken->createCustomerToken($customerId)->getToken(); } |
Related read: How to get logged in customer address in Magento 2?
Apart from the programmatic solution, you can also use Magento 2 API to get customer token by calling a GET request with credentials.
That’s it.
Any doubts? Please mention them in the Comments section below. I’m happy to help you out.
Feel free to share the solution with fellow developers via social media.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
2 Comments
Where to add that code ?
Hello,
You can place this code in the API through which login is happening or such custom action.
Thanks.