Can't create an event using google calendar api php - php

I've followed all the instructions, the php quickstart and the events.insert pages by google; but when i run it the consent form pops up I click allow and then nothing happens bar the consent form resetting.If i change the redirect url to another page then it no longer resets the consent form, but still nothing happens.
$client = new Google_Client();
$client->setAuthConfig('redacted');
$client->addScope("https://www.googleapis.com/auth/calendar");
$client->addScope("https://www.googleapis.com/auth/calendar.events");
$client->setRedirectUri('http://redacted/GoogleClientWorksCalendar.php');//this is the current file
$client->setAccessType('offline');
$client->setIncludeGrantedScopes(true);
$client->setPrompt('consent');
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
$service = new Google_Service_Calendar($client);
$event = new Google_Service_Calendar_Event(array(
'summary' => 'test',
'location' => 'somewhere',
'description' => 'test description',
'start' => array(
'dateTime' => '2020-09-03T09:00:00+02:00',
),
'end' => array(
'dateTime' => '2020-09-03T17:00:00+02:00',
),
));
$calendarId = 'redacted';
$results = $service->events->insert($calendarId, $event);
Thank you.

I have resolved my issue. The problem was I had forgotten a part of the google Oauth2.0 code required, which meant I never received the access token.
This snippet below is fully functional. Hope it helps and thank you all for answering.
$client = new Google_Client();
$client->setAuthConfig('redacted');
$client->addScope("https://www.googleapis.com/auth/calendar");
$client->addScope("https://www.googleapis.com/auth/calendar.events");
$client->setRedirectUri('http://redacted/GoogleClientWorksCalendar.php');//this is the current file
$client->setAccessType('offline');
$client->setIncludeGrantedScopes(true);
$client->setPrompt('consent');
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
$client->authenticate($_GET['code']);
$access_token = $client->getAccessToken();
$client->setAccessToken($access_token);
$service = new Google_Service_Calendar($client);
$event = new Google_Service_Calendar_Event(array(
'summary' => 'test',
'location' => 'somewhere',
'description' => 'test description',
'start' => array(
'dateTime' => '2020-09-03T09:00:00+02:00',
),
'end' => array(
'dateTime' => '2020-09-03T17:00:00+02:00',
),
));
$calendarId = 'redacted';
$results = $service->events->insert($calendarId, $event);

Related

Why google Calendar event not being created with stored access token and refresh token in php

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. 😊

Insert event in google calender

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.

How to fix error sending events to google calender using api in php

