簡體   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