recently I have set up an automatic file creation system on the google drive, I have integrated the API into my symfony application, I manage to authenticate myself, etc., but I do not block on the step of creation of the file.
I have this error that occurs:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission: Request had insufficient authentication scopes."
}
],
"code": 403,
"message": "Insufficient Permission: Request had insufficient authentication scopes."
}
}
I do not really understand where this can come from knowing that I have set the scope indicated in the documentation: $client->addScope(Google_Service_Drive::DRIVE);
my function :
public function createFolder($name)
{
$client = $this->getClient();
// $client->setAuthConfig('code_secret_client.json');
$client->addScope(Google_Service_Drive::DRIVE);
$client->setAccessToken('ya29.a0AfH6SMDO-L_7Lp6YWbGtSqWdPHJKCNezQr8-RRgS8xslHInLApC9uxBJVVljPTKEBgR-iidqIorjNaBThU4-aPjuAth1aD7mzjJXn5n2xP1xPw40p_OLssC7Ttj8CpBJHuqsUm89CYWAGL8cCHGhQ2hBY0YjKQ');
$service = new Google_Service_Drive($client);
$folder = new Google_Service_Drive_DriveFile();
$folder->setName($name);
$folder->setMimeType('application/vnd.google-apps.folder');
$result = $service->files->create($folder);
dump($result);
return $result;
}
Do you have any ideas ?
I was able to reproduce via google example
<?php
/**
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// [START drive_quickstart]
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);
$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;
}
$name = "Stackoverflow";
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);
$folder = new Google_Service_Drive_DriveFile();
$folder->setName($name);
$folder->setMimeType('application/vnd.google-apps.folder');
$result = $service->files->create($folder);
// [END drive_quickstart]
Same error. Then I checked token.json, at "scope" it had readonly. I had deleted that token and requested again Make sure it has "See, edit, create, and delete all of your Google Drive files" option to select when giving perissions, and it will work.
this line was problem on createFolder.
$client->setAccessToken('ya29.a0AfH6SMDO-L_7Lp6YWbGtSqWdPHJKCNezQr8-RRgS8xslHInLApC9uxBJVVljPTKEBgR-iidqIorjNaBThU4-aPjuAth1aD7mzjJXn5n2xP1xPw40p_OLssC7Ttj8CpBJHuqsUm89CYWAGL8cCHGhQ2hBY0YjKQ');
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 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.
I'm using
Windows 10
PHP 7.2
Apache 2.4
I followed the directions at https://developers.google.com/calendar/quickstart/php
When I open a Command Prompt an execute the command PHP quickstart.php I get the error:
First statement in the php.
Finished Outer IF isAccessTokenExpired.
PHP Fatal error: Uncaught InvalidArgumentException: missing the required redirect URI in C:\PHP\vendor\google\auth\src\OAuth2.php:637
Stack trace:
#0 C:\PHP\vendor\google\apiclient\src\Google\Client.php(328): Google\Auth\OAuth2->buildFullAuthorizationUri(Array)
#1 C:\Apache24\htdocs\quickstart.php(60): Google_Client->createAuthUrl()
#2 C:\Apache24\htdocs\quickstart.php(81): getClient()
#3 {main}
thrown in C:\PHP\vendor\google\auth\src\OAuth2.php on line 637
I'm using the code from QuickStart
<?php
/**
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// [START calendar_quickstart]
//require __DIR__ . '/vendor/autoload.php';
print "First statement in the php.\n";
require 'C:\php\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 Calendar API PHP Quickstart');
$client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$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()) {
print "Finished Outer IF isAccessTokenExpired.\n";
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
print "Finished Inner IF getRefreshToken.\n";
$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_Calendar($client);
// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
$events = $results->getItems();
if (empty($events)) {
print "No upcoming events found.\n";
} else {
print "Upcoming events:\n";
foreach ($events as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
printf("%s (%s)\n", $event->getSummary(), $start);
}
}
// [END calendar_quickstart]
It seems that it's failing on the statement if ($client->getRefreshToken())
I can't understand why I would get an error on Quickstart code. Any ideas why this is happening?
There was a problem with the Quickstart.php. I looged the bug with Google, and they gave me an immediate fix. Delete the old $client->setRedirectUri('http://' . $_SERVER['localhost'] . '/oauth2callback.php'); Then, right after the statement: $client = new Google_Client(); add the new line: $client->setRedirectUri("urn:ietf:wg:oauth:2.0:oob"); I also made new credentials by going to the console and then selected: Create an OAuth Client ID. I used an Application Type: Other then downloaded the Client Secret file and renamed it credentials.json. All is working well now.
This is most likely because you the redirect URL was not provided or correctly configured from the credentials page on Google's API console. OAuth needs to redirect back to your server where it will post the access token and refresh token used by their scripts.
If the OAuth flow can't properly redirect and send the credentials back to your server the script will not execute properly.
I'm trying to work through the PHP example provided for the Gmail REST API.
I'm not clear what information I'm supposed to change to my personal information to make the example work. I'm self taught and new to PHP so any info would be appreciated. I've put some comments (MF:) inline with changes I've made but still not working:
<?php
//require 'vendor/autoload.php'; //MF: changed to:
require_once('GoogleAPI/src/Google/autoload.php');
//MF: The downloaded API from GitHub doesn't have a "vendor" folder.
//MF: should this be the project name as it appears up in my Google Developers Console? Does it matter?
define('APPLICATION_NAME', 'Gmail API Quickstart');
//MF: I assume I download and put the path to my JSON Download file from the Google Developer console.
define('CREDENTIALS_PATH', '~/.credentials/gmail-api-quickstart.json');
//MF: I'm confused how this differs from the line above. The JSON Download has the client secret in it as well. Is this different?
define('CLIENT_SECRET_PATH', 'client_secret.json');
define('SCOPES', implode(' ', array(
Google_Service_Gmail::GMAIL_READONLY)
));
//MF: I think I leave the rest alone.
/**
* 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->setAuthConfigFile(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = file_get_contents($credentialsPath);
} 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->authenticate($authCode);
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, $accessToken);
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->refreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, $client->getAccessToken());
}
return $client;
}
/**
* Expands the home directory alias '~' to the full path.
* #param string $path the path to expand.
* #return string the expanded path.
*/
function expandHomeDirectory($path) {
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv("HOMEDRIVE") . getenv("HOMEPATH");
}
return str_replace('~', realpath($homeDirectory), $path);
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Gmail($client);
// Print the labels in the user's account.
$user = 'me';
$results = $service->users_labels->listUsersLabels($user);
if (count($results->getLabels()) == 0) {
print "No labels found.\n";
} else {
print "Labels:\n";
foreach ($results->getLabels() as $label) {
printf("- %s\n", $label->getName());
}
}