使用PHP通过REST调用Xbox Services API遇授权及请求错误求助
访问Xbox Services API遇到的授权及请求问题
作为学习练习,我尝试通过REST接口访问Xbox Services API,缺乏API使用经验,参照微软《MS users batch profile settings post》指南编写了PHP POST请求代码:
$url = "https://profile.xboxlive.com/users/batch/profile/settings"; $data = array( "userIds" => ["2533274791381930"], "settings" => ["GameDisplayName", "GameDisplayPicRaw", "Gamerscore", "Gamertag"] ); $options = array( 'http' => array( 'header' => "x-xbl-contract-version: 2\r\n". "Content-Type: application/json\r\n", 'method' => 'POST', 'content' => json_encode($data), ), ); $context = stream_context_create($options); $result = file_get_contents($url, false, $context); echo $result;
运行后出现错误:
Warning: file_get_contents(https://profile.xboxlive.com/users/batch/profile/settings): Failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized
该错误提示需要授权,但指南未提及令牌相关内容。我在Azure Portal配置应用后,更新代码添加了AccessToken获取逻辑:
$clientId = 'xxxxxxxxxxxxxxxxxxx'; $clientSecret = 'yyyyyyyyyyyyyyyyyyyy'; $grantType = 'client_credentials'; $scope = 'https://graph.microsoft.com/.default'; // Get an access token $tokenUrl = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'; $data = array( 'client_id' => $clientId, 'client_secret' => $clientSecret, 'grant_type' => $grantType, 'scope' => $scope ); $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); $result = file_get_contents($tokenUrl, false, $context); $accessToken = json_decode($result)->access_token; // Make a request to the API $url = "https://profile.xboxlive.com/users/batch/profile/settings"; $data = array( "userIds" => ["2533274791381930"], "settings" => ["GameDisplayName", "GameDisplayPicRaw", "Gamerscore", "Gamertag"] ); $options = array( 'http' => array( 'header' => "Authorization: Bearer ".$accessToken."\r\n". "x-xbl-contract-version: 2\r\n". "Content-Type: application/json\r\n", 'method' => 'POST', 'content' => json_encode($data), ), ); $context = stream_context_create($options); $result = file_get_contents($url, false, $context); echo $result;
运行后出现新错误:
file_get_contents(https://login.microsoftonline.com/common/oauth2/v2.0/token): Failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
我不确定当前方向是否正确,感觉代码本身没问题但可能遗漏了步骤,全程只用PHP实现未使用中间件或第三方API。另外想了解是否必须加入Xbox Live创作者计划才能访问该API,网上相关信息存在冲突,恳请技术建议。
内容的提问来源于stack exchange,提问作者Dan Twining
相关产品推荐
相关产品推荐

