How to set up Gogle's People API - php

I've been trying to set up the sample PHP Quickstart.
When I try running it as is I get the following error :
PHP Fatal error: Uncaught InvalidArgumentException: missing the required redirect URI in /opt/lampp/htdocs/rev_wip/vendor/google/auth/src/OAuth2.php:685
Stack trace:
#0 /opt/lampp/htdocs/rev_wip/vendor/google/apiclient/src/Client.php(406): Google\Auth\OAuth2->buildFullAuthorizationUri(Array)
#1 /opt/lampp/htdocs/rev_wip/quickstart.php(40): Google\Client->createAuthUrl()
#2 /opt/lampp/htdocs/rev_wip/quickstart.php(64): getClient()
#3 {main}
thrown in /opt/lampp/htdocs/rev_wip/vendor/google/auth/src/OAuth2.php on line 685
So I add a URI :
// $redirect_uri = 'http://localhost/rev_wip/' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$redirect_uri = 'http://localhost/rev_wip/' . $_SERVER['PHP_SELF'];
$client->setRedirectUri($redirect_uri);
Now I get (when I run it on the browser) :
Authorization Error
Error 400: redirect_uri_mismatch
You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy.
If you're the app developer, register the redirect URI in the Google Cloud Console.
Learn more
The content in this section has been provided by the app developer. This content has not been reviewed or verified by Google.
If you’re the app developer, make sure that these request details comply with Google policies.
redirect_uri: http://localhost/rev_wip/quickstart.php
I am thinking that this example is a Desktop APP and so there should be no Redirect URI. I, however get the common redirect URI error when I run it on the CLI.
How should I go about it?
Thank you all in advance.
Here is the code that I am working with:
<?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('People API PHP Quickstart');
$client->setScopes(Google_Service_PeopleService::CONTACTS_READONLY);
$client->setAuthConfig(__DIR__ . '/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 = __DIR__ . '/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_PeopleService($client);
// Print the names for up to 10 connections.
$optParams = array(
'pageSize' => 10,
'personFields' => 'names,emailAddresses',
);
$results = $service
->people_connections
->listPeopleConnections('people/me', $optParams);
if (count($results->getConnections()) == 0) {
print "No connections found.\n";
}
else {
print "People:\n";
foreach ($results->getConnections() as $person) {
if (count($person->getNames()) == 0) {
print "No names found for this connection\n";
}
else {
$names = $person->getNames();
$name = $names[0];
printf("%s\n", $name->getDisplayName());
}
}
}
?>

In the tutorial you're linking to there's a section called "Troubleshooting" under which there's a section about the exact error you're facing:
https://developers.google.com/people/quickstart/php#uncaught_invalidargumentexception_missing_the_required_redirect_uri
Uncaught InvalidArgumentException: missing the required redirect URI
This error occurs when the credentials.json file used contains a client ID of the wrong type.
This code requires an OAuth client ID of type Other, which will be
created for you when using the button in Step 1. If creating your own
client ID please ensure you select the correct type.
This suggests you didn't complete step 1 properly or that you have supplied your own client ID of the wrong type.

Related

PHP run local webserver, to fix Google authorization issue caused by the removal of OOB

Google removed urn:ietf:wg:oauth:2.0:oob flow for installed / desktop / native applications. Making Google OAuth interactions safer by using more secure OAuth flows
This flow allowed for the redirect uri to return the authorization code back to an application that did not have a web server running.
The python samples for google-api-python-client compensate for this by spawning a local server.
flow = InstalledAppFlow.from_client_secrets_file(
'C:\YouTube\dev\credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
This works as would be expected the authorization code is returned properly to the application.
My issue is with PHP, and the Google-api-php-client library
The current samples I have found created by google look as follows
// 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));
The user is prompted to copy the authorization code from the web browser themselves and paste it into the console window. In the past this was fine because urn:ietf:wg:oauth:2.0:oob would put the code in the web browser page. Now that is not happening. with the removal of oob we must use '"http://127.0.0.1"' when the authorization completes. a 404 error is displayed to the user in the browser window
However the url bar of the browser window displays the code
https://127.0.0.1/?state=xxxxxxx&code=xxxxxxxxxxxxxx&scope=googleapis.com/auth/youtube.readonly googleapis.com/auth/youtube.force-ssl googleapis.com/auth/yt-analytics.readonly
A user must then copy the code from the URL browser window. This is confusing for non-tenchincal users who see the 404 error and assume that something has gone wrong.
The issue is that the sample code does not spawn a web server as Python does in order to display the redirect uri properly.
My question: Is there a way to spawn a local server like python does with php? or is there an alternative to get this working again properly with php?
Full sample code
For anyone willing to test. Here is a full example.
create installed credentials on google cloud console
enable the google drive api.
Lots of code:
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
use Google\Client;
use Google\Service\Drive;
/**
* Returns an authorized API client.
* #return Client the authorized client object
*/
function getClient()
{
$client = new Client();
$client->setApplicationName('Google Drive API PHP Quickstart');
$client->setScopes('https://www.googleapis.com/auth/drive.readonly');
$client->setAuthConfig('C:\Development\FreeLance\GoogleSamples\Credentials\credentials.json');
$client->setAccessType('offline');
$client->setRedirectUri("http://127.0.0.1");
$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->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$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.
try {
$client = getClient();
}
catch(Exception $e) {
unlink("token.json");
$client = getClient();
}
$service = new Drive($client);
// Print the next 10 events on the user's calendar.
try{
$optParams = array(
'pageSize' => 10,
'fields' => 'files(id,name,mimeType)',
'q' => 'mimeType = "application/vnd.google-apps.folder" and "root" in parents',
'orderBy' => 'name'
);
$results = $service->files->listFiles($optParams);
$files = $results->getFiles();
if (empty($files)) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($files as $file) {
$id = $file->id;
printf("%s - (%s) - (%s)\n", $file->getId(), $file->getName(), $file->getMimeType());
}
}
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}

Google API Quickstart

I've run into the problem with Google API quickstart. I couldn't verify the token because it says that the token format is invalid. The strangest part was that I was able to make it run a few months ago on another project, but now I can't do anything.
My quickstart.php look as:
<?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 Sheets API');
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
$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_Sheets($client);
// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
$spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
$range = 'Class Data!A2:E';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
if (empty($values)) {
print "No data found.\n";
} else {
print "Name, Major:\n";
foreach ($values as $row) {
// Print columns A and E, which correspond to indices 0 and 4.
printf("%s, %s\n", $row[0], $row[4]);
}
}
When I attempt to enter the token it returns following error
Fatal error: Uncaught InvalidArgumentException: Invalid token format in ..\vendor\google\apiclient\src\Google\Client.php:469
Stack trace:
#0 ..\quickstart.php(45): Google_Client->setAccessToken()
#1 ..\quickstart.php(63): getClient()
#2 {main}
thrown in ..\vendor\google\apiclient\src\Google\Client.php on line 469
I've tried to append for $authCode token manually, but it didn't work.
So it literally was my mistake, our front engine changed the link "a bit" so it wasn't be able to be verified. As I've changed to a random domain and copied the token everything worked well.

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

Php Google Drive Api v3 - connection problem (quickstart)

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.

How do I resolve a Redirect URI error with Google Calendar API quickstart.php

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.

Categories