Magento 2 REST API调用以获取客户ID [英] Magento 2 REST API call to get logged in customer ID

查看:333
本文介绍了Magento 2 REST API调用以获取客户ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我在URL中看到此端点:

I see this endpoint in the URL:

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

但是当我使用该URL时,我得到了:

but when I cURL that URL I get:

Consumer is not authorized to access %resources

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

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?

我只需要证明他们已经登录并获取他们的ID即可.

I just need to prove they are logged in and grab their ID.

推荐答案

这应该可行,考虑到您将PHPSESSID与请求一起发送.正如您所说的那样,您可能正在使用cURL.

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.

您可以通过对API进行ajax调用来轻松实现这一点,类似于以下内容:

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');
    }
});

如果需要将请求保留在服务器端,则应在请求中添加PHPSESSID:

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';
}

(cURL请求的来源:

(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)

这篇关于Magento 2 REST API调用以获取客户ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