简体   繁体   English

Magento 2 REST API调用以获取登录的客户ID

[英]Magento 2 REST API call to get logged in customer ID

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. 我想从Magento外部(但在同一个域)进行REST调用,以获取当前登录的客户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. 我不希望他们再次登录或提供密码,我只需要获取他们的ID,以便我可以根据他们的ID将它们重定向到某个地方。

I see this endpoint in the URL: 我在URL中看到了这个端点:

http://.../rest/V1/customers/me

but when I cURL that URL I get: 但当我得到那个URL我得到:

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? 如果是这样,这个PHP调用是什么样的?

I just need to prove they are logged in and grab their ID. 我只需要证明他们已登录并获取他们的ID。

That should work, considering you are sending the PHPSESSID together with you request. 考虑到您将PHPSESSID与您的请求一起发送,这应该可行。 As you said you're using cURL, that is probably not the case. 正如你所说,你正在使用cURL,情况可能并非如此。

You could easily achieve that by making an ajax call to the API, something similar to the following: 你可以通过对API进行ajax调用来轻松实现这一点,类似于以下内容:

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: 如果您需要在服务器端保留请求,则应将PHPSESSID添加到您的请求中:

$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/mp/62092#M1813 ) (cURL请求的来源: https//community.magento.com/t5/Programming-Questions/REST-API-call-to-get-logged-in-customer-ID/mp/62092#M1813

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM