4

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

1

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;
0

For anonymous resource you have to add the Authorization: Bearer to your request.

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

This XXXXXXXX is token id, which you have to generate from admin>System>Intregation

  • my bad, i use self not anonymous , check my updated question – Tiny Dancer Sep 25 '18 at 10:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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