Get Customer token for the REST API using customer id in Magento 2 used to call API.
If you have customer id, retrieve the token by the Token factory class of the Integration module.
Instantiate the Magento\Integration\Model\Oauth\TokenFactory in your class constructor method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <?php namespace Jesadiya\CustomerToken\Model; use Magento\Integration\Model\Oauth\TokenFactory as TokenModelFactory; class Token { /** * Token Model * * @var TokenModelFactory */ private $tokenModelFactory; public function __construct( TokenModelFactory $tokenModelFactory ) { $this->tokenModelFactory = $tokenModelFactory; } /** * Retrieve customer token * * @param int $customerId * @return string */ public function createToken(int $customerId) { $token = $this->tokenModelFactory->create()->createCustomerToken($customerId)->getToken(); return $token; } } |
Call method by required input,
1 2 | $customerId = 1; $result = $this->createToken($customerId); |
Output:
string