Почему мои заголовки клиента Google PHP всегда пустые при попытке oauth2

ПРОБЛЕМА

Наиболее важные ошибки, которые я получаю, invalid_client а также invalid_grant, Я использую токен доступа с oauthplayground. При выборе и авторизации областей API я также заполнил опцию конфигурации, чтобы использовать свой собственный идентификатор клиента и секрет, который должен быть типа Web Application, так как Installed/Native Application а также Service Account бросить mismatch_redirect_uri ошибка, и вы не можете добавить перенаправить Uris для этих типов в консоли.

Мне нравятся многие другие посты, которые я читал с похожими проблемами, и мне нужно запустить CRON для API CURL Google с помощью PHP-клиента. Если вы можете точно объяснить, как использовать установленные учетные записи или служебные учетные записи для этой цели в веб-среде / среде LAMP, у меня все уши

EMPTY CURL DUMP: (выводится из строки 110 файла Google_CurlIO.php)

    $opts = array();
    $opts['headers'] = $requestHeaders;
    $opts['data'] = $respData;
    $opts['curl'] = curl_getinfo($ch);
    $opts['curlversion'] = curl_version();
    $opts['curlerror'] = curl_errno($ch);        
    $opts["params"] = $parsed;
    echo(json_encode($opts));        
    curl_close($ch);
    die(); // THIS DUMP RETURNS...


{
headers: {
content-type: "application/x-www-form-urlencoded",
content-length: 209
},
data: false,
curl: {
url: "https://accounts.google.com/o/oauth2/token",
content_type: null,
http_code: 0,
header_size: 0,
request_size: 0,
filetime: -1,
ssl_verify_result: 0,
redirect_count: 0,
total_time: 0.156,
namelookup_time: 0,
connect_time: 0.078,
pretransfer_time: 0,
size_upload: 0,
size_download: 0,
speed_download: 0,
speed_upload: 0,
download_content_length: -1,
upload_content_length: -1,
starttransfer_time: 0,
redirect_time: 0,
certinfo: [ ],
primary_ip: "74.125.21.84",
primary_port: 443,
local_ip: "192.168.0.108",
local_port: 64342,
redirect_url: ""
},
curlversion: {
version_number: 466432,
age: 3,
features: 3005,
ssl_version_number: 0,
version: "7.30.0",
host: "i386-pc-win32",
ssl_version: "OpenSSL/0.9.8y",
libz_version: "1.2.7",
protocols: [
"dict",
"file",
"ftp",
"ftps",
"gopher",
"http",
"https",
"imap",
"imaps",
"ldap",
"pop3",
"pop3s",
"rtsp",
"scp",
"sftp",
"smtp",
"smtps",
"telnet",
"tftp"
]
},
curlerror: 60,
params: [
"content-type: application/x-www-form-urlencoded",
"content-length: 209"
]
}

PHP-код для OAUTH2 и сделать простой отчет

    require APPPATH . 'third_party/google-api-php-client/src/Google_Client.php';
    require APPPATH . 'third_party/google-api-php-client/src/contrib/Google_YouTubeAnalyticsService.php';

    $client = new \Google_Client();
    $client->setApplicationName($settings->ApplicationName);
    $client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob'); // http://localhost

    //WEB APPLICATION
    $settings->ClientId = '1098485864880-xxx.apps.googleusercontent.com';
    $settings->AssertionCredentialsEmail = '1098485864880-xxx@developer.gserviceaccount.com';
    $settings->clientSecret = '123456789';

    //NATIVE APP
    //$settings->ClientId = '1098485864880-xxx.apps.googleusercontent.com';
    //$settings->AssertionCredentialsEmail = 'my.apis.email@gmail.com';
    //$settings->clientSecret = '123456789';

    //SERVICE APP
    //$settings->ClientId = '1098485864880-xxx.apps.googleusercontent.com';
    //$settings->AssertionCredentialsEmail = '1098485864880-xxx@developer.gserviceaccount.com';
    //$settings->clientSecret = 'notasecret';

    //$settings->AssertionCredentialsKeyFile = 'b175b0ae0f0cf40b43a25f9bce419ec2bc3740ff-privatekey.p12';
    //$settings->privateKey = file_get_contents(APPPATH .'third_party/google-api-php-client/cert/'.$settings->AssertionCredentialsKeyFile);
    //$settings->privateKeyPassword = 'notasecret';

    //$client->refreshToken("1/xxx-yyy");
    $client->setAccessToken('{
     "access_token" : "ya29.1.xxx",
     "token_type" : "Bearer",
     "expires_in" : 3600,
     "created" : 1, // this is NOT actually provided by the oauthplayground
     "refresh_token" : "1/xxx-yyy"
   }'); 

    $redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL);
    $settings->assertionType = 'http://oauth.net/grant_type/jwt/1.0/bearer';

    $client->setRedirectUri($redirect);
    $client->setClientId($settings->ClientId);
    $client->setScopes($settings->AssertionCredentialsPerms);

    //$client->setAssertionCredentials(new \Google_AssertionCredentials(
    //$settings->ApplicationName, $settings->AssertionCredentialsPerms,
    //$settings->privateKey, $settings->privateKeyPassword, $settings->assertionType,
    //$settings->AssertionCredentialsEmail
    //));

    $this->ytservice = new \Google_YouTubeAnalyticsService($client);

    $id = 'contentOwner==aContentOwner';
    $start_date = '2013-01-01';
    $end_date = '2014-01-01';
    $optparams = array('dimensions' => '7DayTotals','sort' => 'day');
    $metrics = array('views','estimatedMinutesWatched','averageViewDuration','comments','favoritesAdded','favoritesRemoved','likes','dislikes','shares','subscribersGained','subscribersLost');

    $api_response = $metrics;
    foreach ($metrics as $metric){ 
        $api = $this->ytservice->reports->query($id, $start_date, $end_date, $metric, $optparams);
        if (isset($api['rows'])) $api_response[$metric] = $api['rows'][0][0];
    }

    return $this->ytservice;

1 ответ

Я читаю первую часть вашего вопроса.

Токен обновления не является токеном доступа: это токен, используемый для получения токена доступа.

Я предполагаю, что вы не используете токен обновления вместо токена доступа. Также обратите внимание, что токен обновления не нужен для доступа к защищенному ресурсу: для него нужен токен доступа.

Другие вопросы по тегам