Google 分析报告 Api - PHP:添加用户帐户

Google Analytics Reporting Api - PHP: Add user account

我想做什么

哪里出了问题

我读了这个Google developers PHP guide。但是,示例代码连接到已与应用程序共享的第一个帐户。

我想查看一段代码,该代码要求用户提供凭据并随后提供对其帐户的访问权限。

在 Stack 上我已经找到了这个答案 Service Applications and Google Analytics API V3: Server-to-server OAuth2 authentication?。但是,提到的 APP_EMAIL 不是特定用户的电子邮件,而是 developer.gserviceaccount.com 在控制台中创建的应用程序的标识。

我也找到了这个帖子 Google Analytics Core Reporting API Version 3.0 without client login。似乎那里解决了类似的话题,但是那里缺少代码的重要部分(从我的角度来看)。

首先,确保通过将访问类型设置为离线来获取刷新令牌。 然后创建一个单独的页面进行报告。 单独的页面应该为所有报告使用帐户 ID 和刷新令牌,如果它给你一个令牌错误,你可以自己刷新它,或者将它们发送回登录页面。

您只需询问一次凭据,就可以访问所有帐户。 php 指南仅使用第一个帐户,但您可以遍历所有帐户并获得更多

$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/creds/client_secrets.json');
$client->setIncludeGrantedScopes(true);
$client->setAccessType("offline");
$client->setApprovalPrompt('force');
$client->addScope(Google_Service_Analytics::ANALYTICS_EDIT);
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);

// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
        // Set the access token on the client.
        $client->setAccessToken($_SESSION['access_token']);
        // Create an authorized analytics service object.
        $analytics = new Google_Service_Analytics($client);
        $accounts=getAccountIds($analytics);
        foreach($accounts as $acc)
        {
         var_dump($acc);
}
}
else {
        $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}