2015-09-02 5 views
0

Я просто запустил код примера из https://developers.google.com/api-client-library/php/auth/service-accounts для получения токена доступа.Google_Auth_Exception: ошибка обновления токена OAuth2, сообщение: '{"error": "invalid_grant"}'

Но я получаю следующее сообщение об ошибке из моего кода

Google_Auth_Exception: Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }' in C:\xampp\htdocs\youtubeapi\Google\Auth\OAuth2.php on line 363 

Мой код

<?php 

require_once 'Google/autoload.php'; 

$client_email = '[email protected]'; 
$private_key = file_get_contents('MyProject.p12'); 
$scopes = array('https://www.googleapis.com/auth/sqlservice.admin'); 

$credentials = new Google_Auth_AssertionCredentials(
    $client_email, 
    $scopes, 
    $private_key 
); 

$client = new Google_Client(); 
$client->setAssertionCredentials($credentials); 
if ($client->getAuth()->isAccessTokenExpired()) { 
    $client->getAuth()->refreshTokenWithAssertion(); 
    echo "dfdsf"; 
} 

$sqladmin = new Google_Service_SQLAdmin($client); 
$response = $sqladmin->instances 
    ->listInstances('examinable-example-123')->getItems(); 
echo json_encode($response) . "\n"; 
?> 

пожалуйста, помогите. В чем проблема?

код Обновление

<?php 

// Call set_include_path() as needed to point to your client library. 
require_once 'Google/autoload.php'; 
require_once 'Google/Client.php'; 
require_once 'Google/Service/YouTube.php'; 
session_start(); 
//'2015-08-28T00:00:00.000Z' 
//'2015-08-29T00:00:00.000Z' 
/* 
* You can acquire an OAuth 2.0 client ID and client secret from the 
* Google Developers Console <https://console.developers.google.com/> 
* For more information about using OAuth 2.0 to access Google APIs, please see: 
* <https://developers.google.com/youtube/v3/guides/authentication> 
* Please ensure that you have enabled the YouTube Data API for your project. 
*/ 


$client_id = 'dfgdfgdfg.apps.googleusercontent.com'; 
    $Email_address = '[email protected]'; 
    $key_file_location = 'Youtube API-asdasd.p12';  
    $htmlBody=""; 
    $client = new Google_Client();  
    $client->setApplicationName("Youtube API"); 
    $key = file_get_contents($key_file_location);  

    // seproate additional scopes with a comma 
    $scopes ="https://www.googleapis.com/auth/analytics.readonly"; 

    $cred = new Google_Auth_AssertionCredentials($Email_address,   
          array($scopes),   
          $key);  

    $client->setAssertionCredentials($cred); 
    $youtube = new Google_Service_YouTube($client); 
    if($client->getAuth()->isAccessTokenExpired()) {   
     $client->getAuth()->refreshTokenWithAssertion($cred);  
    } 
    $_SESSION['token'] = $client->getAccessToken(); 
