Google Spreadsheets API with PHP – Fatal error: Uncaught exception - php

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.

Related

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

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);

UnauthorizedException in reading emails with Oauth 2 using EWS

I am trying to load email list using oauth 2. Following is my code:
<?php
require_once "vendor/autoload.php";
use src\API\Type;
use garethp\ews\MailAPI as API;
$token='EwA......'; //access token
$api = API::withCallbackToken('outlook.office365.com', $token);
$mail = $api->getMailItems();
foreach ($mail as $email) {
$email = $api->getItem($email->getItemId());
$email_id=$email->getItemId();
$subject = $email->getSubject();
$sender = $email->getSender()->getMailbox()->getEmailAddress();
$body = (string) $email->getBody();
echo $body;
}
but getting response as follows:
Fatal error: Uncaught garethp\ews\API\Exception\UnauthorizedException
in
C:\inetpub\wwwroot\bephpforTteam\New\php_ews\php-ews-master\src\API\ExchangeWebServices.php:438
Stack trace: #0
C:\inetpub\wwwroot\bephpforTteam\New\php_ews\php-ews-master\src\API\ExchangeWebServices.php(356):
garethp\ews\API\ExchangeWebServices->handleNonSuccessfulResponses(NULL,
401) #1
C:\inetpub\wwwroot\bephpforTteam\New\php_ews\php-ews-master\src\API\ExchangeWebServices\MiddlewareFactory.php(57):
garethp\ews\API\ExchangeWebServices->processResponse(NULL) #2
C:\inetpub\wwwroot\bephpforTteam\New\php_ews\php-ews-master\src\API\ExchangeWebServices.php(497):
garethp\ews\API\ExchangeWebServices->garethp\ews\API\ExchangeWebServices{closure}(Object(garethp\ews\API\MiddlewareRequest),
Object(Closure)) #3
C:\inetpub\wwwroot\bephpforTteam\New\php_ews\php-ews-master\src\API\ExchangeWebServices\MiddlewareFactory.php(66):
garethp\ews\API\ExchangeWebServices->garethp\ews\API{closure}(Object(garethp\ews\API\MiddlewareRequest)) #4 C:\inetpub\wwwroot\bephpforTt in C:\inetpub\wwwroot\bephpforTteam\New\php_ews\php-ews-master\src\API\ExchangeWebServices.php
on line 438

Google drive API 403 insufficent permission error (do I need a google for work account?)

