Magento – Magento2 rest api add customer token in create customer api

magento-2.1

i am using
magento 2.1.1
php version 7.0

this is my payload and response.

enter image description here

i want to add customer token in the response and i am using following magento 2 api :

http://host/index.php/rest/default/V1/customers

Example (*)
in the response i want to add seesion id in following response :

{
"id": 2278,
"group_id": 1,
"created_at": "2018-11-13 14:06:24",
"updated_at": "2018-11-13 14:06:24",
"created_in": "Default Store View",
"email": "test1023@gmail.com",
"firstname": "test",
"lastname": "lastName",
"store_id": 1,
"website_id": 1,
"addresses": [],
"disable_auto_group_change": 0
"session_id": "b5la2wrgxx00oqu83yuvqdthnqjv1tmv"
}

Hope you guys understand my problem

Best Answer

Create a afterCreateAccount plugin of AccountManagementInterface. You need to create a new customer attribute as well. Your plugin code will look like below.

<?php

namespace Vendor\Module\Plugin;

class AddAccessToken
{

    public function __construct(
        \Magento\Integration\Model\Oauth\TokenFactory $tokenModelFactory,
        \Magento\Customer\Api\Data\CustomerExtensionFactory $customerExtensionFactory
    ) {
        $this->tokenModelFactory = $tokenModelFactory;
        $this->customerExtensionFactory = $customerExtensionFactory
    }

    /**
     * Add token to customer object
     *
     * @param   \Magento\Customr\Api\AccountManagementInterface $subject,
     * @param   \Magento\Customer\Api\Data\CustomerInterface $customer
     * @return  \Magento\Customer\Api\Data\CustomerInterface
     */
    public function afterCreateAccount(
        \Magento\Customr\Api\AccountManagementInterface $subject,
         \Magento\Customer\Api\Data\CustomerInterface $customer
    ) {
        $token = $this->tokenModelFactory->create()->createCustomerToken($customer->getId());
        $extensionAttributes = $customer->getExtensionAttributes();
        if($extensionAttributes === null) {
                $extensionAttributes = $this->customerExtensionFactory->create();
       }
        $extensionAttributes->setToken($token);
        $customer->setExtensionAttributes($extensionAttributes);
        return $customer;
    }

}

di.xml

<type name="Magento\Customr\Api\AccountManagementInterface">
    <plugin name="add_access_token" type="Vendot\Module\Plugin\AddAccessToken"/>
</type>

extension_attributes.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
<extension_attributes for="Magento\Customer\Api\Data\CustomerInterface">
    <attribute code="token" type="string" />
</extension_attributes>
</config>

Go into module.xml file and update setup_version to 1.0.1 and run setup:upgrade command. Let me know if any more help needed.

Related Topic