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

Google Analytics PHP API - Get User Email

在 google 中为 google Analytics 进行身份验证时,我也想获取用户的电子邮件 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));

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

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

从技术上讲,此方法用于列出当前经过身份验证的用户有权访问的帐户。然而,它有一点好处,它还在用户名字段中 returns 他们的电子邮件地址。

{  
   "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 都有这个隐藏的功能,你只需要弄清楚你需要调用哪个方法来获取信息。