5

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":"[email protected]", "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

asked Sep 25, 2018 at 10:13
0

2 Answers 2

2

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;
answered Sep 25, 2018 at 12:37
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":"[email protected]", "password":"d00l1tle"}"

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

answered Sep 25, 2018 at 10:29
1
  • my bad, i use self not anonymous , check my updated question Commented Sep 25, 2018 at 10:39

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.