Isolution666
@Isolution666
Full-Stack Developer

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

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

Вот мой рабочий код:
<?php
namespace xxx\xxx;

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-/*************************************************"
}


Как получить полные данные как в 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"
}


Пробовал и с "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->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-/*************************************************"
}


Кто знает, как получить имя и фамилию пользователя, или только имя ???
  • Вопрос задан
  • 794 просмотра
Решения вопроса 1
Isolution666
@Isolution666 Автор вопроса
Full-Stack Developer
Ошибка была в "скоупах", а так получается то, что нужно!
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;
    }
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 2
@grinat
Ну если урлы идентичны, то значит не хватает скоупов. Либо чел решил их не показывать публичным приложения, т.к. судя по доке:
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...
Ответ написан
dimonchik2013
@dimonchik2013
non progredi est regredi
мало кода

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

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы