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

标签 php rest curl magento2

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

我在 URL 中看到这个端点:

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

但是当我 cURL 那个 URL 时,我得到:

Consumer is not authorized to access %resources

即使它是匿名的并且基于 session ,我是否仍然需要获得 token 才能访问它?如果是这样,这个 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/m-p/62092#M1813)

关于php - Magento 2 REST API 调用以获取登录的客户 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42500559/

相关文章:

java - 我需要为 JDK 1.6 下载什么 Jersey 版本?

java如何重写jackson ObjectReader?

php - 将命令行 cURL 转换为 PHP cURL

php - 你如何处理 jQuery 中的后退按钮?

linux - 没有这样的模块 'PerfectLib'

php - mod_rewrite 问题和 php

php - Curl上传文件失败

javascript - 需要帮助来归纳curl Post代码中的JS/Node.js

php - Guzzle 且无法将响应解析为 JSON

php - 为什么我不应该在 PHP 中使用 mysql_* 函数?