Skip to content

Instantly share code, notes, and snippets.

@malikkurosaki
Created March 11, 2018 03:13
Show Gist options
  • Save malikkurosaki/fc5f56e7a5bfc18ddb901ae6977e46b4 to your computer and use it in GitHub Desktop.
Save malikkurosaki/fc5f56e7a5bfc18ddb901ae6977e46b4 to your computer and use it in GitHub Desktop.
youtube auth use api v3 to login into google account
<?php
if (!file_exists($file = __DIR__ . '/vendor/autoload.php')) {
throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
session_start();
$OAUTH2_CLIENT_ID = '751887412551-o95lukoq6blmmlkom33mteojlpnrtbim.apps.googleusercontent.com';
$OAUTH2_CLIENT_SECRET = '9vGd0fvJ3m0_4ePtN4Ms8jNM';
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION[$tokenSessionKey])) {
$client->setAccessToken($_SESSION[$tokenSessionKey]);
}
if ($client->getAccessToken()) {
$_SESSION['halo'] = "hi";
} else {
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
echo "<a href='".$authUrl."'>login please</a>";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment