我正在尝试从Google获取访问令牌,以便我可以使用"服务帐户"自动将视频上传到YouTube。
此代码:
$credentials = array(
'client_id' => $my_client_id
);
$jwt = JWT::encode($credentials, $private_key);
$client = new Google_Client();
if ($client->authenticate($jwt))
{
// do something
}
失败,出现以下异常:
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error fetching OAuth2 access token, message: 'invalid_request: Client must specify either client_id or client_assertion, not both'' in /home/google/client/google-api-php-client/src/Google/Auth/OAuth2.php:120
我哪里出错了?
泰!
我错过了文档的很大一部分,如下所示:
https://developers.google.com/accounts/docs/OAuth2ServiceAccount#creatingjwt
我还错过了算法必须是 RSA256 而不是 JWT PHP 编码函数中默认的 HSA256。
此外,我需要适当地直接发布请求以获取到终结点的访问令牌:
https://www.googleapis.com/oauth2/v3/token
服务帐号的 Google 私有 JSON 私钥也无效,无法被 openssl 使用,因为最后一个字符被编码/包含为:
\u003d
从字面上看,将其替换为:
=
解决了这个问题。
这是我现在的工作(ish,见结束语句(代码:
$claimset = array(
'iss' => $client_email,
'scope' => 'https://www.googleapis.com/auth/youtube.upload',
'aud' => 'https://www.googleapis.com/oauth2/v3/token',
'exp' => time() + 1800,
'iat' => time(),
'sub' => 'my google account email@gmail.com'); // not sure if reqd
$jwt = JWT::encode($claimset, $private_key, 'RS256');
// Now need to get a token by posting the above to:
// https://www.googleapis.com/oauth2/v3/token
# Our new data
$data = array(
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $jwt
);
# Create a connection
$url = 'https://www.googleapis.com/oauth2/v3/token';
$ch = curl_init($url);
# Form data string
$postString = http_build_query($data, '', '&');
# Setting our options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
# Get the response
$response = curl_exec($ch);
curl_close($ch);
print "and here is what we got: ";
print_r($response);
exit;
不幸的是,由于某种原因,我得到的回应是:
{ "错误": "unauthorized_client", "error_description": "请求中存在未经授权的客户端或范围。
}怀疑我的服务帐户尚无权上传到 YouTube。
我不是经验者,但您可能应该考虑删除此处行末尾的",":
'client_id' => $private_key['client_id'],
//'client_email' => $private_ket['client_email']
更改为:
'client_id' => $private_key['client_id']
//'client_email' => $private_ket['client_email']
我用这个例子来让 oauth 工作。它可能会有所帮助:http://msdn.microsoft.com/en-us/library/dn632721.aspx
您也可以在此处尝试 OAuth 测试:https://developers.google.com/oauthplayground/
祝你好运!