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

时间:2017-06-08 07:14:35

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

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

1 个答案:

答案 0 :(得分:0)

首先,这是个坏主意。我使用了与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的用户不是您的电子邮件。这是服务电子邮件,你会在.json文件中找到它。此外,您还需要为该服务电子邮件设置角色。对于基本用途,查看权限就可以了。

最后,为了获取数据,你可以用这样的函数来做到这一点。

$ VIEW_ID =“123625914”; // **视图ID看起来像这样,你会在GA Reporting Dashboard上找到适合你项目的那些vieew。**

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