Uncaught Error: Undefined constant Google\Service\Sheets::spreadsheets in - php

I am trying to access a google sheet using Google's sheets API using PHP
I am stuck with this error !
Fatal error: Uncaught Error: Undefined constant Google\Service\Sheets::spreadsheets in {my file path} :8 Stack trace: #0 {main} thrown in {my file path} on line 8
My code
<?php
require __DIR__ . '/vendor/autoload.php';
$client = new \Google_Client();
$client->setApplicationName('Google Sheets API PHP');
$client->setScopes([\Google_Service_Sheets::spreadsheets]);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$service = new Google_Service_Sheets($client);
$spreadsheetId = "1FA--HxEEu3zp_u2Bzqhz5nEN2FHSpE5XhQNslEc8LBg";
$range = "Data Analytics - Spreadsheet example!B2:D17";
$response = $service->spreadsheets_values-
>get($spreadsheetId,$range);
$values = $response->getvalues();
if (empty($values))
{
echo "No data found";
}
else
{
$mask = "%10s %-10s %s \n";
foreach($values as $row)
{
echo sprintf($mask, $row[0], $row[1], $row[2]);
}
}
?>

Try to change
$client->setScopes([\Google_Service_Sheets::spreadsheets]);
To. I find this way works better.
$client->setScopes(['https://www.googleapis.com/auth/spreadsheets']);
The way you are doing it should work but you need to have the correct case
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);

Update this code:
$client->setScopes(\Google_Service_Sheets::SPREADSHEETS);
$service = new Google_Service_Sheets($client);
to this:
$client->setScopes(Google\Service\Sheets::SPREADSHEETS);
$service = new Google\Service\Sheets($client);

Related

Bad Request while accesing Gmail API

I'm trying to connect to Gmail but server says:
Uncaught exception 'Google_Service_Exception' with message 'Error calling
GET https://www.googleapis.com/gmail/v1/users/{test}%40gmail.com/messages:
(400) Bad Request' in C:\...\google-api-php-client\src\Google\Http\REST.php on line 110
I can't seem to find the problem. Here's the code:
$google_accounts = $this->getGoogleAccounts();
if (count($google_accounts) > 0) {
require_once $_SERVER['DOCUMENT_ROOT'] . '/include/google-api-php-client/src/Google/autoload.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/include/google-api-php-client/src/Google/Client.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/include/google-api-php-client/src/Google/Service/Gmail.php';
$scopes = array(
'https://mail.google.com',
'https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/gmail.modify',
);
$key_file_location = $_SERVER['DOCUMENT_ROOT'] . '/include/google-api-php-client/src/keys/';
foreach ($google_accounts as $one_account) {
if (!empty($one_account->client_id) && !empty($one_account->service_mail) && !empty($one_account->key_file)) {var_dump($one_account);
$key = file_get_contents($key_file_location . $one_account->key_file);
$client = new Google_Client();
$cred = new Google_Auth_AssertionCredentials($one_account->service_mail, $scopes, $key);
$client->setAssertionCredentials($cred);
$client->setClientId($one_account->client_id);
$client->setAccessType('offline_access');
$service = new Google_Service_Gmail($client);
$opt_param = array();
$messagesResponse = $service->users_messages->listUsersMessages($one_account->login, $opt_param);
var_dump($messagesResponse);
}
}
return $list;
}
else {
return false;
}
You need to add:
$cred->sub = $userEmail;
right after creating $cred where $userEmail is the email address of the user you are trying to impersonate. For reference, see the Google Drive Service Account documentation which uses a different scope and API call but is otherwise similar to what you'd want to do with Gmail API.

I couldn't connect to Google calender api using v3 php client library