I would like to create an application to add folders and data inside those folders in Google Drive.
I am succesfully creating an acccess token using the refresh_token value. I am attempting to do a very basic file upload but its failing. I am also getting a list of files just to see is anything else working and that certainly is.
After the list of files appear I get the following error...
Fatal error: Uncaught exception 'Google_Service_Exception' with
message 'Error calling POST
https://www.googleapis.com/upload/drive/v3/files?uploadType=media:
(403) Insufficient Permission' in
/var/www/html/google-api-php-client/src/Google/Http/REST.php:110
Stack trace: #0
/var/www/html/google-api-php-client/src/Google/Http/REST.php(62):
Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request),
Object(Google_Client))
1 [internal function]: Google_Http_REST::doExecute(Object(Google_Client),
Object(Google_Http_Request))
2 /var/www/html/google-api-php-client/src/Google/Task/Runner.php(174):
call_user_func_array(Array, Array)
3 /var/www/html/google-api-php-client/src/Google/Http/REST.php(46): Google_Task_Runner->run()
4 /var/www/html/google-api-php-client/src/Google/Client.php(593): Google_Http_REST::execute(Object(Google_Client),
Object(Google_Http_Request))
5 /var/www/html/google-api-php-client/src/Google/Service/Resource.php(240):
Google_Client->execute(Object(Google_H in
/var/www/html/google-api-php-client/src/Google/Http/REST.php on line
110
UPDATE: I tried this without using refresh_token too and simply using the latest access token but still getting the exact same error.
Initially setting up access to get myself to the consent screen...
require_once ('../autoload.php');
ini_set('display_errors',1);
error_reporting(E_ALL);
session_start();
$client = new Google_Client();
$client->setAuthConfig('client_secret.json');
$client->addScope("https://www.googleapis.com/auth/drive");
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setRedirectUri('http://www.example.com/oauth2callback.php');
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
print_r($_SESSION);
$client->setAccessToken($_SESSION['access_token']);
$drive_service = new Google_Service_Drive($client);
//$files_list = $drive_service->files->listFiles(array())->getItems();
//echo json_encode($files_list);
} else {
$redirect_uri = 'http:/www.example.com/google-api-php-client/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
And then attempting to upload the file
error_reporting(E_ALL); ini_set('display_errors', 1);
require_once ('../autoload.php');
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('client_secret.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
// this token is obtained the first time from refresh_token, it will not be shown after the initial requrest
$refreshToken ='xxx';
$client->refreshToken($refreshToken);
$service = new Google_Service_Drive($client);
$files_list = $service->files->listFiles(array())->getFiles();
echo '<pre>';
print_r($files_list);
echo '</pre>';
$client->addScope("https://www.googleapis.com/auth/drive");
DEFINE("TESTFILE", 'testfile-small.txt');
if (!file_exists(TESTFILE)) {
$fh = fopen(TESTFILE, 'w');
fseek($fh, 1024 * 1024);
fwrite($fh, "!", 1);
fclose($fh);
}
if ($client->getAccessToken()) {
// This is uploading a file directly, with no metadata associated.
$file = new Google_Service_Drive_DriveFile();
$result = $service->files->create(
$file,
array(
'data' => file_get_contents(TESTFILE),
'mimeType' => 'application/octet-stream',
'uploadType' => 'multipart'
)
);
}

Get Sharepoint data list in php

I tried to get SharePoint list in php. Below is code
require_once __DIR__ . '\Faker-master\src\autoload.php'; //Faker library (https://github.com/fzaninotto/Faker)
require_once 'lib/SPOClient.php';
$username = 'aaaa.aaa#microsoft.com';
$password = '*******';
$url = "https://microsoft.sharepoint.com";
generateContacts($url,$username,$password);
function generateContacts($url,$username,$password){
$client = new SPOClient($url);
$client->signIn($username,$password);
$list = $client->getList('ClientMaster');
$contactsCount = 120;
for($i = 0; $i < $contactsCount; $i++){
$contactEntry = createContactEntry();
$item = $list->addItem($contactEntry);
print "Contact '{$item->Title}' has been created succesfully.\r\n";
}
}
O/p:
Fatal error: Uncaught exception 'Exception' with message 'Invalid STS request. ' in E:\Apps\xampp\htdocs\ep\lib\SPOClient.php:260 Stack trace: #0 E:\Apps\xampp\htdocs\ep\lib\SPOClient.php(242): SPOClient->processToken('requestToken('ssss.kkkk...', '*****') #2 E:\Apps\xampp\htdocs\ep\listexamples.php(24): SPOClient->signIn('ssss.kkkk...', '******') #3 E:\Apps\xampp\htdocs\ep\listexamples.php(15): generateContacts('https://worldem...', 'sssss.kkk...', '******') #4 {main} thrown in E:\Apps\xampp\htdocs\ep\lib\SPOClient.php on line 260

Google Calendar API v3 cant add event php

hey cant seem to create an event with this code,
<?php
require_once 'google-api-php-client/src/apiClient.php'
require_once 'google-api-php-client/src/contrib/apiCalendarService.php';
session_start();
$client = new apiClient();
$client->setApplicationName("Cal");
$client->setClientId('');
$client->setClientSecret('');
//$client->setRedirectUri('http://localhost:8080/createEvent.php');
$client->setRedirectUri('http://localhost:8080/eventNew.php');
//http://localhost:8080/oauth2callback');
$client->setDeveloperKey('');
$cal = new apiCalendarService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
$authUrl = $client->createAuthUrl();
if (!$client->getAccessToken()) {
$event = new Event();
$event->setSummary("test title");
$event->setLocation("test location");
$start = new EventDateTime();
$start->setDateTime('04-03-2012 09:25:00:000 -05:00');
$event->setStart($start);
$end = new EventDateTime();
$end->setDateTime('04-03-2012 10:25:00:000 -05:00');
$event->setEnd($end);
//$attendee1 = new EventAttendee();
//$attendee1->setEmail('email#email.com');
//$attendees = array($attendee1);
//$event->attendees = $attendees;
$createdEvent = $cal->events->insert('primary', $event);
echo $createdEvent->getId();
$_SESSION['token'] = $client->getAccessToken();
}
?>
Keep getting this error message:
Fatal error: Uncaught exception 'apiIOException' with message 'HTTP Error: (0) SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed' in C:\Program Files\EasyPHP-5.3.9\www\google-api-php-client\src\io\apiCurlIO.php:119 Stack trace: #0 C:\Program Files\EasyPHP-5.3.9\www\google-api-php-client\src\io\apiCurlIO.php(56): apiCurlIO->makeRequest(Object(apiHttpRequest)) #1 C:\Program Files\EasyPHP-5.3.9\www\google-api-php-client\src\io\apiREST.php(55): apiCurlIO->authenticatedRequest(Object(apiHttpRequest)) #2 C:\Program Files\EasyPHP-5.3.9\www\google-api-php-client\src\service\apiServiceResource.php(186): apiREST::execute(Object(apiServiceRequest)) #3 C:\Program Files\EasyPHP-5.3.9\www\google-api-php-client\src\contrib\apiCalendarService.php(493): apiServiceResource->__call('insert', Array) #4 C:\Program Files\EasyPHP-5.3.9\www\eventNew.php(47): EventsServiceResource->insert('primary', Object(Event)) #5 {main} thrown in C:\Program Files\EasyPHP-5.3.9\www\google-api-php-client\src\io\apiCurlIO.php on line 119
It seems that your version of PHP on Windows is not set up to verify peer SSL certificates.
There is some information at this link which describes how to fix the problem.
Basically, you need to install the CA bundle on the Windows machine and then add one line to your code, telling it where to look for the CA bundle.
Some programs already have CA bundles with them.
I've used the GIT certificate bundle before when I was having this problem.

Categories