2017-02-28 195 views
2

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

我看到这个端点的网址:

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

但是当我卷曲那个网址获得:

Consumer is not authorized to access %resources 

我还需要获得令牌访问此,即使它是匿名和基于会话?如果是这样,这个PHP调用是什么样的?

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

回答

0

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

您可以轻松地实现通过调用Ajax的API,类似于下面的内容:

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

(源卷曲请求:https://community.magento.com/t5/Programming-Questions/REST-API-call-to-get-logged-in-customer-ID/m-p/62092#M1813