Google Calendar API v3 cant add event php - 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.

Related

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

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.

Google_ServiceException error when retrieving list of users (using Google API SDK)

I am using the following code to retrieve the list of users associated with my Google apps admin account. It's working fine when using a Google apps admin account but when using other Google apps/Gmail accounts an error appears.
Code:
<?php
require_once 'test_user/src/Google_Client.php';
require_once 'test_user/src/contrib/Google_PlusService.php';
require_once 'test_user/src/contrib/Google_Oauth2Service.php';
require_once 'test_user/src/contrib/Google_DirectoryService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("ApplicationName");
//*********** Replace with Your API Credentials **************
$client->setClientId('****');
$client->setClientSecret('****');
$client->setRedirectUri('****');
$client->setDeveloperKey('****');
//************************************************************
$client->setScopes(array('https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/admin.directory.user'));
$plus = new Google_PlusService($client);
$oauth2 = new Google_Oauth2Service($client); // Call the OAuth2 class for get email address
$adminService = new Google_DirectoryService($client); // Call directory API
error_reporting(E_ALL);
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken())
{
$user = $oauth2->userinfo->get();
$me = $plus->people->get('me');
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); // get the USER EMAIL ADDRESS using OAuth2
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
$users = $adminService->users->get($email);
//print_r($users);
//$list_users = $adminService->users->listUsers();
$adminOptParams = array('customer' => 'my_customer');
$list_users = $adminService->users->listUsers($adminOptParams);
print '<h2>Response Result:</h2><pre>' . print_r($list_users, true) . '</pre>';
$_SESSION['access_token'] = $client->getAccessToken();
}
else
{
$authUrl = $client->createAuthUrl();
header("location:$authUrl");
}
?>
Error:
Fatal error: Uncaught exception 'Google_ServiceException' with message 'Error calling GET
https://www.googleapis.com/admin/directory/v1/users/william.nelson920#gmail.com?key=AIzaSyBp0yBFCCosu113tbNbw7yAIjIt1ndFFIs: (404) Resource Not
Found: userKey' in /var/www/vhosts/vx44.com/httpdocs/test_user/src/io/Google_REST.php:66 Stack trace: #0
/var/www/vhosts/vx44.com/httpdocs/test_user/src/io/Google_REST.php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest)) #1
/var/www/vhosts/vx44.com/httpdocs/test_user/src/service/Google_ServiceResource.php(186): Google_REST::execute(Object(Google_HttpRequest)) #2
/var/www/vhosts/vx44.com/httpdocs/test_user/src/contrib/Google_DirectoryService.php(653): Google_ServiceResource->__call('get', Array) #3
/var/www/vhosts/vx44.com/httpdocs/test_user/test_user.php(54): Google_UsersServiceResource->get('william.nelson9...') #4 {main} thrown in
/var/www/vhosts/vx44.com/httpdocs/test_user/src/io/Google_REST.php on line 66
The Directory API is restricted for Google Apps Admin only. It allows domain administrators to retrieve domain users' information.
You should be able to get user information from your own domain (and your own domain ONLY). In your case, you are trying to get the user information of 'william.nelson920#gmail.com'. Since gmail.com is a consumer Google Apps product, and I don't think you are the administrator of gmail.com? The API is throwing the correct error indicating that this user does not exist in your domain.
Here is more info about the get request from Google documentation
https://developers.google.com/admin-sdk/directory/v1/guides/manage-users#get_user
Hope this helps!

Google Admin SDK in PHP

I am using the following code to retrieve the list of users associated with my google apps account.
There is no problem with authentication but when the redirection made this error is appearing.
index.php
<?php
require_once 'test_user/src/Google_Client.php';
require_once 'test_user/src/contrib/Google_PlusService.php';
require_once 'test_user/src/contrib/Google_Oauth2Service.php';
require_once 'test_user/src/contrib/Google_DirectoryService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("ApplicationName");
//*********** Replace with Your API Credentials **************
$client->setClientId('****');
$client->setClientSecret('****');
$client->setRedirectUri('****');
$client->setDeveloperKey('****');
//************************************************************
$client->setScopes(array('https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/admin.directory.user.readonly'));
$plus = new Google_PlusService($client);
$oauth2 = new Google_Oauth2Service($client); // Call the OAuth2 class for get email address
$adminService = new Google_DirectoryService($client); // Call directory API
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken())
{
$user = $oauth2->userinfo->get();
$me = $plus->people->get('me');
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); // get the USER EMAIL ADDRESS using OAuth2
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
//$users = $adminService->users->get($email);
$list_users = $adminService->users->listUsers();
print '<h2>Response Result:</h2><pre>' . print_r($list_users, true) . '</pre>';
$_SESSION['access_token'] = $client->getAccessToken();
}
else
{
$authUrl = $client->createAuthUrl();
header("location:$authUrl");
}
?>
error i'm getting:
Fatal error: Uncaught exception 'Google_ServiceException' with message 'Error calling
GET https://www.googleapis.com/admin/directory/v1/users?
key=AIzaSyBp0yBFCCosu113tbNbw7yAIjIt1ndFFIs: (400) Bad Request' in
/var/www/vhosts/vx44.com/httpdocs/test_user/src/io/Google_REST.php:66 Stack trace: #0
/var/www/vhosts/vx44.com/httpdocs/test_user/src/io/Google_REST.php(36):
Google_REST::decodeHttpResponse(Object(Google_HttpRequest)) #1
/var/www/vhosts/vx44.com/httpdocs/test_user/src/service/Google_ServiceResource.php(186):
Google_REST::execute(Object(Google_HttpRequest)) #2
/var/www/vhosts/vx44.com/httpdocs/test_user/src/contrib/Google_DirectoryService.php(695):
Google_ServiceResource->__call('list', Array) #3
/var/www/vhosts/vx44.com/httpdocs/test_user/test_user.php(52):
Google_UsersServiceResource->listUsers('nelson302.com') #4 {main} thrown in/var/www/vhosts/vx44.com/httpdocs/test_user/src/io/Google_REST.php on line 66
Note that i've enabled Admin SDK on Google APIs Console.
What am i doing wrong here? thank you for helping
Try replacing:
$list_users = $adminService->users->listUsers();
with:
$adminOptParams = array('customer' => 'my_customer');
$list_users = $adminService->users->listUsers($adminOptParams);
this is explained in the Admin SDK Developer's Guide.

Categories