Magento 2 API – Generate Customer Token Using Customer ID
End-to-end Magento integration
Integrate any app or service. Consult our API development experts.
Howdy, Magento devs! Today, I will share a module for a custom Magento 2 API to generate customer token using customer ID. It will be helpful if you are developing an app based on Magento 2 and want to re-generate the customer token from the admin side.
The story goes like this:
On a fine day, one of my colleagues approached me asking, “Is there any method to generate customer token using customer ID through Magento 2 API?” He was working on an Android app and wanted to keep the customer’s session active based on their activity. The straightforward way was to increase the token expiration time to infinity, but that would not be feasible from a security point of view.
Therefore, we decided to develop a custom Magento 2 REST API, which can be used to regenerate the token before its expiry to keep the session active.
Bookmark our Magento 2 API resource hub, and master the art of Magento 2 integration!
In this post, I will share the entire module of the custom API and the method to use it.
Let’s begin ๐
Magento 2 Custom API Module to Generate Customer Token Using Customer ID
I created a REST API module that accepts post requests to generate the customer token by customer ID. It uses the admin token as authentication for security purposes. You can simply follow the steps provided below to create the module and use the API. In the end, I will also demonstrate the working of this API.
In this module, we will use vendor_customapi as a namespace; you can change the vendor & module names as you wish.
Step 1:ย Register the Custom API Module
First, we must register a custom module to create an API in Magento 2. Create the registration.php and module.xml files as provided below.
app/code/Vendor/CustomAPI/registration.php
1 2 3 4 5 6 |
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Vendor_CustomAPI', __DIR__ ); |
app/code/Vendor/CustomAPI/etc/module.xml
1 2 3 4 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Vendor_CustomAPI" setup_version="0.0.1"/> </config> |
Step 2: Define Custom Endpoint
Create a webapi.xml file at app/code/Vendor/CustomAPI/etc/ directory to define the endpoint for our custom API with the following code:
1 2 3 4 5 6 7 8 9 |
<?xml version="1.0"?> <routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd"> <route url="/V1/customer/resettoken/" method="POST"> <service class="Vendor\CustomAPI\Api\Customer\CustomerTokenInterface" method="getToken"/> <resources> <resource ref="Magento_Customer::manage"/> </resources> </route> </routes> |
Step 3: Create an Interface for the Request
Now, create the CustomerTokenInterface.php file at app/code/Vendor/CustomAPI/Api/Customer/ย directory with the following code:
1 2 3 4 5 6 7 8 9 10 11 |
<?php namespace Vendor\CustomAPI\Api\Customer; interface CustomerTokenInterface { /** * @param int $customerId * @return mixed */ public function getToken($customerId); } |
Step 4: Configure Module Dependency
Create a di.xmlย file at the app/code/Vendor/CustomAPI/etc/ directory with the following code:
1 2 3 4 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <preference for="Vendor\CustomAPI\Api\Customer\CustomerTokenInterface" type="Vendor\CustomAPI\Model\Api\Customer\CustomerRepository"/> </config> |
Step 5: Create a Model
Lastly, create a model file for processing the API data. Create CustomerRepository.php atย app/code/Vendor/CustomAPI/Model/Api/Customer/ย directory with the following code:
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 |
<?php namespace Vendor\CustomAPI\Model\Api\Customer; class CustomerRepository { /** * @var \Magento\Integration\Model\Oauth\TokenFactory */ private $tokenModelFactory; /** * @param \Magento\Integration\Model\Oauth\TokenFactory $tokenModelFactory */ public function __construct( \Magento\Integration\Model\Oauth\TokenFactory $tokenModelFactory) { $this->tokenModelFactory = $tokenModelFactory; } /** * @inheritdoc */ public function getToken($customerId) { $customerToken = $this->tokenModelFactory->create(); return $customerToken->createCustomerToken($customerId)->getToken(); } } |
Voila! You’ve successfully create a custom Magento 2 API to generate customer token using customer ID.
Magento 2 Custom API to Generate Customer Token by Customer ID:ย Structure, Endpoints, and Example
You can use this custom API to generate customer token by customer ID. It uses the admin token for the request authentication for security purposes.
Therefore, you need to generate the admin token in Magento 2 using API to use it. The complete API structure is provided below:
Method: POST
URL:ย https://store_url/rest/all/V1/customer/resettoken
Body:
1 2 3 |
{ "customerId" : 1 } |
Response:
1 |
pb2do8k6kbvnar3yfu4ayutgve7k8f6b |
Whoa..! We successfully got the customer token by customer id ๐
& there you go…
Create your own custom API in Magento 2 using the module I provided and try it. ๐
Let me know in the comments if you find this post helpful. You can also ping me for help with Magento 2 API development.
Spread the knowledge! Share this post via social media & other online forums.
Bbyee! Thanks for being with me till the end. ๐
โ Magento 2 API โ Get Customer TokenMagento 2 API – Reset Customer Password โบ
Siddharth Nandava
Siddharth Nandava is an enthusiastic Jr Magento developer at Meetanshi. Apart from the work, you can find him learning new things and spending quality time with his family.
Prev
10 Best eCommerce Platforms in 2024
How Much Does it Cost to Hire a Shopify Expert [2024]
Next