我在通过作曲家安装的谷歌 apiclient 2.0.0 连接时遇到问题。
这是我到目前为止所做的:
我通过作曲家安装了apiclient。
我转到 https://console.cloud.google.com/apis/credentials?my-project 并导航到 API 管理器>凭据页面。
我为服务帐户创建了凭据并下载了 json。然后我把 json 上传到我的服务器。
我通过管理我的服务帐户为帐户启用了域范围委派。
我在"域名验证"选项卡下验证了我的域名。
接下来,我导航到我的日历,并使用与我的服务帐户关联的电子邮件地址共享日历,从而授予管理访问权限。
然后,我与服务帐户的电子邮件地址共享了我的日历。
现在我正在尝试使用 api 进行连接并遇到授权问题。
$json_file = '/path/to/service-account-credentials.json';
$scopes = [
Google_Service_Calendar::CALENDAR,
Google_Service_Calendar::CALENDAR_READONLY
];
// create a new client and authorize
$client = new Google_Client();
// set the basic information of the client
$client->setApplicationName("Apointments");
$client->setSubject( email-address-to-masquerade-as@mycompany.com );
$client->setAccessType('offline');
// load the json credential file
$client->setAuthConfig( $json_file );
$client->setScopes( $scopes );
// check to see if the token is stored in the session
if( isset( $_SESSION['service_token'] ) )
{
// token was stored, use it with the cilent
$client->setAccessToken( $_SESSION['service_token'] );
}
// test the authorization to see if it is expired
if( $client->isAccessTokenExpired() )
{
// Failed authorization, get a new token
$client->refreshTokenWithAssertion();
}
// store the token in the session
$_SESSION['service_token'] = $client->getAccessToken();
从堆栈跟踪中,我已确定有问题的代码行是:
$client->refreshTokenWithAssertion();
这将产生一条错误消息:
客户端错误响应 [url] https://www.googleapis.com/oauth2/v4/token [状态代码] 401 [原因短语] 未授权
关于我哪里出了问题有什么想法吗?
提前感谢,亚当
使用服务帐户的方式仅对访问与应用程序或服务帐户本身相关的数据有效。由于您希望访问Google Calendar
数据,因此您必须是 Google Apps 网域管理员,有权访问您网域用户的任何数据。Google 日历数据属于用户,因此您需要指定尝试访问的用户。
您需要authenticate
用户,需要获取访问令牌并通过该令牌。如果要获取访问令牌,可以调用传递访问令牌的令牌信息,以获取有关用户与其关联的用户的详细信息。
下面是一个快速入门演示应用,请以此作为参考:https://developers.google.com/+/web/samples/php