AgentSmith72
@AgentSmith72
JS - это моё хобби

Как получить телефон из Google OAuth 2.0 API?

Есть сервис
class GoogleService
{
    public function getClient(): \Google_Client
    {
        $configJson = base_path().'/config/google-oauth.json';
        $applicationName = 'Some';

        $client = new \Google_Client();
        $client->setApplicationName($applicationName);
        $client->setAuthConfig($configJson);
        $client->setAccessType('offline');
        $client->setApprovalPrompt ('force');

        $redirectUri = env('GOOGLE_REDIRECT_URI');
        $client->setRedirectUri($redirectUri);

        $client->setScopes(
            [
                \Google\Service\Oauth2::USERINFO_PROFILE,
                \Google\Service\Oauth2::USERINFO_EMAIL,
                \Google\Service\Oauth2::OPENID,
                \Google\Service\Drive::DRIVE_METADATA_READONLY,
                'https://www.googleapis.com/auth/user.phonenumbers.read',
                'https://www.googleapis.com/auth/contacts.readonly',
            ]
        );
        $client->setIncludeGrantedScopes(true);

        return $client;
    }

    public function oauth(string $code)
    {
        $client = $this->getClient();
        $client->authenticate($code);

        $oauth2Service = new Oauth2($client);
        $userInfo = $oauth2Service->userinfo->get();

        return $userInfo;
    }
}


в итоге $oauth2Service->userinfo->get(); возвращает объект без телефона.
В настройках Гугл консоли добавил People API
  • Вопрос задан
  • 55 просмотров
Пригласить эксперта
Ответы на вопрос 1
AgentSmith72
@AgentSmith72 Автор вопроса
JS - это моё хобби
Сервис
работает нормально, если есть лучший способ, буду признателен, если поделитесь.
class GoogleService
{
    public function getClient(): \Google_Client
    {
        $configJson = base_path().'/config/google-oauth.json';
        $applicationName = 'Some';

        $client = new \Google_Client();
        $client->setApplicationName($applicationName);
        $client->setAuthConfig($configJson);
        $client->setAccessType('offline');
        $client->setApprovalPrompt ('force');

        $redirectUri = env('GOOGLE_REDIRECT_URI');
        $client->setRedirectUri($redirectUri);

        $client->setScopes(
            [
                \Google\Service\Oauth2::USERINFO_EMAIL,
                \Google\Service\Oauth2::OPENID
            ]
        );
        $client->setIncludeGrantedScopes(true);

        return $client;
    }

    public function fetchUserData(string $code)
    {
        $data = [];
        $client = $this->getClient();
        $client->authenticate($code);

        $oauth2Service = new Oauth2($client);
        $userInfo = $oauth2Service->userinfo->get();
        $data['userInfo'] = $userInfo;

        $client->fetchAccessTokenWithAuthCode($code);
        $accessToken = $client->getAccessToken();
        $accessToken['grant_type'] = 'urn:ietf:params:oauth:grant-type:jwt-bearer';

        $guzzleClient = new GuzzleClient();
        $response = $guzzleClient->request('GET', "https://people.googleapis.com/v1/people/{$userInfo->id}?personFields=phoneNumbers,birthdays,genders", [
            'headers' => [
                'Authorization' => 'Bearer ' . $accessToken['access_token'],
            ],
        ]);

        $data['personal'] = json_decode($response->getBody()->getContents(), true);
        
        return $data;
    }
}

Получаем телефон, день рождение, пол из настроек профиля пользователя в гугл с помошью php.
Ответ написан
Комментировать
Ваш ответ на вопрос

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

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