I am trying to use this library to list my live youtube streaming but I am getting 'Login Required' error. Please find the attached class, I am using Laravel 5.5.
namespace App\Http\Controllers;
use Google_Client;
use Google_Service_YouTube;
class StreamingController extends Controller
{
const OAUTH2_CLIENT_ID = 'xxxx';
const OAUTH2_CLIENT_SECRET = 'xxxx';
const DEVELOPER_KEY = 'xxxx';
const REDIRECT_URL = 'xxxx';
const APPNAME = "xxxx";
public function index()
{
$client = new Google_Client();
$client->setClientId(self::OAUTH2_CLIENT_ID);
$client->setClientSecret(self::OAUTH2_CLIENT_SECRET);
$client->setDeveloperKey(self::DEVELOPER_KEY);
$client->setRedirectUri(self::REDIRECT_URL);
$client->setApplicationName( self::APPNAME );
$client->setAccessType('offline'); //Added for Refresh Token
$client->setApprovalPrompt('force'); //Added for Refresh Token
$client->setScopes('https://www.googleapis.com/auth/youtube.liveStreams.list');
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://' . self::REDIRECT_URL;
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
}
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
$liveStream = $youtube->liveStreams->listLiveStreams('id,snippet', array( 'mine' => 'true') );
dd( $liveStream );
}
}
I just took a peek at that API endpoint in API explorer and it looks like you need the following scopes:
$client->setScopes('https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.force-ssl https://www.googleapis.com/auth/youtube.readonly');
Also see https://developers.google.com/youtube/v3/live/docs/liveStreams/list
As an aside, I noticed you are using both OAuth and developer key auth. You don't need both and can delete the developer key lines.
I have taken off the API key and modified the setScope as advised the error doesn't go away. I am trying to automate the log in and I expect to extract all running live streaming. Is this supposed to work in this context ?
Google_Service_Exception (401)
{ "error": { "errors": [ { "domain": "global", "reason": "required", "message": "Login Required", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Login Required" } }
I have reused the code from https://developers.google.com/youtube/v3/live/docs/liveStreams/list , the $client->getAccessToken() is returning null so it cannot work. Is this library supposed to work for this use case?
$client = new Google_Client();
$client->setClientId(self::OAUTH2_CLIENT_ID);
$client->setClientSecret( self::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]);
}
$htmlBody = '';
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
try {
// Execute an API request that lists the streams owned by the user who
// authorized the request.
$streamsResponse = $youtube->liveStreams->listLiveStreams('id,snippet', array(
'mine' => 'true',
));
$htmlBody .= "<h3>Live Streams</h3><ul>";
foreach ($streamsResponse['items'] as $streamItem) {
$htmlBody .= sprintf('<li>%s (%s)</li>', $streamItem['snippet']['title'],
$streamItem['id']);
}
$htmlBody .= '</ul>';
} catch (Google_Service_Exception $e) {
$htmlBody = sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody = sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
}
var_dump( $client->getAccessToken() );
So what I am looking for is OAuth 2.0 for server-side standalone authorization and the correct approach may be the Service Account Connection => https://laracasts.com/discuss/channels/tips/google-api-service-account-connection-laravel-5
The YouTube API does not support service accounts. The best way I know how do tell which APIs use service accounts is to click on one of the enabled APIs in https://console.developers.google.com. Then click credentials and see if your service account credentials load in that per-API view.
You are right that it is easy to breeze through necessary auth/auth knowledge, especially when you are trying to get an example working. It's kinda long but https://developers.google.com/identity/protocols/OAuth2WebServer should give you everything you need to know to get authorized to start making API calls.
Please feel free to comment below if you have anymore questions.
I am trying to use this library to list my private YouTube videos through my website. The list should be available as soon as user open the page without user validation. Can or cannot this be done with this library?
You will need user validation once, the very first time. After that it won't be needed again.
The login error was there because I didn鈥檛 click through Authentication Url. @mattwhisenhunt thank you for you assistance your library does its work I have just tried to use it in a wrong context.