繁体   English   中英

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

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

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

我在URL中看到了这个端点:

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

但当我得到那个URL我得到:

Consumer is not authorized to access %resources

即使它是匿名的并且基于会话,我仍然需要获取令牌来访问它吗? 如果是这样,这个PHP调用是什么样的?

我只需要证明他们已登录并获取他们的ID。

考虑到您将PHPSESSID与您的请求一起发送,这应该可行。 正如你所说,你正在使用cURL,情况可能并非如此。

你可以通过对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');
    }
});

如果您需要在服务器端保留请求,则应将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';
}

(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