I've been working on deleting a file in my Google Drive but I can't make it work. I have changed my scope from $client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY); to $client->setScopes(Google_Service_Drive::DRIVE);.
Here's my full code:
<?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 Drive API PHP Quickstart');
//$client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->setScopes(Google_Service_Drive::DRIVE);
//$client->setScopes(Google_Service_Drive::DRIVE_APPDATA);
//$client->setScopes(Google_Service_Drive::DRIVE_FILE);
//$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = 'token.json';
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);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
// 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;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);
/*Get Files under hourly_backup*/
$hourly_backup_id = '1Y3cGEwXy9gLcw9WO0isqwtwtysU0g_bK';
$optParams = array(
//'pageSize' => 20,
'fields' => 'nextPageToken, files(id,name,size,parents,createdTime)',
'q' => "'".$hourly_backup_id."' in parents"
);
$results = $service->files->listFiles($optParams);
if (count($results->getFiles()) == 0) {
print "No files found.\n";
} else {
foreach ($results->getFiles() as $file) {
if(strtotime(date('Y-m-d H:i:s', strtotime($file->getcreatedTime()))) <= strtotime('-48 hours')){
try {
return $service->files->delete($file->getId());
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
} else {
print "weh \n";
}
}
}
If the condition is met and the delete code is ran, this is what I get:
An error occurred: {
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}
UPDATE:
I also tried in the API Explorer and it worked without any problem.
The google drive I'm working on is mine and I am able to delete a file directly without any problems. What could be missing in my code?
"Insufficient Permission"
Means just that the user who is currently authenticated does not have permission to do what you are trying to do.
You said that you changed the scopes. But did you reauthcate the application? The application will pop up and request permission to the drive account. If you are still running with an old access token or refresh token that still has read only access you are not going to be able to delete the file.
Yes!
Work for me only chenage to:
$client->setScopes(Google_Service_Drive::DRIVE);
And you need restar your session.
Look for file:
token.json
in your directory, delete this token.json file and try quickstart.php again.
You ask for new credencials and your access now was complete to upload files.
Related
I am trying to give user permissions to google docs file using php with google docs api but I am getting scopes error and permissions error. It is giving errors while using insert and create permissions methods.
can you please share me the code, how to give user permission to the google docs file to share with others using PHP code and which type of scopes and services I have to use.
$fileId = $file->getId();
$role = 'writer';
$userEmail = 'user#gmail.com';
$fileId = $file->getId();
$userPermission = new Google_Service_Drive_Permission(array(
'type' => 'user',
'role' => $role,
'emailAddress' => $userEmail
));
$request = $service->permissions->create(
$fileId, $userPermission, array('fields' => 'id')
);
getting is error-
An error occurred: {
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission: Request had insufficient authentication scopes."
}
],
"code": 403,
"message": "Insufficient Permission: Request had insufficient authentication scopes."
}
}
This is my 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 Drive API PHP Quickstart');
$client->setScopes([
Google_Service_Drive::DRIVE_FILE,
Google_Service_Drive::DRIVE,
Google_Service_Drive::DRIVE_METADATA_READONLY]);
$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;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);
// Print the names and IDs for up to 10 files.
$optParams = array(
'pageSize' => 10,
'fields' => 'nextPageToken, files(id, name)'
);
$results = $service->files->listFiles($optParams);
if (count($results->getFiles()) == 0) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($results->getFiles() as $file) {
printf("%s (%s)\n", $file->getName(), $file->getId());
}
}
$fileId = $file->getId();
// printf("%s",$fileId);
$newPermission = new Google_Service_Drive_Permission();
$newPermission->setEmailAddress('user#gmail.com');
$newPermission->setType('user');
$newPermission->setRole('writer');
try {
return $service->permissions->create($fileId, $newPermission);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
The permissions create method requires one of the following scopes.
If you are getting a scope error make sure to check which scopes you are authorizing the user with. Also if you have changed the scope in your code make sure to request authorization of the user again you don't want to be running on an outdated access token with your old permissions.
If we check your code
Google_Service_Drive::DRIVE_FILE,
Google_Service_Drive::DRIVE,
Google_Service_Drive::DRIVE_METADATA_READONLY]);
You appear to have all of the scopes added. my guess is though that you ordinally only had DRIVE_METADATA_READONLY you ran your app once and authorized the user. At which point your code saved the users credetinals within tokenPath. So even though you have added new scopes your app has not requested the additional permissions from the user. Delete the file in tokenPath and then your app will request authorization again.
A permissions error is something else. In order to insert the permissions the user you are logged in with must be the owner of the file only they can insert permissions.
google docs link to share
If you are trying to create the share like that can be created in Google drive web application unfortunately that is not possible with the API. Adding permissions to the file for the user will just mean that this user will have access to it in their google drive account.
As this is a Google dock you can use the webview link this will allow the user to open the file directly in their google docs account.
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
I am trying to implement this code as its written in here:
https://developers.google.com/drive/api/v3/quickstart/php
I run my php file in command line, it throws and url in command line and i open it in my browser, i log in my account and i allow quickstart etc.
And then it throws this error in my homepage:
Fatal error: Uncaught Exception: This application must be run on the command line. in C:\xampp\htdocs\upload-project\upload.php:10 Stack trace: #0 C:\xampp\htdocs\upload-project\index.php(18): include() #1 {main} thrown in C:\xampp\htdocs\upload-project\upload.php on line 10
I don't understand, I already run my php file in command line and i open the link in my browser. What is wrong with this code?
<?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 Drive API PHP Quickstart');
$client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
$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;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);
// Print the names and IDs for up to 10 files.
$optParams = array(
'pageSize' => 10,
'fields' => 'nextPageToken, files(id, name)'
);
$results = $service->files->listFiles($optParams);
if (count($results->getFiles()) == 0) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($results->getFiles() as $file) {
printf("%s (%s)\n", $file->getName(), $file->getId());
}
}
Help please... I couldn't fix it.
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.
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.