Reputation: 71
I want to make a REST call from outside of Magento (but on the same domain) to get the currently logged in customer's ID. I don't want them to have to login again or provide a password, I just need to get their ID so I can redirect them somewhere based on their ID.
I see this endpoint in the URL:
http://.../rest/V1/customers/me
but when I cURL that URL I get:
Consumer is not authorized to access %resources
Do I still need to get a token to access this even though it is anonymous and based on the session? If so, what does this PHP call look like?
I just need to prove they are logged in and grab their ID.
Upvotes: 3
Views: 3382
Reputation: 309
That should work, considering you are sending the PHPSESSID together with you request. As you said you're using cURL, that is probably not the case.
You could easily achieve that by making an ajax call to the API, something similar to the following:
jQuery.ajax({
url: 'http://dev.magento2.com/rest/V1/customers/me',
type: 'get',
error: function() {
alert('User not Logged In');
},
success: function() {
alert('User logged in');
}
});
If you need to keep the requests on the server side, then you should add PHPSESSID to your requests:
$ch = curl_init('http://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);
if (isset($json->id)) {
echo 'User logged in';
} else {
echo 'User not logged in';
}
(source for the cURL request: https://community.magento.com/t5/Programming-Questions/REST-API-call-to-get-logged-in-customer-ID/m-p/62092#M1813)
Upvotes: 1