I am a student and now it's the final stage of my final project. I am working with PHP. The documentation that I worked with is: https://developers.google.com/calendar/quickstart/php
My problem is that the Token returns NULL.
The error I get is:
PHP Fatal error: Uncaught InvalidArgumentException: invalid json token in C:\wamp64\www\MarryMe\vendor\google\apiclient\src\Google\Client.php:420
Stack trace:
#0 C:\wamp64\www\MarryMe\insertevent.php(26): Google_Client->setAccessToken(NULL)
#1 C:\wamp64\www\MarryMe\insertevent.php(66): getClient()
#2 {main}
thrown in C:\wamp64\www\MarryMe\vendor\google\apiclient\src\Google\Client.php on line 420
Here is my code:
require_once('./conection/init.php');
require __DIR__ . '/vendor/autoload.php';
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('MarryMe');
$client->setScopes(Google_Service_Calendar::CALENDAR_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 {
if (!isset($_GET['code'])) {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
header("location: $authUrl");
} else {
$code = $_GET['code'];
$authCode = trim($code);
var_dump($authCode);
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
var_dump($accessToken);
$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' => 50,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
$events = $results->getItems();
$event = new Google_Service_Calendar_Event(array(
'summary' => $_SESSION['name'],
'location' => ' ',
'description' => $_SESSION['description'],
'start' => array(
'dateTime' => $_SESSION['start_date'],
'timeZone' => 'UTC',
),
'end' => array(
'dateTime' => $_SESSION['due_date'],
'timeZone' => 'UTC',
),
'reminders' => array(
'useDefault' => FALSE,
'overrides' => array(
array('method' => 'email', 'minutes' => 24 * 60),
array('method' => 'popup', 'minutes' => 10),
),
),
));
$calendarId = 'primary';
$event = $service->events->insert($calendarId, $event);
header("location:./includes/tasksProcess/tasks.php");
//end of insert event ```
Make sure that __DIR__ . is before where your credentials is instantiated so that the function knows where to look for the json file:
so it should look like this
$client->setAuthConfig( __DIR__ . 'credentials.json');
Related
Is it possible to have add/edit/delete events in Google Calendar?
Because all I have accomplished is just to read my events. I`m enabling all the "scopes" I can find about the Calendar API but still I get an error 403 about "Request had insufficient authentication scopes / PERMISSION DENIED".
I have done so many tries to fix that and everytime I get to the same point. I am using OAuth 2.0 Client IDs credentials and one more question I have is which url I should use for the Authorized redirect URIs.
<?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 Calendar API PHP Quickstart');
$client->setScopes(Google_Service_Calendar::CALENDAR_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_Calendar($client);
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
$events = $results->getItems();
#--------------------------------------------------------------------------------------------
// Refer to the PHP quickstart on how to setup the environment:
// https://developers.google.com/calendar/quickstart/php
// Change the scope to Google_Service_Calendar::CALENDAR and delete any stored
// credentials.
$event = new Google_Service_Calendar_Event(array(
'summary' => 'Google I/O 2015',
'location' => '800 Howard St., San Francisco, CA 94103',
'description' => 'A chance to hear more about Google\'s developer products.',
'start' => array(
'dateTime' => '2015-05-28T09:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => '2015-05-28T17:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'recurrence' => array(
'RRULE:FREQ=DAILY;COUNT=2'
),
'attendees' => array(
array('email' => 'lpage#example.com'),
array('email' => 'sbrin#example.com'),
),
'reminders' => array(
'useDefault' => FALSE,
'overrides' => array(
array('method' => 'email', 'minutes' => 24 * 60),
array('method' => 'popup', 'minutes' => 10),
),
),
));
$calendarId = 'primary';
$event = $service->events->insert($calendarId, $event);
printf('Event created: %s\n', $event->htmlLink);
#--------------------------------------------------------------------------------------------------------
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);
echo "<br>";
}
}
?>
I was able to create the event by using your same code with a minor edit. I modified the read-only scope to allow read/write access instead of read-only. This is the final result:
<?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 Calendar API PHP Quickstart');
$client->setScopes(Google_Service_Calendar::CALENDAR);
$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_Calendar($client);
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c') ,
);
$results = $service
->events
->listEvents($calendarId, $optParams);
$events = $results->getItems();
#--------------------------------------------------------------------------------------------
// Refer to the PHP quickstart on how to setup the environment:
// https://developers.google.com/calendar/quickstart/php
// Change the scope to Google_Service_Calendar::CALENDAR and delete any stored
// credentials.
$event = new Google_Service_Calendar_Event(array(
'summary' => 'Google I/O 2015',
'location' => '800 Howard St., San Francisco, CA 94103',
'description' => 'A chance to hear more about Google\'s developer products.',
'start' => array(
'dateTime' => '2015-05-28T09:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
) ,
'end' => array(
'dateTime' => '2015-05-28T17:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
) ,
'recurrence' => array(
'RRULE:FREQ=DAILY;COUNT=2'
) ,
'attendees' => array(
array(
'email' => 'lpage#example.com'
) ,
array(
'email' => 'sbrin#example.com'
) ,
) ,
'reminders' => array(
'useDefault' => false,
'overrides' => array(
array(
'method' => 'email',
'minutes' => 24 * 60
) ,
array(
'method' => 'popup',
'minutes' => 10
) ,
) ,
) ,
));
$calendarId = 'primary';
$event = $service
->events
->insert($calendarId, $event);
printf('Event created: %s\n', $event->htmlLink);
#--------------------------------------------------------------------------------------------------------
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);
echo "<br>";
}
}
?>
I have successfully integrated google OAuth 2.0 with Calendar permissions and I am storing access token and refresh token in the database, after that fetch both token. do not know what wrong I am doing the Calendar event not being created.
<?php
include($_SERVER["DOCUMENT_ROOT"]."/config.php");
include($_SERVER["DOCUMENT_ROOT"]."/functions.php");
require 'vendor/autoload.php';
function getClient($useremail)
{
$client = new Google_Client();
$client->setApplicationName('Google Calendar API PHP Quickstart');
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
$currentTime=date('Y-m-d H:i:s');
$result = dbRowsSelect(array('refresh_token','access_token','expire_on'), "calendar_api_users",
"email = '".$useremail."' ","LIMIT 1");
if(count($result) > 0)
{
$accessToken = $result[0]['access_token'];
$expire_on=$result[0]['expire_on'];
if(strtotime($currentTime) < strtotime($expire_on))
{
$client->setAccessToken($accessToken);
}
else
{
$refreshToken = $result[0]['refresh_token'];
// Refresh the token if possible, else fetch a new one.
$client->fetchAccessTokenWithRefreshToken($refreshToken);
}
}
return $client;
}
// Get the API client and construct the service object.
$email='xxxxx.xxxxxxx#gmail.com';
$client = getClient($email);
$service = new Google_Service_Calendar($client);
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
$events = $results->getItems();
$event = new Google_Service_Calendar_Event(array(
'summary' => 'Google I/O 2015',
'location' => '800 Howard St., San Francisco, CA 94103',
'description' => 'A chance to hear more about Google\'s developer products.',
'start' => array(
'dateTime' => '2021-06-29T09:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => '2021-06-29T17:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'recurrence' => array(
'RRULE:FREQ=DAILY;COUNT=1'
),
'reminders' => array(
'useDefault' => FALSE,
'overrides' => array(
array('method' => 'email', 'minutes' => 24 * 60),
array('method' => 'popup', 'minutes' => 10),
),
),
));
$calendarId = 'primary';
$event = $service->events->insert($calendarId, $event);
printf('Event created: %s\n', $event->htmlLink);
I have fetched access token and refresh token from database , I dont know where is error as its showing white screen no error.
Thanks in advance
When you get the result back from the database, set both the access token and the refresh token.
Then call isAccessTokenExpired if it is then call fetchAccessTokenWithRefreshToken
$client->refreshToken($result[0]['refresh_token']);
$client->setAccessToken($result[0]['access_token']);
// Refresh the access token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
// Note: add code here to save the new access token and refresh token.
}
NOTE: IMO there is no reason for you to be storing the access token you can just store the refresh token set that and then request a new one everytime. Google wont mind. 😊
I'm building the code to create a new event for google calendar. Actually inserted data are static since I focus on using Google API.
If I run my code I get that:
"domain": "global", "reason": "insufficientPermissions", "message": "Insufficient Permission"
I'm able to read an event list but not to create the event:
require_once __DIR__ . '/../vendor/autoload.php';
define('APPLICATION_NAME', 'Google Calendar API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/calendar-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/../client_secret.json');
define('SCOPES', implode(' ', array(
Google_Service_Calendar::CALENDAR)
));
function expandHomeDirectory($path) {
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
}
return str_replace('~', realpath($homeDirectory), $path);
}
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} 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);
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Calendar($client);
$calendarId='primary';
// $calendarId should contain the calendar id found on the settings page of the calendar
/*
$events = $service->events->listEvents($calendarId);
echo '<pre>';
print_r($events);
echo '</pre>';
*/
$event = new Google_Service_Calendar_Event(array(
'summary' => 'Google I/O 2015',
'location' => '800 Howard St., San Francisco, CA 94103',
'description' => 'A chance to hear more about Google\'s developer products.',
'start' => array(
'dateTime' => '2018-01-28T09:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => '2015-05-28T17:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'recurrence' => array(
'RRULE:FREQ=DAILY;COUNT=2'
),
'attendees' => array(
array('email' => 'aaa#gmail.com'),
array('email' => 'bbb#gmail.com'),
),
'reminders' => array(
'useDefault' => FALSE,
'overrides' => array(
array('method' => 'email', 'minutes' => 24 * 60),
array('method' => 'popup', 'minutes' => 10),
),
),
));
$calendarId = 'primary';
$event = $service->events->insert($calendarId, $event);
printf('Event created: %s\n', $event->htmlLink);
For further reference and for those who will face the same issue: if you generate a new token for full acccess and you already have a valid one for read only you have to delete the firts one and generate the new one.
I didn't and the valid token was never replaced so I kept having only read only access.
I am trying to insert an event in my calendar using calendar id.
I just copied a code snippet from here
and downloaded SDK from here
Here is my code
<?php
// Refer to the PHP quickstart on how to setup the environment:
// https://developers.google.com/google-apps/calendar/quickstart/php
// Change the scope to Google_Service_Calendar::CALENDAR and delete any stored
// credentials.
include('google-api-php-client-2.0.3/vendor/autoload.php');
include('google-api-php-client-2.0.3/src/Google/Client.php');
include('google-api-php-client-2.0.3/src/Google/Service/Resource.php');
include('google-api-php-client-2.0.3/google-api-php-client-2.0.3/vendor/google/apiclient-services/src/Google/Service/Calendar.php');
include('google-api-php-client-2.0.3/google-api-php-client-2.0.3/src/Google/Service.php');
$event = new Google_Service_Calendar_Event(array(
'summary' => 'Google I/O 2015',
'location' => '800 Howard St., San Francisco, CA 94103',
'description' => 'A chance to hear more about Google\'s developer products.',
'start' => array(
'dateTime' => '2015-05-28T09:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => '2015-05-28T17:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'recurrence' => array(
'RRULE:FREQ=DAILY;COUNT=2'
),
'attendees' => array(
array('email' => 'lpage#example.com'),
array('email' => 'sbrin#example.com'),
),
'reminders' => array(
'useDefault' => FALSE,
'overrides' => array(
array('method' => 'email', 'minutes' => 24 * 60),
array('method' => 'popup', 'minutes' => 10),
),
),
));
$calendarId = 'xxxxxxxxxxxxxx#group.calendar.google.com';
$client = new Google_Client();
$client->setApplicationName("schedular app");
$client->setClientId('xxxxx.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxxxxxx');
$service = new Google_Service_Calendar_Events_Resource($client,$event,'','');
$events = $service->insert($calendarId, $event);
printf('Event created: %s\n', $event->htmlLink);
?>
but I am getting error like
Fatal error: Cannot declare class Google_Service, because the name is already in use in D:\xampp\htdocs\gmt\google-api-php-client-2.0.3\src\Google\Service.php on line 18
How to solve this. or what i am doing wrong. please help.
I guess the root of your problem is that you are using too many includes. Use only include('google-api-php-client-2.0.3/vendor/autoload.php'); and delete the rest of them. I think that the way your code is structured should be enough to create the event, but the way I prefer doing it is this way:
<?php
session_start();
//INCLUDE PHP CLIENT LIBRARY
require_once "google-api-php-client-2.0.3/vendor/autoload.php";
$client = new Google_Client();
$client->setAuthConfig("client_creds.json");
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/index.php');
$client->addScope("https://www.googleapis.com/auth/calendar");
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$cal = new Google_Service_Calendar($client);
$event = new Google_Service_Calendar_Event(array(
'summary' => 'Event One',
'location' => 'Some Location',
'description' => 'Google API Test Event',
'start' => array(
'dateTime' => '2016-11-14T10:00:00-07:00'
),
'end' => array(
'dateTime' => '2016-11-14T10:25:00-07:00'
),
'reminders' => array(
'useDefault' => FALSE,
'overrides' => array(
array('method' => 'email', 'minutes' => 24 * 60),
array('method' => 'popup', 'minutes' => 10),
),
),
));
$calendarId = 'primary';
$event = $cal->events->insert($calendarId, $event);
printf('Event created: %s\n', $event->htmlLink);
} else {
if (!isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/index.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
?>
Please note that for the calendar Id value I am using 'primary' because it will be the primary calendar of the authenticated user. Please refer to the documentation here for more details. I hope this helps!
Check all the files that you have include, this may have cause this error. Also you might want to start with PHP Quickstart:
Complete the steps described a simple PHP command-line application that makes requests to the Google Calendar API.
Here is their sample code:
<?php
require_once __DIR__ . '/vendor/autoload.php';
define('APPLICATION_NAME', 'Google Calendar API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/calendar-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/calendar-php-quickstart.json
define('SCOPES', implode(' ', array(
Google_Service_Calendar::CALENDAR_READONLY)
));
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(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} 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);
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($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_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);
if (count($results->getItems()) == 0) {
print "No upcoming events found.\n";
} else {
print "Upcoming events:\n";
foreach ($results->getItems() as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
printf("%s (%s)\n", $event->getSummary(), $start);
}
}
This shows what are the needed files to be included. Hope this helps.
I modified the Google Calendar API quickstart to make an
$myEvent = $service->events->insert($calendarId, $myEvent);
and got a Error :
PHP Fatal error: Uncaught Google_Service_Exception: {
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}
Here my code:
<?php
require_once __DIR__ . '/vendor/autoload.php';
define('APPLICATION_NAME', 'gCal2phposteo');
define('CREDENTIALS_PATH', '~/.credentials/altesGCal.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/altesGCal.json
define('SCOPES', implode(' ', array(
Google_Service_Calendar::CALENDAR)
));
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(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
//pk, from StackOverflow https://stackoverflow.com/questions/10827920/not-receiving-google-oauth-refresh-token
// $client->setApprovalPrompt('force'); // needed if you loose the refreshToken
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} 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);
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
//pk, BUG: refresh token is not saved
if ($client->isAccessTokenExpired()) {
$refreshToken = $client->getRefreshToken();
$client->fetchAccessTokenWithRefreshToken($refreshToken); // loosing the refresh token here !
$myAccess = $client->getAccessToken();
$myAccess['refresh_token'] = $refreshToken;
file_put_contents($credentialsPath, json_encode($myAccess));
}
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_Calendar($client);
$calendarId = 'primary';
$myEvent = new Google_Service_Calendar_Event(
array(
'summary' => 'pk4test Summary',
'location' => 'Village-Neuf, 1 rue des alouettes',
'description' => 'Consultation d\'ostéopathie.',
'start' => array(
'dateTime' => '2016-11-07T18:15:00.000+01:00',
'timeZone' => 'Europe/Paris',
),
'end' => array(
'dateTime' => '2016-11-07T19:00:00.000+01:00',
'timeZone' => 'Europe/Paris',
),
'attendees' => array(
array(
'email' => 'osteo#kienner.fr',
'organizer' => true
),
# array('email' => 'xx#domain.fr', 'resource' => true),
),
'creator' => array(
'email' => 'osteo#kienner.fr',
'displayName' => 'Cabinet d\'ostéopathie Kienner Mireille',
'self' => true
),
'guestsCanInviteOthers' => false,
'guestsCanModify' => false,
'guestsCanSeeOtherGuests' => false,
)
);
$myEvent = $service->events->insert($calendarId, $myEvent);
printf('Event created: %s', $myEvent->htmlLink);
I have seen 3 posts saying that I should share my calendar with the automatically created service account:
POST 1:
403 Forbidden message when calling the v3 Google Calendar API using a Service Account via OAuth 2.0
POST 2:
Edit Google calendar events from Google service account: 403.
I found 2 created accounts, even though I think I have to share with the XXXXXXXX#developer.gserviceaccount.com, I also shared the calendar with myProjectName##appspot.gserviceaccount.com
Anyone an idea what is wrong ?
Try deleting any stored credentials.
In your case '~/.credentials/altesGCal.json'.
Make sure you also grant the appropriate permissions to the client email address created from the Google Developer console. What I suggest is to follow the steps outlined in the OAuth guide.