我只是从https://developers.google.com/api-client-library/php/auth/service-accounts
运行示例代码以获取访问令牌。
但是我的代码中出现以下错误
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 = 'clinetemailis@7523.com';
$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 = '456dsfd1@developer.gserviceaccount.com';
$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 :(得分:-1)
您的第一个代码示例:
看起来您正在尝试连接到Google Cloud SQL API,您是否授予服务帐户访问权限的权限?
您的第二个代码示例:
您正在申请Google Analytics的范围
$scopes ="https://www.googleapis.com/auth/analytics.readonly";
但是尝试向YouTube提出请求
Google_Service_YouTube
Anwsers:
<强>注释强>
这些代码示例不一样,你真的应该有两个问题,一个用于解决Google云sql api问题,另一个用于YouTube api。