YouTube Data API: listLiveBroadcasts doesn't work... why? - php

I try to use the YouTube API, but when I wish to use the LiveBroadcasts.list API.
When I use the same JSON key to list my playlist it's OK... I don't understand why.
$client = new \Google_Client();
$client->setAuthConfig(__DIR__ . '/../../key/youtube_client.json');
$client->setApplicationName('Broadcast');
$client->setScopes([
'https://www.googleapis.com/auth/youtube',
'https://www.googleapis.com/auth/youtube.force-ssl',
'https://www.googleapis.com/auth/youtube.upload',
'https://www.googleapis.com/auth/youtube.readonly'
]);
$service = new \Google_Service_YouTube($client);
$broadcastsResponse = $service->liveBroadcasts->listLiveBroadcasts(
'id,snippet,contentDetails',
array(
'broadcastType' => 'persistent',
'mine' => 'true',
)
);
The error message is:
{ "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "errors": [ { "message": "Login Required.", "domain": "global", "reason": "required", "location": "Authorization", "locationType": "header" } ], "status": "UNAUTHENTICATED" } }
Can someone help me to know where is my mistake?

You appear to be missing a lot of the authorization code that is required in order to fetch an access token.
<?php
/**
* Sample PHP code for youtube.liveBroadcasts.list
* See instructions for running these code samples locally:
* https://developers.google.com/explorer-help/guides/code_samples#php
*/
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new Exception(sprintf('Please run "composer require google/apiclient:~2.0" in "%s"', __DIR__));
}
require_once __DIR__ . '/vendor/autoload.php';
$client = new Google_Client();
$client->setApplicationName('API code samples');
$client->setScopes([
'https://www.googleapis.com/auth/youtube.readonly',
]);
// 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('YOUR_CLIENT_SECRET_FILE.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);
$response = $service->liveBroadcasts->listLiveBroadcasts('');
print_r($response);
This sample is going to end up running more as a console application as it just builds the url for you. If you need it run as a web application let me know i have some other sampes just not for this API which you can find here. If you need help altering it let me know.

Related

How to retrieve assignment, quiz marks from Google Classroom using api in php

I want to read assignments or quiz marks from Google Classroom using API for a project. But I can't find out how to read marks from Google Classroom.
Please give me some suggestions and source code for reading assignments or quiz marks from Google Classroom using PHP or Laravel.
Already I've added some code to the quickstart.php file:
<?php
require __DIR__ . '/vendor/autoload.php';
// if (php_sapi_name() != 'cli') {
// throw new Exception('This application must be run on the command line.');
// }
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Classroom API & PHP');
$client->setScopes(array(
Google_Service_Classroom::CLASSROOM_COURSES,
Google_Service_Classroom::CLASSROOM_STUDENT_SUBMISSIONS_STUDENTS_READONLY,
Google_Service_Classroom::CLASSROOM_ROSTERS)
);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following 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);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Copyright 2021 Google LLC.
// SPDX-License-Identifier: Apache-2.0
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Classroom($client);
// set these parameters:
// 328776504166 <- It is my course id
// 339429593407 <- It is my course work id
$courseId = "328776504166";
$courseWorkId = "339429593407";
$results = $service->courses_courseWork_studentSubmissions->listCoursesCourseWorkStudentSubmissions($courseId, $courseWorkId);
foreach ($results->studentSubmissions as $r => $submission) {
$student = $service->courses_students->get($courseId, $submission->userId);
$studentName = $student->profile->name->fullName;
print($studentName . ": ");
print($submission->assignedGrade. "\n");
}
Then when I run quickstart.php at localhost the following problems can be seen:
Fatal error: Uncaught Google_Service_Exception: {
"error": {
"code": 403,
"message": "Request had insufficient authentication scopes.",
"errors": [
{
"message": "Insufficient Permission",
"domain": "global",
"reason": "insufficientPermissions"
}
],
"status": "PERMISSION_DENIED"
}
}
I can't find my wrong. How to solve this problem? please give me some suggestions
Answer:
You can use the courses.courseWork.studentSubmissions.list method to retrieve a list of student submissions for a piece of coursework. In the response, there will be the assignedGrade field.
Example:
// Copyright 2021 Google LLC.
// SPDX-License-Identifier: Apache-2.0
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Classroom($client);
// set these parameters:
$courseId = "180119025944";
$courseWorkId = "177950380066";
$results = $service->courses_courseWork_studentSubmissions->listCoursesCourseWorkStudentSubmissions($courseId, $courseWorkId);
foreach ($results->studentSubmissions as $r => $submission) {
$student = $service->courses_students->get($courseId, $submission->userId);
$studentName = $student->profile->name->fullName;
print($studentName . ": ");
print($submission->assignedGrade. "\n");
}
Also, make sure that you have the correct scopes set up:
$client->setScopes(array(
Google_Service_Classroom::CLASSROOM_COURSES,
Google_Service_Classroom::CLASSROOM_STUDENT_SUBMISSIONS_STUDENTS_READONLY,
Google_Service_Classroom::CLASSROOM_ROSTERS)
);
References:
PHP Quickstart | Classroom API | Google Developers
Google Classroom API - PHP Reference
Method: courses.courseWork.studentSubmissions.list | Classroom API | Google Developers

Wordpress PHP Google Sheets API Access

I'm having issues accessing Google Sheets through PHP in WordPress (WP). I've accessed the same sheet before in a local python program and I recall that once the code first ran the google authorization window popped up asking for approval. This WP shortcode isn't getting to that point and instead outputs an error message to the WP page stating a valid API Key is missing. What am I missing here?
Shortcode:
require_once __DIR__ . '/vendor/autoload.php';
function excel_tester_function() {
$client = new Google_Client();
$client->setApplicationName('Google Sheets and PHP');
$client->setAuthConfig(__DIR__ . '/credentials.json');
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
$client->setAccessType('online');
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client->setRedirectUri($redirect_uri);
$service = new Google_Service_Sheets($client);
$spreadsheetId = '{SHEET_ID}';
$get_range = '{RANGE}';
$response = $service->spreadsheets_values->get($spreadsheetId, $get_range);
$values = $response->getValues();
foreach ($val as $values) {
print($val);
}
}
add_shortcode('excel-tester', 'excel_tester_function');
Error:
Fatal error: Uncaught Google_Service_Exception: { "error": { "code": 403, "message": "The request is missing a valid API key.", "errors": [ { "message": "The request is missing a valid API key.", "domain": "global", "reason": "forbidden" } ], "status": "PERMISSION_DENIED" } } in...
Please advise. Let me know if there is any info I can provide that could help solve this. Thank you.

Google App Script Api 404 error while running script via api

i am currently trying to run an app script function when user connect there google account. when one row is finished typing i want the row information back to my server.so i came to a conclusion that app script is suitable for that.
what i have do step by step is
1) create a google console project
2) enable app script
3) enable google sheet api
4) download credentials.json
5) create a script
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Apps Script API PHP Quickstart');
$client->setScopes(['https://www.googleapis.com/auth/script.projects','https://www.googleapis.com/auth/script.scriptapp','https://www.googleapis.com/auth/spreadsheets','https://www.googleapis.com/auth/spreadsheets.readonly','https://www.googleapis.com/auth/script.external_request','https://www.googleapis.com/auth/script.deployments']);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following 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);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
/**
* Shows basic usage of the Apps Script API.
*
* Call the Apps Script API to create a new script project, upload files to the
* project, and log the script's URL to the user.
*/
$client = getClient();
$service = new Google_Service_Script($client);
// Create a management request object.
$request = new Google_Service_Script_CreateProjectRequest();
$request->setTitle('console script 44400');
$response = $service->projects->create($request);
$scriptId = $response->getScriptId();
$code = <<<EOT
function customFunction(e) {
var range = e.range;
range.setNote('Last modified: ' + new Date());
var ui = SpreadsheetApp.getUi();
ui.alert('text');
}
ScriptApp.newTrigger('customFunction')
.forSpreadsheet('xxxxxxxxxxxx')
.onEdit()
.create();
EOT;
$file1 = new Google_Service_Script_ScriptFile();
$file1->setName('hello 111100');
$file1->setType('SERVER_JS');
$file1->setSource($code);
$manifest = <<<EOT
{
"timeZone": "America/New_York",
"exceptionLogging": "CLOUD",
"oauthScopes": [
"https://www.googleapis.com/auth/spreadsheets.readonly",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/script.scriptapp",
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.scripts"
]
}
EOT;
$file2 = new Google_Service_Script_ScriptFile();
$file2->setName('appsscript');
$file2->setType('JSON');
$file2->setSource($manifest);
$request = new Google_Service_Script_Content();
$request->setScriptId($scriptId);
$request->setFiles([$file1, $file2]);
$response = $service->projects->updateContent($scriptId, $request);
echo "https://script.google.com/d/" . $response->getScriptId() . "/edit\n";
$request = new \Google_Service_Script_ExecutionRequest();
$request->setFunction('customFunction');
$response = $service->scripts->run($scriptId, $request);
I got the response as
Fatal error: Uncaught Google_Service_Exception: {
"error": {
"code": 404,
"message": "Requested entity was not found.",
"errors": [
{
"message": "Requested entity was not found.",
"domain": "global",
"reason": "notFound"
}
],
"status": "NOT_FOUND"
}
}
the error is due to
$request = new \Google_Service_Script_ExecutionRequest();
$request->setFunction('customFunction');
$response = $service->scripts->run($scriptId, $request);
i see similar errors on internet .but the solutions don't work for me. i pass all the necessary scopes
'https://www.googleapis.com/auth/script.projects','https://www.googleapis.com/auth/script.scriptapp','https://www.googleapis.com/auth/spreadsheets','https://www.googleapis.com/auth/spreadsheets.readonly','https://www.googleapis.com/auth/script.external_request','https://www.googleapis.com/auth/script.deployments'
between as a side note when i try to run the script manually in the script editor and try editing in the google sheet the above script work and the alert box shown. but this is not practical in case of user who connected there google account.we cannot guarantee that user run script manually to make things work.we need the api to run the script and make the trigger working.Please help
Edited
version code added
$request1=new Google_Service_Script_Version();
$request1->setScriptId($scriptId);
$request1->setVersionNumber(1);
$service->projects_versions->create($scriptId,$request1);
added above script run API code but still get same error
I've got the same problem and the solution is quite easy.
You need to deploy your project as "API Exeutable". That is all.
But for such deploying you have to set Google Cloud Platform (GCP) Project Number in Project Settings.

