I am using this code in PHP to get the Youtube server URL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.youtube.com/youtubei/v1/player?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{
"videoId": "'.$yt_video_id.'",
"context": {
"client": {
"clientName": "ANDROID",
"clientVersion": "16.20.35"
},
"device": {
"platform": "ANDROID",
"platformVersion": "11"
}
},
"playbackMode": "EMBEDDED",
"playerParams": {
"autoplay": 1
}
}');
curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
echo '<pre>';print_r($result);
It is working fine and returns the video info along with the formats and adaptive formats. The returned server URL also has the expire field in the URL itself which means the returned media URL will expire after that time.
I added the logic to save expire in the database and reran the above code to fetch the new media URL when the current time is greater than the previous expire time.
The problem is that sometime the above curl request returns the following error, but when I refresh, it works:
"reason": {
"runs": [{
"text": "The following content is not available on this app."
}]
}
I am afraid that this can happen with my live videos and the user will not be able to watch video.
What am I doing wrong, and what is the best way to handle the expiration? What catch I am missing here? I have seen that many other video players are working fine without errors.
UPDATE - If I try it with "WEB" as client then it works every time. I am following @Mahad answer for web from this link get_video_info YouTube endpoint suddenly returning 404 not found.