【问题标题】:Cannot connect with a Google Service Account via php and google apiclient alpha 2.0.0无法通过 php 和 google apiclient alpha 2.0.0 连接到 Google 服务帐户
【发布时间】:2016-08-21 04:20:09
【问题描述】:

我在通过 composer 安装的 google apiclient 2.0.0 连接时遇到问题。

这是我到目前为止所做的:

我通过 composer 安装了 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 [原因短语] Unauthorized

关于我哪里出错了有什么想法吗?

提前致谢, 亚当

【问题讨论】:

    标签: php google-calendar-api google-api-php-client service-accounts


    【解决方案1】:

    您使用服务帐户的方式仅适用于访问与您的应用程序或您的服务帐户本身相关的数据。由于您希望访问 Google Calendar 数据,因此您必须是有权访问您的任何域用户数据的 Google Apps 域管理员。 Google 日历数据属于用户,因此您需要指定您尝试访问的用户。

    您需要authenticate 用户,需要获取访问令牌并传递它。如果您正在获取访问令牌,则可以调用令牌信息传递访问令牌以获取有关用户与其关联的更多信息。

    这是一个快速入门演示应用程序,请将此作为您的参考:https://developers.google.com/+/web/samples/php

    【讨论】:

    • 正确,我只想访问我自己帐户的数据。我不想访问其他用户的数据。我有一个有日历的管理员帐户。我想访问我的管理员帐户的日历并操作数据。
    猜你喜欢
    • 2022-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2019-07-24
    • 2019-02-17
    • 2015-06-12
    相关资源
    最近更新 更多