在服务器端设置 Google 帐户而不显示帐户选择对话框

Set Google Account on Server side without showing dialog for account selection

这是我从中获取 GA 数据的代码,但它总是在浏览器中询问帐户选择。如何在 PHP 脚本中定义默认帐户。

我错过了什么?

这相当于 GA 文档中的 index.php 但我使用 Symfony 框架并决定更改此路线

/**
 * @Route("/get-google-analytics-data")
 */
public function getGoogleAnalyticsData () {
    $ga = $this->get('google_analytics_service');

    $client = new \Google_Client();
    $client->setAuthConfig(__DIR__ . '/client_secrets.json');
    $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_AnalyticsReporting($client);

        // Call the Analytics Reporting API V4.
        $response = $ga->getReport($analytics);

        // Print the response.
        return new \Symfony\Component\HttpFoundation\Response($ga->printResults($response));

    } else {
        $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback';
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));

        return $this->redirect($redirect_uri);
    }

这等同于 GA 文档中的 oauth2callback.php。

}
/**
 * @Route("/oauth2callback", name="gaOA2callback")
 */
public function gaOA2callback () {
    $client = new \Google_Client();
    $client->setAuthConfig(__DIR__ .'/client_secrets.json');
    $client->setRedirectUri('http://' . $_SERVER["HTTP_HOST"] . '/oauth2callback');
    $client->addScope(\Google_Service_Analytics::ANALYTICS_READONLY);

// Handle authorization flow from the server.
        if (! isset($_GET['code'])) {
        $auth_url = $client->createAuthUrl();
        header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));

        return $this->redirect($auth_url);
    } else {
        $client->authenticate($_GET['code']);
        $_SESSION['access_token'] = $client->getAccessToken();
        $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/get-google-analytics-data';
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));

        return $this->redirect($redirect_uri);
    }
}

首先,这是个坏主意。我用错误的方式与 GA API.

沟通
function initializeAnalytics()
    {
        // Use the developers console and download your service account
        // credentials in JSON format. Place them in this directory or
        // change the key file location if necessary.
        $KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';

        // Create and configure a new client object.
        $client = new \Google_Client();
        $client->setApplicationName("Hello Analytics Reporting");
        $client->setAuthConfig($KEY_FILE_LOCATION);
        $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly', 'https://www.googleapis.com/auth/analytics']);
        $analytics = new \Google_Service_AnalyticsReporting($client);

        return $analytics;
    }

可以看到函数中包含了.json文件。您可以从 Google 控制台仪表板从您的 OAuth 2.0 客户端 ID 下载此文件 .

https://console.developers.google.com/apis/credentials?project=&authuser=1

如果您没有这些,您将需要创建一个新的。

Most important thing, enter a valid VIEW_ID, if you do not do that you will get permission denied error and probably you will look for solution on other places.

关于权限,这个API的用户不是你的邮箱。它是服务电子邮件,zou 会在 .json 文件中找到它。您还需要为该服务电子邮件设置角色。对于基本使用,查看权限就可以了。

最后,要获取数据,您可以使用这样的函数来完成。

$VIEW_ID = "123625914"; // **视图 ID 看起来像这样,你会在你的项目的 GA 报告仪表板上找到一堆这样的视图。**

function getReport($analytics, $nameSystem) {

    // Replace with your view ID, for example XXXX.
    $VIEW_ID = "123625914"; 

    // Create the DateRange object.
    $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
    $dateRange->setStartDate("4000daysAgo");
    $dateRange->setEndDate("today");

    $today = new \Google_Service_AnalyticsReporting_DateRange();
    $today->setStartDate("today");
    $today->setEndDate("today");

    // Create the Metrics object.
    $views = new \Google_Service_AnalyticsReporting_Metric();
    $views->setExpression("ga:pageviews");
    $views->setAlias("views");

    $user = new \Google_Service_AnalyticsReporting_Metric();
    $user->setExpression("ga:users");
    $user->setAlias("user");

    $country = new \Google_Service_AnalyticsReporting_Dimension();
    $country->setName("ga:country");

    $continent = new \Google_Service_AnalyticsReporting_Dimension();
    $continent->setName("ga:continent");

    $event = new \Google_Service_AnalyticsReporting_Dimension();
    $event->setName("ga:eventLabel");
    $event->setName("ga:eventCategory");

    // Create the ReportRequest object.
    $request = new \Google_Service_AnalyticsReporting_ReportRequest();
    $request->setViewId($VIEW_ID);
    $request->setDateRanges([$dateRange, $today]);
    $request->setMetrics(array($views, $user));
    $request->setDimensions(array($event));
    $request->setFiltersExpression('ga:eventCategory==' . $nameSystem);

    $request1 = new \Google_Service_AnalyticsReporting_ReportRequest();
    $request1->setViewId($VIEW_ID);
    $request1->setDateRanges([$dateRange, $today]);
    $request1->setMetrics(array($user));
    $request1->setDimensions(array($continent, $event));
    $request->setFiltersExpression('ga:eventCategory==' . $nameSystem);

    $request2 = new \Google_Service_AnalyticsReporting_ReportRequest();
    $request2->setViewId($VIEW_ID);
    $request2->setDateRanges([$dateRange, $today]);
    $request2->setMetrics(array($user));
    $request2->setDimensions(array($event));
    $request2->setFiltersExpression('ga:eventCategory==' . $nameSystem);


    $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
    $body->setReportRequests( array( $request, $request1, $request2) );
    return $analytics->reports->batchGet( $body );
}