Skip to content

Instantly share code, notes, and snippets.

@atomjoy
Last active October 29, 2025 16:22
Show Gist options
  • Select an option

  • Save atomjoy/b48c66936503daea65733cae948c8e9f to your computer and use it in GitHub Desktop.

Select an option

Save atomjoy/b48c66936503daea65733cae948c8e9f to your computer and use it in GitHub Desktop.
Youtube API

Youtube API

https://developers.google.com/youtube/v3/docs/videos/list

Get live stream curent viewers

Set in .env YOUTUBE_API_KEY with https://www.googleapis.com/auth/youtube.readonly permissions.

/**
 * Youtube video live viewers
 *
 * $url = 'https://youtube.googleapis.com/youtube/v3/videos?part=statistics%2Cstatus%2CliveStreamingDetails&id={VIDEO_ID}&key={KEY}';
 */
public function youtubeLiveCurrentViewers()
{
  try {
    $count = Cache::store('file')
      ->remember(
        'youtubeConcurrentViewers',
        config('access.youtube.current_refresh', 60),
        function () {
          $key = env('YOUTUBE_API_KEY', '');
          $videoId = Storage::disk('local')->get(config('access.youtube.current', 'youtube-current.txt'));
          if (!empty($videoId) && !empty($key)) {
            $res = Http::get('https://youtube.googleapis.com/youtube/v3/videos?part=liveStreamingDetails&id=' . $videoId . '&key=' . $key)->json();
            $cnt = $res['items'][0]['liveStreamingDetails']['concurrentViewers'] ?? 0;
          }
          return  $cnt ?? 0;
        }
      );
  } catch (Throwable $e) {
    report($e);
    return 0;
  }

  return $count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment