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>";
}
}
?>
Related
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');
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 integrate google calendar with my application successfully.
First time, i authenticate successfully and all the events are created on google calendar properly.
Now, second time i don't want to authenticate, i just want to click on a button then the all the new events from my application should be created on google calendar.
I guess that it will be done by the refresh token.
I received token.
See my below code for that.
<?php
session_start();
require_once('vendor/google/apiclient/src/Google/autoload.php');
require_once 'vendor/google/apiclient/src/Google/Client.php';
require_once 'vendor/google/apiclient/src/Google/Service/Calendar.php';
$scopes ="https://www.googleapis.com/auth/calendar.readonly";
$client_id = '';
$Email_address = '';
$key_file_location = '';
$client_secret = "";
$redirect_uri = "";
$key = file_get_contents($key_file_location);
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setAccessType('offline'); // Gets us our refreshtoken
$client->setScopes(array('https://www.googleapis.com/auth/calendar.readonly'));
$cred = new Google_Auth_AssertionCredentials(
$Email_address,
array($scopes),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
$_SESSION['token'] = $client->getAccessToken();
$client->setAccessToken($_SESSION['token']);
}
echo "Token".$_SESSION['token'];
if ($client->getAccessToken()) {
$service = new Google_Service_Calendar($client);
$events = $service->events->listEvents('primary');
while(true) {
foreach ($events->getItems() as $event) {
echo $event->getSummary() . " ==> ";
echo $event->end->dateTime;
echo "<br>";
}
$pageToken = $events->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$events = $service->events->listEvents('primary', $optParams);
} else {
break;
}
}
}
?>
I got token here, but now i want to login in my google calendar without using authentication again and again. Because first time i did it.
Now, can i login in my google account using token?
if yes, then how can i do it?
First time i authenticate the user, for that here is my code.
<?php
session_start();
$client = new Google_Client();
$client->setApplicationName("ABC-APP");
$client->setClientId("");
$client->setClientSecret('');
$client->setRedirectUri('');
$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();
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
}
if ($client->getAccessToken()) {
$service = new Google_Service_Calendar($client);
$event = new Google_Service_Calendar_Event(array(
'summary' => "Myevent",
'location' => "31 Shuijd",
'description' => "Test Descriptionj",
'start' => array(
'dateTime' => "12/1/2016",
'timeZone' => "Asia/Kolkata",
),
'end' => array(
'dateTime' => "12/2/2016",
'timeZone' => "Asia/Kolkata",
),
'recurrence' => array(
'RRULE:FREQ=DAILY;COUNT=2'
),
'attendees' => array(
array('email' => $row['contact_email']),
),
'reminders' => array(
'useDefault' => FALSE,
'overrides' => array(
array('method' => 'email', 'minutes' => 24 * 60),
array('method' => 'popup', 'minutes' => 10),
),
),
));
$event = $service->events->insert("primary", $event);
}
?>
You're headed in a good direction. You just need to refresh your access token when it has expired, using the refresh token received from Google after setting the access type offline. You should have that refresh token saved in the database for each user that grants you offline access, so you can refresh the access token without asking them for permission again.
The code would look something like this:
$client->refreshToken($refreshToken);
$tokens = $client->getAccessToken();
$tokens->refresh_token = $refreshToken; // the refresh token is not returned, so if you're updating the session or database, you should set it manually so you don't lose it
You just need to store access token into session when you login first time
and pass this when you want to create event if require
$session_token = <access token store in session >
if (!$client->getAccessToken()) {
$client->setAccessToken($session_token);
}
Edit :: changes
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
I integrate google calendar with my application successfully. First time, i authenticate successfully and all the events are created on google calendar properly.
->please attach the code when you have created events for the first time