I couldn't connect able to display events,insert events by using php client library.
This is the error i got.
I am using v3 version of client library
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/calendar/v3/calendars/primary?key=****************: (401) Login Required' in /var/www/html/google-api-php-client1/src/Google/Http/REST.php:79
Stack trace:
#0 /var/www/html/google-api-php-client1/src/Google/Http/REST.php(44): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request))
#1 /var/www/html/google-api-php-client1/src/Google/Client.php(503): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#2 /var/www/html/google-api-php-client1/src/Google/Service/Resource.php(195): Google_Client->execute(Object(Google_Http_Request))
#3 /var/www/html/google-api-php-client1/src/Google/Service/Calendar.php(1269): Google_Service_Resource->call('get', Array, 'Google_Service_...')
#4 /var/www/html/simple.php(27): Google_Service_Calendar_Calendars_Resource->get('primary') #5 {main} thrown in /var/www/html/google-api-php-client1/src/Google/Http/REST.php on line 79
since you are getting 401 login required error so you need to set setAccessToken.visit here Error with Google Calendar API - 401 Login required when adding a calendar event
may be you need to issue refreshToken() using the original authenticated access code that contains a refresh token.
// example
$google_client->refreshToken($token->refresh_token);
and use 'setDeveloperKey'. it works.you can see this:https://code.google.com/p/google-api-php-client/issues/detail?id=218
Finally solved problem.
This is the perfect example to get list of events of calender.
<?php
// ...
ini_set('display_errors', 1);
error_reporting(E_ALL);
set_include_path('google-api-php-client1/src');
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
//
$client = new Google_Client();
//print_r($client);exit;
//$client->setUseObjects(true);
$client->setApplicationName("your-app-name");
$client->setClientId("CLIENT id");
$client->setClientSecret('CLIENT SECRET');
$client->setDeveloperKey('DEVELOPER KEY');
$client->setRedirectUri('your url mostly localhost');
$client->setScopes(array(
'https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/calendar.readonly',
));
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
//print_r($_SESSION['token']);exit;
//header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
if (isset($_SESSION['token'])) {
//echo 'innn';exit;
$client->setAccessToken($_SESSION['token']);
//echo 'innn';exit;
}
}
if ($client->getAccessToken()) {
//echo 'innn';exit;
$service = new Google_Service_Calendar($client);
//echo '<pre>'; print_r($service);exit;
//$calendar = $service->calendars->get('primary');
//echo $calendar->getSummary();
$events = $service->events->listEvents('primary');
while(true) {
foreach ($events->getItems() as $event) {
echo $event->getSummary();
}
$pageToken = $events->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$events = $service->events->listEvents('primary', $optParams);
} else {
break;
}
}
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
Script to add event.
Actual problem is Google Calendar version 3 not matching with its documentation.
So I checked Calender.php for all available classes.
$event = new Google_Service_Calendar_Event();
$event->setSummary('Interview');
$event->setLocation('Hell');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('2014-09-04T10:00:00.000-07:00');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('2014-09-04T11:00:00.000-07:00');
$event->setEnd($end);
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail('email#abc.com');
// ...
$attendees = array($attendee1,
// ...
);
$event->attendees = $attendees;
$createdEvent = $service->events->insert('primary', $event);
echo $createdEvent->getId();

Google Spreadsheets API with PHP – Fatal error: Uncaught exception

I'm trying to get started with the google SpreadSheet API. I know there are a bunch of other languages but PHP is the only one I'm vaguely competent in. I keep falling at the first hurdle and getting:
Fatal error: Uncaught exception 'Google\Spreadsheet\Exception' in
/Users/djave/Google Drive/Sites/practise/gdata/lib/Google/Spreadsheet/ServiceRequestFactory.php:48
Stack trace: #0 /Users/djave/Google Drive/Sites/practise/gdata/lib/Google/Spreadsheet/SpreadsheetService.php(37):
Google\Spreadsheet\ServiceRequestFactory::getInstance()
#1 /Users/djave/Google Drive/Sites/practise/gdata/index.php(32): Google\Spreadsheet\SpreadsheetService->getSpreadsheets()
#2 {main} thrown in /Users/djave/Google Drive/Sites/practise/gdata/lib/Google/Spreadsheet/ServiceRequestFactory.php on line 48
How this happens:
Step 1 Download and add the folder google-api-php-client
Next, fiddle with the code until it works
set_include_path('lib/');
require_once 'lib/Google/Client.php';
require_once 'lib/Google/Service/Books.php';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("-------------------------------------");
$service = new Google_Service_Books($client);
$optParams = array('filter' => 'free-ebooks');
$results = $service->volumes->listVolumes('Henry David Thoreau', $optParams);
foreach ($results as $item) {
echo $item['volumeInfo']['title'], "<br /> \n";
}
Result: prints out a list of books
Step 2 Download and install php-google-spreadsheet-client
First off I copy the example exactly below what I have, then include all the right files until it can find everything:
set_include_path('lib/');
require_once 'lib/Google/Client.php';
require_once 'lib/Google/Service/Books.php';
require_once 'lib/Google/Spreadsheet/SpreadsheetService.php';
require_once 'lib/Google/Spreadsheet/ServiceRequestFactory.php';
require_once 'lib/Google/Spreadsheet/Exception.php';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("-------------------------------------");
$service = new Google_Service_Books($client);
$optParams = array('filter' => 'free-ebooks');
$results = $service->volumes->listVolumes('Henry David Thoreau', $optParams);
foreach ($results as $item) {
echo $item['volumeInfo']['title'], "<br /> \n";
}
$spreadsheetService = new Google\Spreadsheet\SpreadsheetService();
$spreadsheetFeed = $spreadsheetService->getSpreadsheets();
$spreadsheet = $spreadsheetFeed->getByTitle('MySpreadsheet');
$worksheetFeed = $spreadsheet->getWorksheets();
But I just get
Fatal error: Uncaught exception 'Google\Spreadsheet\Exception' in /Users/djave/Google Drive/Sites/practise/gdata/lib/Google/Spreadsheet/ServiceRequestFactory.php:48 Stack trace: #0 /Users/djave/Google Drive/Sites/practise/gdata/lib/Google/Spreadsheet/SpreadsheetService.php(37): Google\Spreadsheet\ServiceRequestFactory::getInstance() #1 /Users/djave/Google Drive/Sites/practise/gdata/index.php(23): Google\Spreadsheet\SpreadsheetService->getSpreadsheets() #2 {main} thrown in /Users/djave/Google Drive/Sites/practise/gdata/lib/Google/Spreadsheet/ServiceRequestFactory.php on line 48
I'm doing something really stupid, right? Thanks for any help
Looks like you've forgotten to bootstrap the lib first: https://github.com/asimlqt/php-google-spreadsheet-client#bootstrapping
require 'vendor/autoload.php';
use Google\Spreadsheet\DefaultServiceRequest;
use Google\Spreadsheet\ServiceRequestFactory;
$serviceRequest = new DefaultServiceRequest($accessToken);
ServiceRequestFactory::setInstance($serviceRequest);
Give edit permission to "client_email" field value in client_secret.json file by opening the actual spreadsheet, refer image.

