如何从Outlook Mail REST API v1迁移到Graph API

时间:2018-07-29 19:11:20

标签: api email graph outlook

我当前正在使用Outlook Mail REST API v1在PHP中检索服务器端的邮件。 这很容易做到,并且只需使用基本身份验证即可处理一行代码:

json_decode(file_get_contents("https://<user>:<pass>@outlook.office365.com/api/v1.0/me/folders/inbox/messages"));

不幸的是,该API已被弃用,很快将无法使用,因此我想切换到较新的Graph API。

我在“ apps.dev.microsoft.com”下添加了我的应用程序,创建了一个客户端密钥,并在应用程序权限下添加了“ Mail.Read”(“允许该应用程序在没有登录用户的情况下读取所有邮箱中的邮件。”

使用下面的代码(https://developer.microsoft.com/en-us/graph/docs/concepts/auth_v2_service#4-get-an-access-token),我可以检索令牌:

$url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
$data = [
    "client_id" => "<client_id>",
    "client_secret" => "<client_secret>",
    "scope" => "https://graph.microsoft.com/.default",
    "grant_type" => "client_credentials"
];

$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);
$context = stream_context_create($options);
$response = json_decode(file_get_contents($url, false, $context));

响应中包含一个“ Bearer”类型的访问令牌,看起来很不错。

因此,我想使用这样的令牌检索邮件:

$url = 'https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages';

$options = array(
    'http' => array(
        'header'  => "Authorization: Bearer " . $response->access_token,
        'method'  => 'GET'
    )
);
$context = stream_context_create($options);
$data = json_decode(file_get_contents($url, false, $context));

不幸的是,我现在被这个警告困住了:

Warning: file_get_contents(https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request

我不知道从这里去哪里,可能是URL错误或范围问题或我缺少一些授权。该文档对我来说很混乱,没有帮助。

0 个答案:

没有答案