🔥 Just Launched! Werra Premium Template for HyväSee it in Action

Magento 2 API – Generate Customer Token Using Customer ID

By Siddharth NandavaUpdated on Apr 24, 2025 4 min read

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

<?php
    \Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE,
        'Vendor_CustomAPI',
        __DIR__
    );

app/code/Vendor/CustomAPI/etc/module.xml

<?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:

<?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:

<?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:

<?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/Customerdirectory with the following code:

<?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:

{
	"customerId" : 1
}

Response:

pb2do8k6kbvnar3yfu4ayutgve7k8f6b
magent 2 api generate customer token using customer id 700x40

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.

Siddharth Nandava Full Image
Article bySiddharth 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.