Подтвердить что ты не робот

Как получить электронную почту пользователя с токеном доступа google?

Я выполнил все эти шаги.

https://developers.google.com/+/web/signin/

У меня есть идентификатор клиента и секрет клиента.

Теперь я получил токен доступа, как я могу получить профиль пользователя и адрес электронной почты с токеном доступа? И как проверить, зарегистрирован ли пользователь или нет?

4b9b3361

Ответ 1

Используя OAuth2, вы можете запросить разрешения через параметр области. (Документация.) Я предполагаю, что области, которые вы хотите, https://www.googleapis.com/auth/userinfo.email и https://www.googleapis.com/auth/userinfo.profile.

Тогда просто получить информацию о профиле, как только вы получите токен доступа. (Я предполагаю, что вы смогли выкупить возвращаемый код авторизации для токена доступа?) Просто сделайте запрос на https://www.googleapis.com/oauth2/v1/userinfo?access_token= {accessToken}, который возвращает JSON массива данных профиля, включая электронную почту:

{
    "id": "00000000000000",
    "email": "[email protected]",
    "verified_email": true,
    "name": "Fred Example",
    "given_name": "Fred",
    "family_name": "Example",
    "picture": "https://lh5.googleusercontent.com/-2Sv-4bBMLLA/AAAAAAAAAAI/AAAAAAAAABo/bEG4kI2mG0I/photo.jpg",
    "gender": "male",
    "locale": "en-US"
}

Нет гарантий, но попробуйте следующее:

$url = "https://www.googleapis.com/oauth2/v1/userinfo";
$request = apiClient::$io->makeRequest($client->sign(new apiHttpRequest($url, 'GET')));

if ((int)$request->getResponseHttpCode() == 200) {
    $response = $request->getResponseBody();
    $decodedResponse = json_decode($response, true);
    //process user info
  } else {
    $response = $request->getResponseBody();
    $decodedResponse = json_decode($response, true);
    if ($decodedResponse != $response && $decodedResponse != null && $decodedResponse['error']) {
      $response = $decodedResponse['error'];
    }
  }
}

Ответ 2

попробуйте это

$accessToken = 'access token';
$userDetails = file_get_contents('https://www.googleapis.com/oauth2/v1/userinfo?access_token=' . $accessToken);
$userData = json_decode($userDetails);

if (!empty($userData)) {

  $googleUserId = '';
  $googleEmail = '';
  $googleVerified = '';
  $googleName = '';
  $googleUserName = '';

  if (isset($userData->id)) {
    $googleUserId = $userData->id;
  }
  if (isset($userData->email)) {
    $googleEmail = $userData->email;
    $googleEmailParts = explode("@", $googleEmail);
    $googleUserName = $googleEmailParts[0];
  }
  if (isset($userData->verified_email)) {
    $googleVerified = $userData->verified_email;
  }
  if (isset($userData->name)) {
    $googleName = $userData->name;
  }
} else {

  echo "Not logged In";
}

Ответ 3

Вы просто добавляете эту строку в свой scope Откройте Application.cfc, а затем добавьте этот код

     <cfset request.oauthSettings = 
           {scope = "https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile",
                                    client_id = "Your-id",
                                    client_secret = "your-secret",
                                    redirect_uri = "redirect-page",
                                    state = "optional"} />

Теперь вы можете получать электронную почту от функции, которую вы можете вызвать следующим образом

    <cfscript>              
        public function getProfile(accesstoken) {

            var h = new com.adobe.coldfusion.http();
            h.setURL("https://www.googleapis.com/oauth2/v1/userinfo");
            h.setMethod("get");
            h.addParam(type="header",name="Authorization",value="OAuth #accesstoken#");
            h.addParam(type="header",name="GData-Version",value="3");
            h.setResolveURL(true);
            var result = h.send().getPrefix();
            return deserializeJSON(result.filecontent.toString());
        }       
    </cfscript>

            <cfoutput>
            <cfset show = getProfile(session.ga_accessToken)>
            <cfdump var="#show#">
           </cfoutput>

Надеюсь, это поможет многим людям решить эту проблему.:)