Last active
August 26, 2016 16:06
-
-
Save andrewshulgin/c08b104ae579b4fdf4b3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// ID OAuth клиента | |
$OAUTH2_CLIENT_ID = ''; | |
// Ключ OAuth клиента | |
$OAUTH2_CLIENT_SECRET = ''; | |
// URL для приема токена | |
$TOKEN_SAVE_URL = 'http://' . $_SERVER['HTTP_HOST'] . '/'; | |
// URL для переадресации после авторизации | |
$REDIRECT_URL = 'http://' . $_SERVER['HTTP_HOST'] . '/'; | |
set_include_path('google-api-php-client/src'); | |
require_once 'Google/Client.php'; | |
require_once 'Google/Service/YouTube.php'; | |
session_start(); | |
// Гугл-клиент | |
$client = new Google_Client(); | |
// Устанавливаем наши API ключи | |
$client->setClientId($OAUTH2_CLIENT_ID); | |
$client->setClientSecret($OAUTH2_CLIENT_SECRET); | |
$client->setScopes('https://www.googleapis.com/auth/youtube'); | |
// URL для приема токена | |
$client->setRedirectUri($TOKEN_SAVE_URL); | |
// Клиент Youtube API | |
$youtube = new Google_Service_YouTube($client); | |
// Принимаем код авторизации и редиректим куда надо | |
if (isset($_GET['code'])) { | |
if (strval($_SESSION['state']) !== strval($_GET['state'])) { | |
die('Несовпадение состояния сессии'); | |
} | |
$client->authenticate($_GET['code']); | |
// Сохраняем токен в сессию | |
$_SESSION['token'] = $client->getAccessToken(); | |
// Редиректим юзера | |
header('Location: ' . $REDIRECT_URL); | |
} | |
// Устанавливаем токен, если есть в сессии | |
if (isset($_SESSION['token'])) { | |
$client->setAccessToken($_SESSION['token']); | |
} | |
// Устанавливаем ID видео из GET параметра и сохраняем в сессию | |
if (isset($_GET['video'])) { | |
$video = ($_GET['video']); | |
$_SESSION['video'] = $video; | |
// Устанавливаем ID видео из сессии | |
} elseif (isset($_SESSION['video'])) { | |
$video = $_SESSION['video']; | |
} | |
if (isset($video)) { | |
$watched = false; | |
// Если есть токен | |
if ($client->getAccessToken()) { | |
try { | |
// Получаем каналы пользователя | |
$channelsResponse = $youtube->channels->listChannels('contentDetails', array( | |
'mine' => 'true', | |
)); | |
foreach ($channelsResponse['items'] as $channel) { | |
// Получаем ID списка просмотренных видео | |
$watchedListId = $channel['contentDetails']['relatedPlaylists']['watchHistory']; | |
// Получаем 1, если видео просмотренно | |
$playlistItemsResponse = $youtube->playlistItems->listPlaylistItems('snippet', array( | |
'playlistId' => $watchedListId, | |
'videoId' => $video, | |
)); | |
$watched = $playlistItemsResponse['pageInfo']['totalResults'] > 0; | |
} | |
} catch (Google_Service_Exception $e) { | |
// Видео не просмотренно | |
if ($e->getCode() == 404) {} | |
} catch (Google_Exception $e) { | |
// Другая ошибка | |
printf('<p>%s</p>', htmlspecialchars($e->getMessage())); | |
} | |
printf('<p>%s</p>', $watched ? "watched" : "not watched"); | |
// Сохраняем новый токен | |
$_SESSION['token'] = $client->getAccessToken(); | |
// Токена нету | |
} else { | |
$state = mt_rand(); | |
$client->setState($state); | |
$_SESSION['state'] = $state; | |
// Ссылка для авторизации | |
$authUrl = $client->createAuthUrl(); | |
printf('<a href="%s">auth</a>', $authUrl); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment