在PHP中获取Google YouTube API服务帐户访问令牌

时间:2014-12-12 12:28:08

标签: google-api youtube-api service-accounts

我正在尝试从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

我哪里错了?

TY!

2 个答案:

答案 0 :(得分:1)

我错过了大部分文档,如下所示:

https://developers.google.com/accounts/docs/OAuth2ServiceAccount#creatingjwt

我也错过了算法已经是RSA256而不是HSA256,因为在JWT PHP编码函数中是默认的。

此外,我需要适当地直接发送请求以获取到端点的访问令牌:

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。

答案 1 :(得分:0)

我不是一个实验者,但你应该考虑删除你在这一行末尾的“,”:

'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/

祝你好运!