3

I need customer id and token number when login customer account in Magento2 I used this API for customer login:

Method: Post rest/V1/integration/customer/token

Body

{ "username" : "[email protected]", "password" : "abc12345!"; }

2
  • 1
    you have to create your own API endpoint that accepts user username as input for search customer data.
    – fmsthird
    Feb 4, 2019 at 9:38
  • Added an answer below. If you are specifically needing a response containing token and customer id directly from logging in, @fmsthird is correct that you need a custom endpoint. As part of that endpoint you'll have to define a new interface that holds token and customer id and return that. I could probably do a write up of how that could be accomplished if it's what you are looking for :).
    – sdaugherty
    Jun 11, 2019 at 23:08

2 Answers 2

2

The following endpoint (the one you mentioned) will return the access token upon submitting correct user credentials:

Method: Post rest/V1/integration/customer/token

Then all you need to do is pass that token as a bearer token to this next endpoint and you'll receive all the details for that customer:

Method: Get rest/V1/customers/me

Example Request

curl --request GET \ --url https://example.com/rest/V1/customers/me \ --header 'authorization: Bearer x6qa7biotlej2s2li1tl3zzx5ww42lt8'

Example Response

Customer id is id in the response

{
    "id": 77819,
    "group_id": 1,
    "default_shipping": "11169",
    "created_at": "2018-08-23 15:49:17",
    "updated_at": "2019-06-11 22:33:59",
    "created_in": "US",
    "email": "te[email protected]",
    "firstname": "Test",
    "lastname": "Person",
    "store_id": 1,
    "website_id": 1,
    "addresses": [
        {
            "id": 11170,
            "customer_id": 77819,
            "region": {
                "region_code": "Etelä-Savo",
                "region": "Etelä-Savo",
                "region_id": 976
            },
            "region_id": 976,
            "country_id": "FI",
            "street": [
                "Finlandiantie"
            ],
            "telephone": "1234",
            "postcode": "58450",
            "city": "Punkaharju",
            "firstname": "Test",
            "lastname": "Person",
            "custom_attributes": [
                {
                    "attribute_code": "some_custom_attribute",
                    "value": "A custom value"
                }
            ]
        }
    ],
    "disable_auto_group_change": 0,
    "extension_attributes": {
        "is_subscribed": false
    },
    "custom_attributes": [
        {
            "attribute_code": "some_custom_attribute",
            "value": "A custom value"
        }
    ]
}
2

Full working example

YourModule/Customer/etc/di.xml

    <preference for="YourModule\Customer\Api\AuthServiceInterface"
                type="YourModule\Customer\Model\AuthService" />

YourModule/Customer/etc/webapi.xml

<route url="/V2/login" method="POST">
    <service class="YourModule\Customer\Api\AuthServiceInterface" method="login"/>
    <resources>
        <resource ref="anonymous"/>
    </resources>
</route>

YourModule/Customer/Api/Data/LoginResponseInterface.php

interface LoginResponseInterface {
    /**#@+
     * Constants defined for keys of the data array. Identical to the name of the getter in snake case
     */
    const ACCESS_TOKEN = 'access_token';
    const CUSTOMER_ID = 'customer_id';
    /**#@-*/

    /**
     * Get access token
     *
     * @return string
     */
    public function getAccessToken();

    /**
     * Set access token
     *
     * @param string $token
     * @return $this
     */
    public function setAccessToken($token);

    /**
     * Set customerId
     *
     * @param int $id
     * @return $this
     */
    public function setStoreWebsiteId($id);

    /**
     * Get customerId
     *
     * @return int
     */
    public function getCustomerId();
}

YourModule/Customer/Model/Data/LoginResponse.php

class LoginResponse extends AbstractModel implements LoginResponseInterface {

    /**
     * @inheritdoc
     */
    public function getAccessToken(){
        return $this->getData(self::ACCESS_TOKEN);
    }

    /**
     * @inheritdoc
     */
    public function setAccessToken($token){
        return $this->setData(self::ACCESS_TOKEN, $token);
    }

    /**
     * @inheritdoc
     */
    public function setCustomerId($id){
        return $this->setData(self::CUSTOMER_ID, $id);
    }

    /**
     * @inheritdoc
     */
    public function getCustomerId(){
        return $this->getData(self::CUSTOMER_ID);
    }
}

YourModule/Customer/Api/AuthServiceInterface.php

