Graph API无法正确检索数据

时间:2019-02-08 07:17:58

标签: php api microsoft-graph microsoft-graph-sdks

我正在使用Microsoft graph APIhttps://github.com/microsoftgraph/msgraph-sdk-php)通过php SDK从Microsoft帐户检索我的消息。

我的代码示例如下

<?php

// Autoload files using the Composer autoloader.
require_once __DIR__ . '/vendor/autoload.php';

use Microsoft\Graph\Graph;
use Microsoft\Graph\Model;


    //get the access token to access graph api
    $tenantId = "XXXXXX";
    $clientId = "XXXXXXXXXXXX";
    $clientSecret = "XXXXXXXXXXX";

    $guzzleClient = new \GuzzleHttp\Client(array('curl' => array( CURLOPT_SSL_VERIFYPEER => false)));
    $url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token?api-version=1.0';
    $token = json_decode($guzzleClient->post($url, [
        'form_params' => [
            'client_id' => $clientId,
            'client_secret' => $clientSecret,
            'resource' => 'https://graph.microsoft.com/',
            'grant_type' => 'client_credentials',
        ],
    ])->getBody()->getContents());
    $accessToken = $token->access_token;

    //get the messages of user
    $graph = new Graph();
    $graph->setAccessToken($accessToken);

    $messages = $graph->createRequest("GET", "/me/messages")
                    ->setReturnType(Model\User::class)
                    ->execute();
    print_r($messages); exit;

但这会引发如下错误:

  

致命错误:未捕获的GuzzleHttp \ Exception \ ClientException:客户端错误:GET https://graph.microsoft.com/v1.0/me/messages导致400 Bad Request响应:{“错误”:{“代码”:“ BadRequest”,“消息”:“当前经过身份验证的上下文对此请求无效。(被截断...)在第113行的C:\ wamp64 \ www \ graph_api \ vendor \ guzzlehttp \ guzzle \ src \ Exception \ RequestException.php中

enter image description here

这是由于访问Graph API的权限问题引起的吗?我在Microsoft app registration portal

中设置了以下权限

enter image description here

以及天蓝色的门户网站

enter image description here

什么可能导致此问题?有什么办法解决问题吗?

1 个答案:

答案 0 :(得分:5)

您遇到了例外情况:

  

当前已认证的上下文对此请求无效

因为获取的令牌用于应用程序许可(client credentials flow)。在此流程中,Me没有上下文,因为它表示已登录的用户上下文

要获取客户端凭据流中的消息,需要在端点中明确解析用户:

https://graph.microsoft.com/v1.0/users/{user-id}/messages 

示例

$userId = "--user-id-goes-here--";

$messages = $graph->createRequest("GET", "/users/{$userId}/messages")
    ->setReturnType(\Microsoft\Graph\Model\User::class)
    ->execute();