I am trying to send events to google calender using api from php. but there is some error always with this. cannot understand what to do next. Here is my code:
Fatal error: Uncaught exception 'Google_ServiceException' with message 'Error calling POST https://www.googleapis.com/calendar/v3/calendars/some_calendar#gmail.com/events?key={MY is here}: (401) Login Required' in /home/abcd/public_html/mouthworks/gplus-verifytoken-php-master/google-api-php-client/src/io/Google_REST.php:66 Stack trace: #0 /home/abcd/public_html/mouthworks/gplus-verifytoken-php-master/google-api-php-client/src/io/Google_REST.php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest)) #1 /home/abcd/public_html/mouthworks/gplus-verifytoken-php-master/google-api-php-client/src/service/Google_ServiceResource.php(186): Google_REST::execute(Object(Google_HttpRequest)) #2 /home/abcd/public_html/mouthworks/gplus-verifytoken-php-master/google-api-php-client/src/contrib/Google_CalendarService.php(494): Google_ServiceResource->__call('insert', Array) #3 /home/abcd/public_html/mouthworks/test.php(24): Google_EventsServiceResource->insert('some_calendar#g...', Object(Google_Even in /home/abcd/public_html/mouthworks/gplus-verifytoken-php-master/google-api-php-client/src/io/Google_REST.php on line 66
require_once './gplus-verifytoken-php-master/
google-api-php-client/src/Google_Client.php';
require_once '
./gplus-verifytoken-php-master/
google-api-php- client/src/contrib/Google_CalendarService.php';
session_start();
ob_start();
$client = new Google_Client();
$client->setApplicationName('demo');
$client->
setClientId('client id');
$client->setClientSecret('secret');
$client->setRedirectUri('http://someurl.com');
$client->
setDeveloperKey('dev key');
$cal = new Google_CalendarService($client);
$event = new Google_Event();
$event->setSummary('Pi Day');
$event->setLocation('Math Classroom');
$start = new Google_EventDateTime();
$start->setDateTime('2016-11-14T10:00:00.000-05:00');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime('2016-11-14T10:25:00.000-05:00');
$event->setEnd($end);
// error is on this next line
$createdEvent =
$cal->events->insert('some_calendar#gmail.com',$event);
echo $createdEvent->id;
?>
The first thing I am noticing here is that you are not authenticating your API call and that is why you are getting the error (401) Login Required. You must first authenticate the user to access user data. Please refer to the documentation here https://developers.google.com/api-client-library/php/auth/web-app. After the user is successfully authenticated then you can make the API call.The second thing I notice is that you are putting the email address on the calendar id. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. Your code should look something like this:
session_start();
$client = new Google_Client();
$client->setAuthConfig("client_secrets.json");
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/event.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' => 'Pi Day',
'location' => 'Math Classroom',
'description' => 'Pi History in detail',
'start' => array(
'dateTime' => '2016-11-14T10:00:00-05:00'
),
'end' => array(
'dateTime' => '2016-11-14T10:25:00-05: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'] . '/event.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
I hope you find this information helpful. I also recommend you reading the reference documentation found here https://developers.google.com/google-apps/calendar/v3/reference/events/insert

google calendar api: invalid credentials after 1 hour

Good day. I try to understand google calendar api and I encountered a strange problem then use Oauth2. First time I normal authorization and add event, but after 1 hour (after token expired) I have 401 error (invalid credentials). I refresh the token (use refresh_token), but have 401 error again. New token tested on https://www.googleapis.com/oauth2/v1/tokeninfo and:
{
"issued_to": "***.apps.googleusercontent.com",
"audience": "***.apps.googleusercontent.com",
"scope": "https://www.googleapis.com/auth/calendar",
"expires_in": 3581,
"access_type": "offline"
}
but I have 401 error then I try insert event.
It continues 1 day. For the next day I get the new token and it work for 1 hour again.
My test code:
require_once 'google-php-api/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('client_secret***.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope(Google_Service_Calendar::CALENDAR);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
if ($_GET['logout'] == "1") {
session_unset();
} else {
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
if ($client->isAccessTokenExpired()) {
$oldToken = json_decode(file_get_contents("token.json"));
$client->refreshToken($oldToken->refresh_token);
$newAccessToken = $client->getAccessToken();
$newAccessToken['refresh_token'] = $refreshToken;
$_SESSION['access_token'] = $newAccessToken;
$client->setAccessToken($_SESSION['access_token']);
} else {
file_put_contents("token.json", json_encode($_SESSION['access_token']));
}
print_r($_SESSION['access_token']);
$service = new Google_Service_Calendar($client);
$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' => '2016-10-06T10:13:00.000',
'timeZone' => 'GMT +03:00',
),
'end' => array(
'dateTime' => '2016-10-06T10:15:00.000',
'timeZone' => 'GMT +03:00',
),
'attendees' => array(
array(
'email' => 'sbakul77#gmail.com',
'resource' => true
),
),
"creator"=> array(
"email" => "email#example.com",
"displayName" => "Example",
"self"=> true
),
"guestsCanInviteOthers" => false,
"guestsCanModify" => false,
"guestsCanSeeOtherGuests" => false,
));
$calendarId = '**#gmail.com';
$event = $service->events->insert($calendarId, $event);
printf('Event created: %s, Event id: %s', $event->htmlLink, $event->id);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
Why is this happening? And why my refreshing token is "invalid credentials"?

Login to google calendar using token only

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

Categories