Delete file with google drive API PHP V3 permission error

I have an issue with google drive PHP API V3 I'm trying to remove a file from the drive using the code below:
This is the code I'm using:
<?php
require_once __DIR__ . '/vendor/autoload.php';
define('APPLICATION_NAME', 'Google Drive API PHP');
define('CREDENTIALS_PATH', '/root/.credentials/drive-php.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
define('SCOPES', implode(' ', array(
Google_Service_Drive::DRIVE_METADATA_READONLY
)
));
if (php_sapi_name() != 'cgi-fcgi') {
throw new Exception('This application must be run on the command line.');
}
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
$accessToken = json_decode(file_get_contents(CREDENTIALS_PATH), true);
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents(CREDENTIALS_PATH, json_encode($client->getAccessToken()));
}
return $client;
}
$client = getClient();
$service = new Google_Service_Drive($client);
$optParams = array(
'fields' => 'files(id, createdTime)'
);
$results = $service->files->listFiles($optParams);
if (count($results->getFiles()) != 0) {
foreach ($results->getFiles() as $file) {
$service->files->delete($file['id']);
}
}
All is working I can get the ID of the file but when I try to delete it I get the below error.
Any idea why please?
Thanks
PHP Fatal error: Uncaught Google_Service_Exception: {
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}
Google_Service_Drive::DRIVE_METADATA_READONLY cannot be used for deleting files using Drive API. So how about using Google_Service_Drive::DRIVE as the scope?
When you modified the scope, please remove the file of drive-php.json at /root/.credentials/, and run the script again. By this, the access token and refresh token reflected the modified scope can be retrieved.
And then, please confirm whether Drive API is enabled again.
If this was not useful for you, I'm sorry.

How to create gmail business user account using google API with PHP

I want to create a new gmail business user account in gmail using PHP. When I run this code it will shows some message like Open the following link in your browser: with URL and asking for verification code. If I run the link in browser it will generate some random string. I got 403 error when I paste the random string in terminal for verification. Here is my code.
<?php
require_once __DIR__ . '/vendor/autoload.php';
define('APPLICATION_NAME', 'Directory API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/admin-directory_v1-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/admin-directory_v1-php-quickstart.json
define('SCOPES', implode(' ', array(
Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY)
));
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following 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);
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
My error
Fatal error: Uncaught Google_Service_Exception: { "error": { "errors": [ { "domain": "global", "reason": "forbidden", "message": "Not Authorized to access this resource/api" } ], "code": 403, "message": "Not Authorized to access this resource/api" } }
Fatal error: Uncaught Google_Service_Exception:
{
"error":{
"errors":[
{
"domain":"global",
"reason":"forbidden",
"message":"Not Authorized to access this resource/api"
}
],
"code":403,
"message":"Not Authorized to access this resource/api"
}
}
Means that the user you are authenticating with does not have access to an admin directory account
The Directory API lets you perform administrative operations on users, groups, organizational units, and devices in your account.
Solution: Login with a user who has access to the G suite account.

Categories