interface AuthServiceInterface
{
    /**
     * Login and return accessToken, customer info
     *
     * @param string $username
     * @param string $password
     * @return Data\LoginResponseInterface
     * @throws \Magento\Framework\Exception\AuthenticationException
     */
    public function login($username, $password);
}

YourModule/Customer/Model/AuthService.php

use Magento\Customer\Api\AccountManagementInterface;
use YourModule\Customer\Api\AuthServiceInterface;
use Magento\Integration\Model\CredentialsValidator;
use Magento\Integration\Model\Oauth\TokenFactory as TokenModelFactory;
use Magento\Integration\Model\ResourceModel\Oauth\Token\CollectionFactory as TokenCollectionFactory;
use Magento\Integration\Model\Oauth\Token\RequestThrottler;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Event\ManagerInterface;
use Magento\Store\Model\StoreManagerInterface;

class AuthService implements AuthServiceInterface
{
    /**
     * Token Model
     *
     * @var TokenModelFactory
     */
    private $tokenModelFactory;

    /**
     * @var Magento\Framework\Event\ManagerInterface
     */
    private $eventManager;

    /**
     * Customer Account Service
     *
     * @var AccountManagementInterface
     */
    private $accountManagement;

    /**
     * @var \Magento\Integration\Model\CredentialsValidator
     */
    private $validatorHelper;

    /**
     * Token Collection Factory
     *
     * @var TokenCollectionFactory
     */
    private $tokenModelCollectionFactory;

    /**
     * @var Data\LoginResponseFactory
     */
    protected $_loginResponseFactory;

    /**
     * @var RequestThrottler
     */
    private $requestThrottler;

    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * Initialize service
     *
     * @param TokenModelFactory $tokenModelFactory
     * @param AccountManagementInterface $accountManagement
     * @param TokenCollectionFactory $tokenModelCollectionFactory
     * @param \Magento\Integration\Model\CredentialsValidator $validatorHelper
     * @param Data\LoginResponseFactory $loginResponseFactory
     * @param StoreManagerInterface $storeManager
     * @param \Magento\Framework\Event\ManagerInterface $eventManager
     */
    public function __construct(
        TokenModelFactory $tokenModelFactory,
        AccountManagementInterface $accountManagement,
        TokenCollectionFactory $tokenModelCollectionFactory,
        CredentialsValidator $validatorHelper,
        \YourModule\Customer\Model\Data\LoginResponseFactory $loginResponseFactory,
        StoreManagerInterface $storeManager,
        ManagerInterface $eventManager = null
    ) {
        $this->tokenModelFactory = $tokenModelFactory;
        $this->accountManagement = $accountManagement;
        $this->tokenModelCollectionFactory = $tokenModelCollectionFactory;
        $this->validatorHelper = $validatorHelper;
        $this->eventManager = $eventManager ?: \Magento\Framework\App\ObjectManager::getInstance()
            ->get(ManagerInterface::class);

        $this->_loginResponseFactory = $loginResponseFactory;
        $this->storeManager = $storeManager;
    }

    /**
     * @inheritdoc
     */
    public function login($username, $password)
    {
        $this->validatorHelper->validate($username, $password);
        $this->getRequestThrottler()->throttle($username, RequestThrottler::USER_TYPE_CUSTOMER);
        try {
            $customerDataObject = $this->accountManagement->authenticate($username, $password);
        } catch (\Exception $e) {
            $this->getRequestThrottler()->logAuthenticationFailure($username, RequestThrottler::USER_TYPE_CUSTOMER);
            throw new AuthenticationException(
                __(
                    'The account sign-in was incorrect or your account is disabled temporarily. '
                    . 'Please wait and try again later.'
                )
            );
        }
        $this->eventManager->dispatch('customer_login', ['customer' => $customerDataObject]);
        $this->getRequestThrottler()->resetAuthenticationFailuresCount($username, RequestThrottler::USER_TYPE_CUSTOMER);
        $token = $this->tokenModelFactory->create()->createCustomerToken($customerDataObject->getId())->getToken();

        $loginResponse = $this->_loginResponseFactory->create();
        $loginResponse->setCustomerId($customerDataObject->getId());
        $loginResponse->setAccessToken($token);
        
        return $loginResponse;
    }

    /**
     * Get request throttler instance
     *
     * @return RequestThrottler
     * @deprecated 100.0.4
     */
    private function getRequestThrottler()
    {
        if (!$this->requestThrottler instanceof RequestThrottler) {
            return \Magento\Framework\App\ObjectManager::getInstance()->get(RequestThrottler::class);
        }
        return $this->requestThrottler;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.