YouTube oauth как запросить данные аккаунта

Итак, используя документацию youtube oauth, я придумал такой способ получения токена доступа:

      /**
         * Get api authorization
         *
         * @return string
         */
        public function getAuthorizationUrl()
        {
            // Make redirect
            $this->params = [
                'client_id'    => '######',
                'redirect_uri' => '######',
                'scope'        => 'https://www.googleapis.com/auth/youtube',
                'response_type'=> 'code',
                'access_type'  => 'offline'
            ];
            $redirect_url = 'https://accounts.google.com/o/oauth2/auth?' . http_build_query($this->params);
            return $redirect_url;
        }

        /**
         * Get API token and save account list to db
         *
         * @param $code
         *
         * @return \App\Models\DynamicDashboard\ThirdPartyAccounts
         */
        public function getCallbackUrl($code)
        {

            // Grab the returned code and extract the access token.
            $this->params = [
                'code'          => $code,
                'client_id'     => '#####',
                'client_secret' => '######',
                'redirect_uri'  => '######',
                'grant_type'    => 'authorization_code'
            ];

        // Get access token
        $command = 'curl --data "' . http_build_query($this->params) . '" https://accounts.google.com/o/oauth2/token';
        exec($command, $token);
        $output = implode('', $token);
        $token = json_decode($output);

        // Do a request using the access token to get the list of accounts.
        $command = 'curl -H "Authorization: Bearer ' . $token->access_token . '" https://www.googleapis.com/oauth2/v1/userinfo';
        $result = $this->getRequest($command);

        //Do a request using the access token to get youtube account id.
        $command = 'curl -H "Authorization: Bearer ' . $token->access_token  . '"http://gdata.youtube.com/feeds/api/users/default?v=2';
        exec($command, $youtube);
        var_dump($youtube); exit;

        //Do a request using the access token to get channel id.
        $command = 'curl -H "Authorization: Bearer ' . $token->access_token  . '"https://www.googleapis.com/youtube/v3/channels?part=id&mine=true';
        exec($command, $channel);
        $outputChannel = implode('', $channel);
        $channelId = json_decode($outputChannel);
    }

var_dump из $youtube возвращает пустой массив:

array {  
       }

Итак, прямо сейчас мне удалось сохранить учетную запись Google, но как я могу получить из этой учетной записи идентификатор учетной записи YouTube или идентификатор канала? Я пытался сделать это вот так:

            //Do a request using the access token to get youtube account id.
            $command = 'curl -H "Authorization: Bearer ' . $token->access_token  . '"http://gdata.youtube.com/feeds/api/users/default?v=2';
            exec($command, $youtube);
            var_dump($youtube); exit;

            //Do a request using the access token to get channel id.
            $command = 'curl -H "Authorization: Bearer ' . $token->access_token  . '"https://www.googleapis.com/youtube/v3/channels?part=id&mine=true';
            exec($command, $channel);
            $outputChannel = implode('', $channel);
            $channelId = json_decode($outputChannel);

Но обе переменные: $youtube и $channelId возвращают пустой массив. Кто-нибудь может сказать мне, пожалуйста, почему? Спасибо за помощь!


person Alan    schedule 08.09.2016    source источник
comment
Вы имеете в виду google plus id   -  person Kumar    schedule 09.09.2016
comment
да, извините, моя ошибка, и информация об учетной записи, такая как имя профиля   -  person Alan    schedule 09.09.2016
comment
означает, что у вас есть токен доступа, и, используя токен доступа, вы хотите получить идентификатор и имя профиля, верно?   -  person Kumar    schedule 10.09.2016
comment
на самом деле это то, что я имею в виду   -  person Alan    schedule 12.09.2016


Ответы (1)


Я нашел это сообщение SO, которое может помощь в получении идентификатора пользователя после входа в систему через google oauth. Вам нужен вызов GET для https://www.googleapis.com/oauth2/v1/userinfo с правильным токеном доступа. В ответ включен идентификатор пользователя. Вот документация.

Этот ответ также может помочь.

Если вы спрашиваете, как получить имя пользователя YouTube или идентификатор пользователя YouTube для текущего аутентифицированного пользователя, его можно найти в ответе на правильно аутентифицированный запрос к http://gdata.youtube.com/feeds/api/users/default?v=2.

person abielita    schedule 09.09.2016
comment
Я сохранил учетную запись Google Plus, но не знаю, как получить такие сведения, как идентификатор канала YouTube. Когда я пытаюсь выполнить запрос, он возвращает пустой массив. Я отредактировал свой вопрос. - person Alan; 12.09.2016