Unable to delete events in Google Calendar using php api

I am working on the PHP API to Google Calendar, I have previously used the Zend library and I am upgrading to the API V3 I downloaded the Git Hub client library v1.0.
I have completed oAuth 2 and I am storing Refresh tokens in a database. I can connect and write events to Google Calendar, thanks mainly to the contributors at StackOverflow. Thanks
My problem is that I cannot delete events. I am connecting with oAuth 2 and retrieving event Ids however
$service->events->delete('primary', $event->getId());
This generates Fatal error: Uncaught exception 'Google_IO_Exception' with message 'HTTP Error: Unable to connect: '0'' in C:\wamp\www\new-roster-decoder\src\Google\IO\Stream.php on line 128
I have hunted high and low and been unable to find a solution. Please help Thanks
EDITED AS SOLVED
Due to Emily's great advice this is solved
Solution downloaded the latest API from GitHub as the problem of GZIP has been sorted.
As a matter of interest I initially commented out GZIP in congig.php and this fixed it, but I then lost the performance benefits, then new library sorted it.
Lessons learnt. Stackoverflow users are very kind to give their time, and always try the lastest software
END OF EDIT
<?php
/// This works
session_start();
set_include_path("src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
require_once 'account/dbc.php';
$client_id = 'XXXXXXXXXX.apps.googleusercontent.com';
$client_secret = 'XXXXXXXXXXX';
$redirect_uri = 'http://localhost:80/new-roster-decoder/account/GoogleoAuth.php';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/calendar");
$client->setAccessType('offline');
$users_rs_settings = mysqli_query($link,"select * from users WHERE id = 118");
$users_array = mysqli_fetch_array($users_rs_settings);
$refresh_token = $users_array['refresh_token']; //2010-04-06
$client->refreshToken($refresh_token);
$service = new Google_Service_Calendar($client);
$event = new Google_Service_Calendar_Event();
$event->setSummary('Positioning TX');
$event->setLocation('BRS-LGW');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('2014-02-19T14:00:00.000-00:00');
$start->setTimeZone('Europe/London');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('2014-02-19T17:25:00.000-00:00');
$end->setTimeZone('Europe/London');
$event->setEnd($end);
// insert ext properties
$rdname = "RosterDecoderID";
$rdvalue = 1;
$extendedProperties = New Google_Service_Calendar_EventExtendedProperties();
$extendedProperties->setPrivate(array($rdname=>$rdvalue));
$event->setExtendedProperties($extendedProperties);
// end of insert ext properties
$createdEvent = $service->events->insert('primary', $event);
echo $createdEvent->getId()."\n\n";
$_SESSION['access_token'] = $client->getAccessToken();
var_dump($_SESSION['access_token']);
var_dump($event);
$minCheck = date(DATE_ATOM, mktime(0, 0, 0, date("m"), date("d"), date("Y") ));
$maxCheck = date(DATE_ATOM, mktime(0, 0, 0, date("m"), (date("d")+1), date("Y") ));
$optParams = array( 'privateExtendedProperty' => 'RosterDecoderID=1','timeMin' => $minCheck, 'timeMax' => $maxCheck);
$events = $service->events->listEvents('primary', $optParams);
while(true) {
foreach ($events->getItems() as $event) {
$eventID = $event->getId();
//////////////////////////////////////////////////////////
//This bit throws an error
$service->events->delete('primary', $event->getId());
/////////////////////////////////////////////////////////
// The error is
// Fatal error: Uncaught exception 'Google_IO_Exception' with message 'HTTP Error: Unable to connect: '0'' in C:\wamp\www\new-roster-decoder\src\Google\IO\Stream.php on line 128
echo $event->getSummary();
echo $event->getId()."\n\n";
}
}
?>
I am able to delete event from google calendar..
use private key file you get from developer console.
Fore more info check this link
What is the Google API password for the OAuth PKCS p12 private key?
how-where-to-obtain-a-p12-key-file-from-the-google-developers-console
below is code please check
const KEY_FILE = '<<some location on server>>/xxx-65454f656a-xxx-560265d-privatekey.p12';
// this is my private key file location, make sure it accessible
try {
$key = file_get_contents(KEY_FILE);
$auth = new \Google_Auth_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/calendar'),
$key);
$auth->sub = $calendarId;
$client = new \Google_Client();
$client->setAssertionCredentials($auth);
$client->setApplicationName("Parabola V2");
$client->setClientId(CLIENT_ID);
$service = new \Google_Service_Calendar($client);
$service->events->delete($calendarId, $eventId);
} catch (\Exception $e) {
echo "Exception while deleting event :- ".$e->getMessage();
return null;
}
$service->events->delete('primary', $event->getId());
'primary' must be the calendar id
"myname#gmail.com" or "mhggf54gfh5#group.calendar.google.com"
thats how it work for me

