【问题标题】:Set Google Account on Server side without showing dialog for account selection在服务器端设置 Google 帐户而不显示帐户选择对话框
【发布时间】:2017-11-09 18:33:50
【问题描述】:

这是我从中获取 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);
    }
}

【问题讨论】:

    标签: php symfony oauth-2.0 google-analytics-api


    【解决方案1】:

    首先,这是一个坏主意。我使用了错误的方式与 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 文件。您可以通过 OAuth 2.0 客户端 ID 从 Google 控制台仪表板下载此文件 .

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

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

    最重要的是,输入一个有效的 VIEW_ID,如果你不这样做,你 将获得权限被拒绝错误,您可能会寻找 其他地方的解决方案。

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

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

    $VIEW_ID = "123625914"; // **view ID 是这样的,您会在 GA Reporting Dashboard 上为您的项目找到一堆这些视图。**

    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 );
    } 
    

    【讨论】:

      猜你喜欢
      • 2014-01-07
      • 2013-10-11
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      • 2017-02-09
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      相关资源
      最近更新 更多