if (isset($_SESSION['token'])) { 
    $client->setAccessToken($_SESSION['token']); 
} 
// Check to ensure that the access token was successfully acquired. 
if ($client->getAccessToken()) { 
if(isset($_POST['title']) && isset($_POST['timeStart']) && isset($_POST['timeEnd']) && isset($_POST['Status']) && isset($_POST['dateStart']) && isset($_POST['dateEnd'])) 
{ 
    try { 

    // Create an object for the liveBroadcast resource's snippet. Specify values 
    // for the snippet's title, scheduled start time, and scheduled end time. 
    $startTime = $_POST['dateStart']."T".$_POST['timeStart'].":00+0530"; 
    $endTime = $_POST['dateEnd']."T".$_POST['timeEnd'].":00+0530"; 
    //$startDatetime = new DateTime($startTime); 
    //$endDatetime = new DateTime($endTime); 

    //$startDatetime = $startDatetime->format(DateTime::ISO8601); 
    //$endDatetime = $endDatetime->format(DateTime::ISO8601); 
    $broadcastSnippet = new Google_Service_YouTube_LiveBroadcastSnippet(); 
    $broadcastSnippet->setTitle($_POST['title']); 
    $broadcastSnippet->setScheduledStartTime($startTime); 
    $broadcastSnippet->setScheduledEndTime($endTime); 

    // Create an object for the liveBroadcast resource's status, and set the 
    // broadcast's status to "private". 
    $status = new Google_Service_YouTube_LiveBroadcastStatus(); 
    $status->setPrivacyStatus($_POST['Status']); 

    // Create the API request that inserts the liveBroadcast resource. 
    $broadcastInsert = new Google_Service_YouTube_LiveBroadcast(); 
    $broadcastInsert->setSnippet($broadcastSnippet); 
    $broadcastInsert->setStatus($status); 
    $broadcastInsert->setKind('youtube#liveBroadcast'); 

    // Execute the request and return an object that contains information 
    // about the new broadcast. 
    $broadcastsResponse = $youtube->liveBroadcasts->insert('snippet,status', 
     $broadcastInsert, array()); 

    // Create an object for the liveStream resource's snippet. Specify a value 
    // for the snippet's title. 
    $streamSnippet = new Google_Service_YouTube_LiveStreamSnippet(); 
    $streamSnippet->setTitle('New Stream'); 

    // Create an object for content distribution network details for the live 
    // stream and specify the stream's format and ingestion type. 
    $cdn = new Google_Service_YouTube_CdnSettings(); 
    $cdn->setFormat("1080p"); 
    $cdn->setIngestionType('rtmp'); 

    // Create the API request that inserts the liveStream resource. 
    $streamInsert = new Google_Service_YouTube_LiveStream(); 
    $streamInsert->setSnippet($streamSnippet); 
    $streamInsert->setCdn($cdn); 
    $streamInsert->setKind('youtube#liveStream'); 

    // Execute the request and return an object that contains information 
    // about the new stream. 
    $streamsResponse = $youtube->liveStreams->insert('snippet,cdn', 
     $streamInsert, array()); 

    // Bind the broadcast to the live stream. 
    $bindBroadcastResponse = $youtube->liveBroadcasts->bind(
     $broadcastsResponse['id'],'id,contentDetails', 
     array(
      'streamId' => $streamsResponse['id'], 
     )); 

    $htmlBody .= "<h3>Added Broadcast</h3><ul>"; 
    $htmlBody .= sprintf('<li>%s published at %s (%s)</li>', 
     $broadcastsResponse['snippet']['title'], 
     $broadcastsResponse['snippet']['publishedAt'], 
     $broadcastsResponse['id']); 
    $htmlBody .= '</ul>'; 
    $htmlBody .= "<h3>Added Stream</h3><ul>"; 
    $htmlBody .= sprintf('<li>%s (%s)</li>', 
     $streamsResponse['snippet']['title'], 
     $streamsResponse['id']); 
    $htmlBody .= '</ul>'; 
    $htmlBody .= "<h3>Bound Broadcast</h3><ul>"; 
    $htmlBody .= sprintf('<li>Broadcast (%s) was bound to stream (%s).</li>', 
     $bindBroadcastResponse['id'], 
     $bindBroadcastResponse['contentDetails']['boundStreamId']); 
    $htmlBody .= '</ul>'; 
    //$htmlBody .="<h3>Live Broadcast</h3><div>"; 

    //$htmlBody .= sprintf("<iframe id='ytplayer' type='text/html' width='640' height='390' src='http://www.youtube.com/embed/%s?autoplay=1' frameborder='0'></iframe>", 
     // $broadcastsResponse['id']); 
    $htmlBody .= '</div>'; 


    } catch (Google_Service_Exception $e) { 
    $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>', 
     htmlspecialchars($e->getMessage())); 
     // echo $e->getMessage(); 
    } catch (Google_Exception $e) { 
    $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>', 
     htmlspecialchars($e->getMessage())); 
    } 

    $_SESSION['token'] = $client->getAccessToken(); 
    } else { 


} 
} else { 
    // If the user hasn't authorized the app, initiate the OAuth flow 
    $state = mt_rand(); 
    $client->setState($state); 
    $_SESSION['state'] = $state; 

    $authUrl = $client->createAuthUrl(); 
    $htmlBody = <<<END 
    <h3>Authorization Required</h3> 
    <p>You need to <a href="$authUrl" onclick="window.open('$authUrl', 'newwindow', 'width=600, height=400'); return false;">authorize access</a> before proceeding.<p> 
END; 
} 
?> 

<!doctype html> 
<html> 
<head> 
<title>Bound Live Broadcast</title> 
</head> 
<body> 

    <?=$htmlBody?> 
</body> 
</html> 

Я использую эту проверку подлинность для планирования живого потока когда я использую этот код. я получаю еще одну ошибку Error calling POST https://www.googleapis.com/youtube/v3/liveBroadcasts?part=snippet%2Cstatus: (403) Insufficient Permission

Как я могу сделать свой запрос с достаточным разрешением?

+0

использовать 'session_start();' после запроса '' Google/autoload.php'' –

+0

Я добавил session_start(); после «Google/autoload.php». но все равно я получаю ту же ошибку – Kichu

+0

[Читать это] (http://www.daimto.com/google_service_account_php/) article –

ответ

-1

Ваш первый пример кода:

Похоже, вы пытаетесь подключиться к Google Cloud SQL API, вы дали разрешения учетной записи службы для доступа к нему?

Ваш второй образец Код:

Вы запрашиваете область для Google Analytics

$scopes ="https://www.googleapis.com/auth/analytics.readonly"; 

Но пытаться делать запросы от YouTube

Google_Service_YouTube 

Anwsers:

  1. Области должны соответствовать требуемой службе и разрешениям.
  2. API YouTube не поддерживает учетные записи служб, которые необходимо использовать Oauth2.

Комментарий

Эти примеры кода не похожи вы на самом деле должны были иметь два вопроса один для проблемы с Google Cloud SQL API другого для API YouTube.

Смежные вопросы