我正在创建 YouTube 广播并成功运行。
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
// $client->refreshToken($accessToken);
// // $client->refreshToken($accessToken);
// $newToken = $client->getAccessToken();
// echo "new token : ". $newToken;
$client->setAccessToken($accessToken);
try {
// Define service object for making API requests.
$service = new Google_Service_YouTube($client);
// Define the $liveBroadcast object, which will be uploaded as the request body.
$liveBroadcast = new Google_Service_YouTube_LiveBroadcast();
// Add 'contentDetails' object to the $liveBroadcast object.
$liveBroadcastContentDetails = new Google_Service_YouTube_LiveBroadcastContentDetails();
$liveBroadcastContentDetails->setEnableClosedCaptions(true);
$liveBroadcastContentDetails->setEnableContentEncryption(true);
$liveBroadcastContentDetails->setEnableDvr(true);
$liveBroadcastContentDetails->setRecordFromStart(true);
$liveBroadcastContentDetails->setStartWithSlate(true);
$liveBroadcast->setContentDetails($liveBroadcastContentDetails);
// Add 'snippet' object to the $liveBroadcast object.
$liveBroadcastSnippet = new Google_Service_YouTube_LiveBroadcastSnippet();
$liveBroadcastSnippet->setScheduledStartTime($start_date_time);
$liveBroadcastSnippet->setTitle($class_name);
$liveBroadcast->setSnippet($liveBroadcastSnippet);
// Add 'status' object to the $liveBroadcast object.
$liveBroadcastStatus = new Google_Service_YouTube_LiveBroadcastStatus();
$liveBroadcastStatus->setPrivacyStatus('unlisted');
$liveBroadcast->setStatus($liveBroadcastStatus);
$response = $service->liveBroadcasts->insert('snippet,contentDetails,status', $liveBroadcast);
return ($response->id);
} catch (Google_Service_Exception $e) {
print_r($e);
} catch (Google_Exception $e) {
print_r($e);
}
但一段时间后授权失败。 令牌已过期,无法创建广播。 我尝试刷新令牌但不起作用,请帮忙。
https://developers.google.com/youtube/v3/live/docs/liveBroadcasts/insert?apix=true[][1]
答案 0 :(得分:0)
首先确保请求离线访问,这将向您返回刷新令牌
function buildClient(){
$client = new Google_Client();
$client->setAccessType("offline"); // offline access. Will result in a refresh token
$client->setIncludeGrantedScopes(true); // incremental auth
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->addScope([YOUR SCOPES HERE]);
return $client;
}
用户第一次授权你应该返回一个刷新令牌。把它存放在某个地方。
$client->getRefreshToken()
确保在 $client->setRefreshtoken($stored) 中加载刷新令牌,以便它在下一部分中使用。
然后检查访问令牌是否已过期并将刷新令牌添加回并强制获取新的访问令牌。
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
}