{"id":2708,"date":"2024-12-31T20:26:01","date_gmt":"2024-12-31T20:26:01","guid":{"rendered":"https:\/\/meetanshi.com\/blog\/magento-2-api-generate-customer-token-using-customer-id\/"},"modified":"2025-04-24T09:38:41","modified_gmt":"2025-04-24T04:08:41","slug":"magento-2-api-generate-customer-token-using-customer-id","status":"publish","type":"post","link":"https:\/\/meetanshi.com\/blog\/magento-2-api-generate-customer-token-using-customer-id\/","title":{"rendered":"Magento 2 API \u2013 Generate Customer Token Using Customer ID"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Howdy, Magento devs! Today, I will share a module for a custom&nbsp;<em><strong>Magento 2 API to generate customer token using customer ID<\/strong><\/em>. 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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>The story goes like this:<\/em><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">On a fine day, one of my colleagues approached me asking,&nbsp;<em>\u201cIs there any method to generate customer token using customer ID through Magento 2 API?\u201d&nbsp;<\/em>He was working on an Android app and wanted to keep the customer\u2019s 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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Therefore, we decided to develop a custom&nbsp;<a href=\"https:\/\/developer.adobe.com\/commerce\/webapi\/rest\/\" target=\"_blank\" rel=\"noreferrer noopener\">Magento 2 REST API<\/a>, which can be used to regenerate the token before its expiry to keep the session active.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Bookmark our&nbsp;<a href=\"https:\/\/meetanshi.com\/blog\/magento-2-api\/\" target=\"_blank\" rel=\"noreferrer noopener\">Magento 2 API resource hub<\/a>, and master the art of Magento 2 integration!<\/em><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this post, I will share the entire module of the custom API and the method to use it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let\u2019s begin  <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Magento 2 Custom API Module to Generate Customer Token Using Customer ID<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this module, we will use&nbsp;<strong><em>vendor_customapi&nbsp;<\/em><\/strong>as a namespace; you can change the vendor &amp; module names as you wish.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 1:&nbsp;Register the Custom API Module<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">First, we must register a custom module to create an API in Magento 2. Create the&nbsp;<strong>registration.php<\/strong>&nbsp;and&nbsp;<strong>module.xml<\/strong>&nbsp;files as provided below.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em><strong>app\/code\/Vendor\/CustomAPI\/registration.php<\/strong><\/em><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\n    \\Magento\\Framework\\Component\\ComponentRegistrar::register(\n        \\Magento\\Framework\\Component\\ComponentRegistrar::MODULE,\n        'Vendor_CustomAPI',\n        __DIR__\n    );<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><em><strong>app\/code\/Vendor\/CustomAPI\/etc\/module.xml<\/strong><\/em><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?xml version=\"1.0\"?>\n&lt;config xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:Module\/etc\/module.xsd\">\n    &lt;module name=\"Vendor_CustomAPI\" setup_version=\"0.0.1\"\/>\n&lt;\/config><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Step 2: Define Custom Endpoint<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a&nbsp;<strong>webapi.xml<\/strong>&nbsp;file at&nbsp;<em><strong>app\/code\/Vendor\/CustomAPI\/etc\/&nbsp;<\/strong><\/em>directory to define the endpoint for our custom API with the following code:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?xml version=\"1.0\"?>\n&lt;routes xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"..\/..\/..\/..\/..\/app\/code\/Magento\/Webapi\/etc\/webapi.xsd\">\n    &lt;route url=\"\/V1\/customer\/resettoken\/\" method=\"POST\">\n        &lt;service class=\"Vendor\\CustomAPI\\Api\\Customer\\CustomerTokenInterface\" method=\"getToken\"\/>\n        &lt;resources>\n            &lt;resource ref=\"Magento_Customer::manage\"\/>\n        &lt;\/resources>\n    &lt;\/route>\n&lt;\/routes><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Step 3: Create an Interface for the Request<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Now, create the&nbsp;<strong>CustomerTokenInterface.php&nbsp;<\/strong>file at&nbsp;<em><strong>app\/code\/Vendor\/CustomAPI\/Api\/Customer\/&nbsp;<\/strong><\/em>directory with the following code:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\nnamespace Vendor\\CustomAPI\\Api\\Customer;\n\ninterface CustomerTokenInterface\n{\n    \/**\n     * @param int $customerId\n     * @return mixed\n     *\/\n    public function getToken($customerId);\n}<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Step 4: Configure Module Dependency<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a&nbsp;<strong>di.xml&nbsp;<\/strong>file at the&nbsp;<em><strong>app\/code\/Vendor\/CustomAPI\/etc\/&nbsp;<\/strong><\/em>directory with the following code:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?xml version=\"1.0\"?>\n&lt;config xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:ObjectManager\/etc\/config.xsd\">\n    &lt;preference for=\"Vendor\\CustomAPI\\Api\\Customer\\CustomerTokenInterface\" type=\"Vendor\\CustomAPI\\Model\\Api\\Customer\\CustomerRepository\"\/>\n&lt;\/config><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Step 5: Create a Model<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Lastly, create a model file for processing the API data. Create&nbsp;<strong>CustomerRepository.php&nbsp;<\/strong>at&nbsp;<em><strong>app\/code\/Vendor\/CustomAPI\/Model\/Api\/Customer<\/strong>\/&nbsp;<\/em>directory with the following code:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\nnamespace Vendor\\CustomAPI\\Model\\Api\\Customer;\n\nclass CustomerRepository\n{\n    \/**\n     * @var \\Magento\\Integration\\Model\\Oauth\\TokenFactory\n     *\/\n    private $tokenModelFactory;\n\n    \/**\n     * @param \\Magento\\Integration\\Model\\Oauth\\TokenFactory $tokenModelFactory\n     *\/\n    public function __construct(\n        \\Magento\\Integration\\Model\\Oauth\\TokenFactory $tokenModelFactory)\n    {\n        $this->tokenModelFactory = $tokenModelFactory;\n    }\n\n    \/**\n     * @inheritdoc\n     *\/\n    public function getToken($customerId)\n    {\n        $customerToken = $this->tokenModelFactory->create();\n        return $customerToken->createCustomerToken($customerId)->getToken();\n    }\n\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Voila! You\u2019ve successfully create a custom Magento 2 API to generate customer token using customer ID.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Magento 2 Custom API to Generate Customer Token by Customer ID:&nbsp; Structure, Endpoints, and Example<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Therefore, you need to generate the&nbsp;<a href=\"https:\/\/meetanshi.com\/blog\/magento-2-api-get-admin-token\/\" target=\"_blank\" rel=\"noreferrer noopener\">admin token in Magento 2 using API<\/a>&nbsp;to use it. The complete API structure is provided below:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Method:&nbsp;<\/strong>POST<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>URL:&nbsp;<\/strong><em>https:\/\/store_url\/rest\/all\/V1\/customer\/resettoken<\/em><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Body:<\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">{\n\t\"customerId\" : 1\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Response:<\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">pb2do8k6kbvnar3yfu4ayutgve7k8f6b<\/pre>\n\n\n\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" src=\"https:\/\/meetanshi.com\/blog\/wp-content\/uploads\/2023\/02\/magent-2-api-generate-customer-token-using-customer-id-700x402.png\" alt=\"magent 2 api generate customer token using customer id 700x40\"\/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Whoa..! We successfully got the customer token by customer id  <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">&amp; there you go\u2026<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Create your own custom API in Magento 2 using the module I provided and try it.<\/em>&nbsp; <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let me know in the comments if you find this post helpful. You can also ping me for help with&nbsp;<a href=\"https:\/\/meetanshi.com\/magento-api-integration-service.html\" target=\"_blank\" rel=\"noreferrer noopener\">Magento 2 API development<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Spread the knowledge!<\/strong>&nbsp;Share this post via social media &amp; other online forums.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Bbyee! Thanks for being with me till the end.  <\/p>\n","protected":false},"excerpt":{"rendered":"<p>Howdy, Magento devs! Today, I will share a module for a custom&nbsp;Magento 2 API to generate customer token using customer ID. It will be helpful&#8230;<\/p>\n","protected":false},"author":38,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[34],"tags":[],"class_list":["post-2708","post","type-post","status-publish","format-standard","hentry","category-magento"],"acf":[],"_links":{"self":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/2708","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/users\/38"}],"replies":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/comments?post=2708"}],"version-history":[{"count":3,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/2708\/revisions"}],"predecessor-version":[{"id":12866,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/2708\/revisions\/12866"}],"wp:attachment":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/media?parent=2708"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/categories?post=2708"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/tags?post=2708"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}