我正在尝试按照Using OAuth 2.0 for Server to Server Applications指南获取访问令牌,以便我可以使用Youtube Reporting API。
但无论我做什么,我总是这样的结果:
Warning: file_get_contents(https://www.googleapis.com/oauth2/v4/token): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
这是我的代码
$contents = file_get_contents('BCGA-557d334b8526.json');
$account = json_decode($contents, TRUE);
$privateKeyString = $account['private_key'];
$time = time();
$expiration = $time + 3600;
$header = '{"alg":"RS256","typ":"JWT"}';
$claim_set = '{"iss":"youtube-reporting@ataproject-850089.iam.gserviceaccount.com","scope":"https://www.googleapis.com/auth/yt-analytics.readonly","aud":"https://www.googleapis.com/oauth2/v4/token","exp":"' . $expiration . '","iat":"' . $time . '"}';
$unsignedToken = base64_encode($header) . '.' . base64_encode($claim_set);
$signature = hash_hmac('sha256', $unsignedToken, $privateKeyString, true);
$jwt = base64_encode($header) . '.' . base64_encode($claim_set) . '.' . base64_encode($signature);
$url = "https://www.googleapis.com/oauth2/v4/token";
$data = array('grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion' => $jwt);
// use key 'http' even if you send the request to https://...
$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($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
有什么建议吗?
答案 0 :(得分:0)
您忘记了
'grant_type' => 'refresh_token'