简体   繁体   中英

Google Calendar API Insert event without authorization

I need to authorize users on my site to insert an event in our google calendar. It's a booking system, where the user selects a service,confirm, and a new event is inserted automaticly in our calendar. The problem is, i have an authorization button on client's page witch i don't need.

<button id="authorize-button" onclick="handleAuthClick(event)">Authorize</button>

So i think i need a service account authorization. But i don't know how to use generated json and p12 key in javascript. I need a sample or at least to understand what i have to do..

JS code:

var CLIENT_ID = '*********.apps.googleusercontent.com';
var API_KEY = 'AIza***********************';
var SCOPES = ["https://www.googleapis.com/auth/calendar"];

function handleClientLoad() {
  gapi.client.setApiKey(API_KEY);
  window.setTimeout(checkAuth, 1);
}

function checkAuth() {
  gapi.auth.authorize({
    client_id: CLIENT_ID,
    scope: SCOPES,
    immediate: true
  }, handleAuthResult);
}

function handleAuthResult(authResult) {
  var authorizeButton = document.getElementById('authorize-button');
  if (authResult && !authResult.error) {
    authorizeButton.style.visibility = 'hidden';
  } else {
    authorizeButton.style.visibility = '';
    authorizeButton.onclick = handleAuthClick;
  }
}

function handleAuthClick(event) {
  gapi.auth.authorize({
    client_id: CLIENT_ID,
    scope: SCOPES,
    immediate: false
  }, handleAuthResult);
  return false;
}

PS - Site is on php.

Yes, i needed to use service account with php sdk. You download p12 key, upload on server and then:

require_once ('../src/Google/autoload.php');

$client_id = '{your_code}.apps.googleusercontent.com'; //Client ID
$service_account_name = '{your_email}@developer.gserviceaccount.com'; //Email Address
$key_file_location = $_SERVER['DOCUMENT_ROOT'] .'{file}.p12'; //key.p12
$client = new Google_Client(); //AUTHORIZE OBJECTS
$client->setApplicationName("App Name");

//INSTATIATE NEEDED OBJECTS (In this case, for freeBusy query, and Create New Event)
$service = new Google_Service_Calendar($client);
$id = new Google_Service_Calendar_FreeBusyRequestItem($client);
$item = new Google_Service_Calendar_FreeBusyRequest($client);
$event = new Google_Service_Calendar_Event($client);
$startT = new Google_Service_Calendar_EventDateTime($client);
$endT = new Google_Service_Calendar_EventDateTime($client);


if (isset($_SESSION['service_token'])) {
  $client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
    $service_account_name,
    array('https://www.googleapis.com/auth/calendar'),
    $key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();

/************************************************
  MAIN FUNCTIONS
 ************************************************/

function GetFreeBusy($calendar_id, $calendar_date) {
  global $id; //GET OBJECTS FROM OUTSIDE
  global $item;
  global $service;
  $arrayTime = array();
  $id->setId($calendar_id);
  $item->setItems(array($id));
  $item->setTimeZone('Europe/Rome');
  $item->setTimeMax("{$calendar_date}T18:00:00+02:00");
  $item->setTimeMin("{$calendar_date}T08:00:00+02:00");
  $query = $service->freebusy->query($item);

  $start = $query["calendars"][$calendar_id]["busy"];
  $end = $query["calendars"][$calendar_id]["busy"];

  $length = count($start);
  for ($i = 0; $i < $length; $i++) {
    $startTime = $start[$i]["start"];
    $endTime = $start[$i]["end"];

    list($a, $b) = explode('T', $startTime);
    list($startHour, $d) = explode(':00+', $b);
    list($e, $f) = explode('T', $endTime);
    list($endHour, $g) = explode(':00+', $f);
    array_push($arrayTime, array($startHour, $endHour));
    // I CREATED AN ARRAY FOR MY NEEDS ex. [ ["8:00", "10:00"], ["14:00", "14:30"] ]
  }
  return $arrayTime;
}

function CreateEvent($calendarId, $summary, $location, $description, $date, $start, $end) {

  global $service;
  global $event;
  global $startT;
  global $endT;

  $startT->setTimeZone("Europe/Rome");
  $startT->setDateTime($date."T".$start.":00");
  $endT->setTimeZone("Europe/Rome");
  $endT->setDateTime($date."T".$end.":00");

  $event->setSummary($summary);
  $event->setLocation($location);
  $event->setDescription($description);
  $event->setStart($startT);
  $event->setEnd($endT);

if($insert = $service->events->insert($calendarId, $event)) {
  return true;
}

}

You open your calendar, and add share it with {your_email}@developer.gserviceaccount.com. Now, any user can create events to my cal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM