Почему Google Client API не даёт имя пользователя?

Ссылка скопирована
1 ответ

Здравствуйте.
--
Я перепробовал всё что показали в документации, это какой то кошмар.
Вот исходники https://github.com/googleapis/google-api-php-client на установку Клиента Google

Вот мой рабочий код:

<?php namespace xxxxxx;  use Yii; use Google_Client; use Google_Service_Drive; use Google_Service_Oauth2; use Google_Service_Plus; use Google_Service_Exception;     class Google  {          public $Client_Id; // Yii::$app->google->Client_Id;          public $Secret; // Yii::$app->google->Secret;          public $RedirectUri; // Yii::$app->google->RedirectUri;           public function getClientGoogle()      {         $client = new Google_Client();         $client->setClientId(Yii::$app->google->Client_Id);         $client->setClientSecret(Yii::$app->google->Secret);         $client->setRedirectUri(Yii::$app->google->RedirectUri);         $client->setScopes("email");         $loginUrl = $client->createAuthUrl();         return $loginUrl;     }      public function GetUserProfileInfo($access_token)      {	         $url = 'https://www.googleapis.com/userinfo/v2/me?fields=email,family_name,gender,given_name,hd,id,link,locale,name,picture,verified_email';	         $ch = curl_init();		         curl_setopt($ch, CURLOPT_URL, $url);		         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);         curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));         $data = json_decode(curl_exec($ch), true);         $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);		         if($http_code != 200)                  throw new Exception('Error : Failed to get user information');          return $data;     }          public function getTokenGoogle()      {         $gclient = new Google_Client();         $gclient->setClientId(Yii::$app->google->Client_Id);         $gclient->setClientSecret(Yii::$app->google->Secret);         $gclient->setRedirectUri(Yii::$app->google->RedirectUri);         $gclient->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/plus.me'));          $get = Yii::$app->request->get();         $result = $get['code'];         if($result)         {                 $token = $gclient->fetchAccessTokenWithAuthCode($result);                 $result = json_decode(json_encode($token));                   return 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='.$result->access_token;         }             } }

<?php namespace xxxxxx; use Yii; use Google_Client; use Google_Service_Drive; use Google_Service_Oauth2; use Google_Service_Plus; use Google_Service_Exception; class Google { public $Client_Id; // Yii::$app->google->Client_Id; public $Secret; // Yii::$app->google->Secret; public $RedirectUri; // Yii::$app->google->RedirectUri; public function getClientGoogle() { $client = new Google_Client(); $client->setClientId(Yii::$app->google->Client_Id); $client->setClientSecret(Yii::$app->google->Secret); $client->setRedirectUri(Yii::$app->google->RedirectUri); $client->setScopes("email"); $loginUrl = $client->createAuthUrl(); return $loginUrl; } public function GetUserProfileInfo($access_token) { $url = 'https://www.googleapis.com/userinfo/v2/me?fields=email,family_name,gender,given_name,hd,id,link,locale,name,picture,verified_email'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token)); $data = json_decode(curl_exec($ch), true); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if($http_code != 200) throw new Exception('Error : Failed to get user information'); return $data; } public function getTokenGoogle() { $gclient = new Google_Client(); $gclient->setClientId(Yii::$app->google->Client_Id); $gclient->setClientSecret(Yii::$app->google->Secret); $gclient->setRedirectUri(Yii::$app->google->RedirectUri); $gclient->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/plus.me')); $get = Yii::$app->request->get(); $result = $get['code']; if($result) { $token = $gclient->fetchAccessTokenWithAuthCode($result); $result = json_decode(json_encode($token)); return 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='.$result->access_token; } } }

Получаю:

{   "id": "*************************",   "email": "********@gmail.com",   "verified_email": true,   "picture": "https://lh3.googleusercontent.com/a-/*************************************************" }

{ "id": "*************************", "email": "********@gmail.com", "verified_email": true, "picture": "https://lh3.googleusercontent.com/a-/*************************************************" }

Как получить полные данные как в Google Console. ???

GET https://www.googleapis.com/userinfo/v2/me?fields=email%2Cfamily_name%2Cgender%2Cgiven_name%2Chd%2Cid%2Clink%2Clocale%2Cname%2Cpicture%2Cverified_email&key={YOUR_API_KEY}     Response   200   - Show headers -    {  "id": "******************",  "email": "***************@gmail.com",  "verified_email": true,  "name": "************",  "given_name": "******************",  "picture": "https://lh3.googleusercontent.com/a-/*****************************************",  "locale": "ru" }

GET https://www.googleapis.com/userinfo/v2/me?fields=email%2Cfamily_name%2Cgender%2Cgiven_name%2Chd%2Cid%2Clink%2Clocale%2Cname%2Cpicture%2Cverified_email&key={YOUR_API_KEY} Response 200 - Show headers - { "id": "******************", "email": "***************@gmail.com", "verified_email": true, "name": "************", "given_name": "******************", "picture": "https://lh3.googleusercontent.com/a-/*****************************************", "locale": "ru" }

Пробовал и с "me" и без него https://any-api.com/googleapis_com/oauth2/docs/use...

try {                 $token = $gclient->fetchAccessTokenWithAuthCode($result);                 $gclient->setAccessToken($token);                 $oAuth = new Google_Service_Oauth2($gclient);                 $data = $oAuth->userinfo_v2_me->get();                 print_r($data);             } catch (Exception $e) { // Google_Service_Exception                  echo $e->getMessage();             }

try { $token = $gclient->fetchAccessTokenWithAuthCode($result); $gclient->setAccessToken($token); $oAuth = new Google_Service_Oauth2($gclient); $data = $oAuth->userinfo_v2_me->get(); print_r($data); } catch (Exception $e) { // Google_Service_Exception echo $e->getMessage(); }

и

try {                 $token = $gclient->fetchAccessTokenWithAuthCode($result);                 $gclient->setAccessToken($token);                 $oAuth = new Google_Service_Oauth2($gclient);                 $data = $oAuth->userinfo->get();                 print_r($data);             } catch (Exception $e) { // Google_Service_Exception                  echo $e->getMessage();             }

try { $token = $gclient->fetchAccessTokenWithAuthCode($result); $gclient->setAccessToken($token); $oAuth = new Google_Service_Oauth2($gclient); $data = $oAuth->userinfo->get(); print_r($data); } catch (Exception $e) { // Google_Service_Exception echo $e->getMessage(); }

Получаю:

{   "id": "*************************",   "email": "********@gmail.com",   "verified_email": true,   "picture": "https://lh3.googleusercontent.com/a-/*************************************************" }

{ "id": "*************************", "email": "********@gmail.com", "verified_email": true, "picture": "https://lh3.googleusercontent.com/a-/*************************************************" }

Кто знает, как получить имя и фамилию пользователя, или только имя ???

Дополнительно:

Ошибка была в "скоупах", а так получается то, что нужно!

public function getClientGoogle()      {         $client = new Google_Client();         $client->setClientId(Yii::$app->google->Client_Id);         $client->setClientSecret(Yii::$app->google->Secret);         $client->setRedirectUri(Yii::$app->google->RedirectUri);         $client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/plus.me'));          $loginUrl = $client->createAuthUrl();         return $loginUrl;     }

public function getClientGoogle() { $client = new Google_Client(); $client->setClientId(Yii::$app->google->Client_Id); $client->setClientSecret(Yii::$app->google->Secret); $client->setRedirectUri(Yii::$app->google->RedirectUri); $client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/plus.me')); $loginUrl = $client->createAuthUrl(); return $loginUrl; }

Ответы:

Ну если урлы идентичны, то значит не хватает скоупов. Либо чел решил их не показывать публичным приложения, т.к. судя по доке:
https://www.googleapis.com/auth/userinfo.profile See your personal info, including any personal info you've made publicly available
via https://developers.google.com/identity/protocols/g...

  • А разве это не связано с закрытием Google+ ???

мало кода

и, вообще говоря, их возможно получить?

  • return 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='.$result->access_token;

    return 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='.$result->access_token;

    Сейчас только увидел /v1/ - тут я обращаюсь к первой версии
    ...

    public function GetUserProfileInfo($access_token)      {	         $url = 'https://www.googleapis.com/userinfo/v2/me?fields=email,family_name,gender,given_name,hd,id,link,locale,name,picture,verified_email';	         $ch = curl_init();

    public function GetUserProfileInfo($access_token) { $url = 'https://www.googleapis.com/userinfo/v2/me?fields=email,family_name,gender,given_name,hd,id,link,locale,name,picture,verified_email'; $ch = curl_init();

    - А здесь ко второй версии, https://any-api.com/googleapis_com/oauth2/docs/use... - может быть из за того что к v1 обратился, потому и получил ограниченный список, а не как здесь. Надо это тоже проверить.

    хотя я вроде как обращался к v2 $data = $oAuth->userinfo_v2_me->get(); только не делал custom fields :)

  • https://www.googleapis.com/auth/userinfo.profile

    $client->setScopes("email"); - в моём коде на самом деле иначе, это по ошибке не ту версию кода выложил. У меня вот так написано на сайте ->

    $client->setScopes("https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email");

    $client->setScopes("https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email");

Нужно решить такую задачу?

Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.

Заказать помощь
Лучший ответ
1
Сергей Миронов Ответ

Для того чтобы получить имя пользователя при использовании Google Client API, необходимо убедиться, что вы запрашиваете соответствующие разрешения для доступа к информации о пользователе.

Прежде всего, убедитесь, что вы правильно настроили ваш OAuth клиент и добавили необходимые разрешения. Для этого вам нужно создать проект в консоли разработчика Google, затем создать учетные данные OAuth 2.0 и указать правильные URI перенаправления.

После этого в вашем коде PHP вы должны запросить разрешение на доступ к информации о пользователе. Ниже приведен пример кода, показывающий как это можно сделать:

// Подключаем библиотеку Google Client API
require_once 'vendor/autoload.php';
 
// Создаем новый объект клиента
$client = new Google_Client();
$client->setAuthConfig('client_secret.json');
$client->addScope(Google_Service_PeopleService::USERINFO_PROFILE);
 
// Проверяем, авторизован ли пользователь
if ($client->isAccessTokenExpired()) {
  $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
}
 
// Получаем информацию о пользователе
$service = new Google_Service_PeopleService($client);
$user = $service->people->get('people/me', ['personFields' => 'names']);
 
// Выводим имя пользователя
echo 'Имя пользователя: ' . $user->getNames()[0]->getDisplayName();

// Подключаем библиотеку Google Client API require_once 'vendor/autoload.php'; // Создаем новый объект клиента $client = new Google_Client(); $client->setAuthConfig('client_secret.json'); $client->addScope(Google_Service_PeopleService::USERINFO_PROFILE); // Проверяем, авторизован ли пользователь if ($client->isAccessTokenExpired()) { $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); } // Получаем информацию о пользователе $service = new Google_Service_PeopleService($client); $user = $service->people->get('people/me', ['personFields' => 'names']); // Выводим имя пользователя echo 'Имя пользователя: ' . $user->getNames()[0]->getDisplayName();

Этот код запрашивает разрешение на доступ к информации о профиле пользователя и затем выводит имя пользователя. Убедитесь, что вы правильно настроили все необходимые параметры и разрешения, и вы должны успешно получить имя пользователя при использовании Google Client API.

Другие ответы (0)

Пока нет других ответов. Будьте первым, кто поможет автору.

Ответить на вопрос

комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Вам также может быть интересно