Magento – Get customer details by using Authentication Token

customermagento2resttokenwebapi

I use this Magento 2 rest api to get customer token:

curl -X POST "https://my.project/rest/V1/integration/customer/token" \
     -H "Content-Type:application/json" \
     -d "{"username":"me@awesome.com", "password":"d00l1tle"}"

i successfully got the token, and i pass the token in header when i access my custom magento 2 webapi

Authorization: Bearer <authentication token>

webapi.xml

<route url="/V1/test/most/" method="GET">
      <service class="Vendor\Module\Api\TestRepositoryInterface" method="getTest"/>
      <resources>
          <resource ref="self"/>
      </resources>
  </route>

i want to retrieve the customer information in my getTest() function base on customer token which is use as Authorization header

Best Answer

webapi.xml

<route url="/V1/test/most/" method="GET">
  <service class="Vendor\Module\Api\TestRepositoryInterface" method="getTest"/>
  <resources>
      <resource ref="self"/>
  </resources>
        <data>
            <parameter name="customerId" force="true">%customer_id%</parameter>
        </data>
 </route>

in this API call you'll get customer ID and based on ID you can get Customer data.


Another solution

$ch = curl_init('dev.magento2.com/rest/V1/customers/me');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json'
));
curl_setopt($ch, CURLOPT_COOKIE, 'PHPSESSID=' . $_COOKIE['PHPSESSID']);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

$json = json_decode($result);
echo $json->id;