0

I am explore google calendar api to synchronize user google events with my website events.First I was done with to login with gmail and get permission from user account offline access. My code is

<?php
require_once __DIR__.'/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setAuthConfigFile(__DIR__.'/client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/google4/oauth2callback.php');
$client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setIncludeGrantedScopes(true);
//echo $_GET['access_token'].' '.$_GET['code'];
if (!isset($_GET['code']) && !isset($_SESSION['access_token'])) { //echo "werwe";exit;
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $db = mysql_connect('localhost','root','');
  mysql_select_db('google',$db);
  //echo $_SESSION['refresh_token'];
  $client->refreshToken($_SESSION['refresh_token']);
  $client->authenticate($_GET['code']);
  // $client()->getRefreshToken();
  $_SESSION['access_token'] = $client->getAccessToken();
  //print_r($_SESSION['access_token']);exit;
  //
  $sql = "update google set access_token='".$_SESSION['access_token']['refresh_token']."' WHERE userId = '".$_SESSION['userId']."'";
  mysql_query($sql);
   $_SESSION['refresh_token']=$_SESSION['access_token']['refresh_token'];
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/google4';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>

when user allowed to access their data from api google returns array like

[
  access_token => xxx,
  token_type => bearer,
  created => xxx,
  expires_in => 3600,
  refresh_token => xxx
] 

Using this access token I get the event data, My code is

<?php
require_once __DIR__.'/vendor/autoload.php';
//error_reporting(E_PARSE);
session_start();

$client = new Google_Client();
$client->setAuthConfig(__DIR__.'/client_secrets.json');
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/google4/oauth2callback.php');
$client->setAccessType('offline');
echo "<a href='logout.php'> logout </a>";

if (isset($_SESSION['access_token']) &&           $_SESSION['refresh_token']) {
    $client->refreshToken($_SESSION['refresh_token']);
    $client->setAccessToken($_SESSION['access_token']);
    $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);

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

} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/google4/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

I get event data but when session expire how to get user data ?

what i have to store for that user so I can access the user calendar data offline so the website connect directly to their account, if I have permission for offline access?

how I get data from user calendar every time if session expires using saved user data ?

user3256212
  • 107
  • 5

1 Answers1

1

Google allowed offline access for 60 days (please ensure current policy from google.com) To gain offline access you need to pass following flag with your oAuth request

access_type=offline

Please note following flag is useful when you want to ask offline access user forcefully

approval_prompt=force

So, every time you need to gain access google data you need to request refresh token with previous access token data. You have to save access token data into your database.

  • I am put this in my code but I don't know what data store in my database so I can pass it to google and I get events from user account. – user3256212 Oct 20 '16 at 06:33
  • If do you know about any **demo** code for this please share link with me. – user3256212 Oct 20 '16 at 06:36
  • sorry, code is related with another project so its not shareable. try to get refresh token, you will get access of those data according to scope only. please don't try to get other data that user didn't permit. – Shahadat Hossain Khan Oct 20 '16 at 06:50
  • 1
    Just to add to what this answerd said, check this [SO thread](http://stackoverflow.com/questions/9241213/how-to-refresh-token-with-google-api-client) for addtional code sample. – noogui Oct 20 '16 at 16:11