2017-02-28 190 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