Google Calendar API v3 - Google_AuthException - Could not json decode the token issue

I've searched this Group, plus others, along with other websites and cannot find a solution to this. Error output is below. I definitely know that setAccessToken should NOT be NULL. Any guidance would be great here. the Google Calendar v3 API documentation is not so great...in fact, the samples are for older API versions.
PHP Fatal error: Uncaught exception 'Google_AuthException' with message 'Could not json decode the token' in google-api-php-client/src/auth/Google_OAuth2.php:162
Stack trace:
0 google-api-php-client/src/Google_Client.php(170): Google_OAuth2->setAccessToken(NULL)
1 Cal.php(16): Google_Client->setAccessToken(true)
2 {main}
thrown in google-api-php-client/src/auth/Google_OAuth2.php on line 162
Below is the code for my app:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_CalendarService.php';
session_start();
$client = new Google_Client();
$service = new Google_CalendarService($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
} else {
$client->setAccessToken($client->authenticate($_GET['code']));
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$event = new Google_Event();
$event->setSummary('Appointment');
$event->setLocation('Somewhere');
$start = new Google_EventDateTime();
$start->setDateTime('2013-10-05T10:00:00.000-07:00');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime('2013-10-05T10:25:00.000-07:00');
$event->setEnd($end);
$attendee1 = new Google_EventAttendee();
$attendee1->setEmail('my#email.com');
// ...
$attendees = array($attendee1);
$event->attendees = $attendees;
$createdEvent = $service->events->insert('primary', $event);
echo $createdEvent->getId();
} else {
echo "failed hard";
}
?>
ClientID, Key, etc are kept in my google-api-php-client/src/config.php file
I haven't reviewed the api docs in a while but I use something like the following to configure the client. Maybe it will help.
$certFile = file_get_contents('/path/to/cert.p12');
$client = new Google_Client();
$client->setApplicationName('My App');
$client->setClientId($clientId);
$client->setScopes([
'https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/calendar.readonly',
]);
if ($token = $_SESSION['google.calendar.token']) {
$client->setAccessToken($token);
}
$credentials = new Google_AssertionCredentials($service_email, $client->getScopes(), $certFile);
$client->setAssertionCredentials($credentials);
$service = new Google_CalendarService($client);

Categories