I am trying to build a simple process. Access Youtube Data API and get information about a Youtube channel.
I've done this before using php GET:
file_get_contents('https://www.googleapis.com/youtube/v3/search?key=MYKEY&channelId= CHANNELID&maxResults=10&order=date&type=video&part=snippet');
But now I would like to create a cron job using the Google Client to access the data like so:
<?php
require_once'/home/PROJECT/vendor/autoload.php';
$client = new Google_Client();
$client->setApplicationName('API code samples');
$client->setScopes([
'https://www.googleapis.com/auth/youtube.force-ssl',
]);
// TODO: For this request to work, you must replace
// "YOUR_CLIENT_SECRET_FILE.json" with a pointer to your
// client_secret.json file. For more information, see
// https://cloud.google.com/iam/docs/creating-managing-service-account-keys
$client->setAuthConfig('client_secret.json');
$client->setAccessType('offline');
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open this link in your browser:\n%s\n", $authUrl);
print('Enter verification code: ');
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Define service object for making API requests.
$service = new Google_Service_YouTube($client);
$queryParams = [
'channelId' => 'CHANNELID',
'type' => 'video'
];
$response = $service->search->listSearch('snippet', $queryParams);
print_r($response);
?>
I am confused. Using php GET, I only needed an API Key. But with Google Client I need an authorization. Why? Can I use an API Key using the Google Client? I created secret key and want to run it in a cron job. But I get errors like so:
Open this link in your browser: https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=offline&client_id=CLIENTID.apps.googleusercontent.com&redirect_uri=https%3A%2F%2FTEST.co&state&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.force-ssl&approval_prompt=auto Enter verification code:
Warning: Use of undefined constant STDIN - assumed 'STDIN' (this will throw an Error in a future version of PHP) in /var/www/html/index.php on line 21
Warning: fgets() expects parameter 1 to be resource, string given in /var/www/html/index.php on line 21
Fatal error: Uncaught InvalidArgumentException: Invalid code in /home/matthew/vendor/google/apiclient/src/Client.php:248 Stack trace: #0 /var/www/html/index.php(24): Google\Client->fetchAccessTokenWithAuthCode() #1 {main} thrown in /home/matthew/vendor/google/apiclient/src/Client.php on line 248
What am I doing wrong?