Google Analytics PHP API - 获取用户电子邮件

时间:2017-06-21 10:11:48

标签: php google-analytics google-api google-analytics-api google-api-php-client

在google Analytics for google中进行身份验证时,我想获取用户的电子邮件ID是否可以这样做,以便我该如何解决?

以下是我用于验证和保存access_token

的代码
      $scope =implode(' ', array(Google_Service_Calendar::CALENDAR_READONLY,Google_Service_Analytics::ANALYTICS_READONLY));

    $this->client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/google/callback');
    $this->client->addScope($scope);
    $this->client->setAccessType("offline");

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

    } else {
        $this->client->authenticate($_GET['code']);
        $_SESSION['access_token'] = $this->client->getAccessToken();

        if (isset($_SESSION['access_token']['refresh_token'])) {

            $this->googledbsave_model->create_google_cred($_SESSION['id'], $_SESSION['access_token']);


           if($_SESSION['id']==19){

                $access_token =  $_SESSION['access_token'];

                $update_token = array(

                    'access_token' => $access_token['access_token'],
                    'token_type' => $access_token['token_type'],
                    'expires_in' => $access_token['expires_in'],
                    'created' => $access_token['created']
                );

                $get_prof = $this->googledbsave_model->update_subadmin($_SESSION['id'], $update_token);

            }


        } else {
            $this->googledbsave_model->create_google_cred($_SESSION['id'], $_SESSION['access_token']);
            $this->revokeToken();

            $_SESSION['has_error'] = 1;
            $_SESSION['error_message'] = "Cannot Syncronise Account Properly... Please Authenticate Again";
        }


        $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/google/getProfileIDs';
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));

1 个答案:

答案 0 :(得分:1)

您正在使用Google AnalyticsAPI进行身份验证,最简单的方法是通过管理协议。做一个account summaries list

$accounts = $analytics->management_accountSummaries->listManagementAccountSummaries();

从技术上讲,此方法用于列出当前经过身份验证的用户有权访问的帐户。但是它有一点奖励,因为它还在用户名字段中返回他们的电子邮件地址。

{  
   "kind":"analytics#accountSummaries",
   "username":"xxxx@gmail.com",
   "totalResults":14,
   "startIndex":1,
   "itemsPerPage":1000,
   "items":[  
      {      
       ....
      }]
}

您也可以使用您正在使用的Google日历API执行相同操作。在主日历上执行calendar get

$calendar = $service->calendars->get('primary');

主日历是所有用户的主日历。

{
 "kind": "calendar#calendar",
 "etag": "\"E756z8zuickcYzaOnj8krCN4-Pk\"",
 "id": "xxxx@gmail.com",
 "summary": "laurly71@gmail.com",
 "timeZone": "Europe/Copenhagen"
}

很多Google API都有这个隐藏的功能,您只需要确定需要调用哪种方法来获取信息。