本文寫於2014/ 10/22,文中所有的連接和文檔的狀態都是以這個時間點爲準。截止到這個時間點,google developer中的文檔還是老版的,和新版代碼是衝突的。
google api php代碼地址 (Beta 版本) :https://github.com/google/google-api-php-client
google calendar api文檔地址(文檔還沒有更新): https://developers.google.com/google-apps/calendar/
1. 首先了解一下google api
google api是一套公共的訪問接口,通過這套接口,我們能夠訪問google的一些數據。通常情況下我們需要首先註冊一個Google developer的賬戶。這裏將忽略註冊的部分。
想要訪問api,主要有兩種方法:通過REST接口,通過client library (針對每一種語言,google提供的一套類庫),在這篇文章中我們將要講解的是php語言的client library方式。
2. google api的驗證
想要通過google api的獲取一些數據。我們首先需要通過google的驗證,google提供了兩種authentication的方式:
1. 通過一個developer key 來訪問。這種方式簡單的說就是在訪問一些google的公共接口的時候(例如google book 裏面查找一個作者的所有書籍),我們通過給google 提供我們的developer key,google 就能夠允許我們訪問這套api。
雖然這種方法很簡單,但是我們不能訪問用戶的信息。比如你想訪問自己的google日曆裏面的內容,這種方式就不可以了。
2. 通過OAuth2.0來進行用戶驗證
OAuth 2.0是現在比較好的驗證框架,這裏不做贅述。通過OAuth2.0驗證我們通常情況下會遇到兩種情況:client-to-server 和 server-to-server
a. client-to-server
這種情況是用戶通過頁面來授權,是的程序能夠訪問某個人的信息。比如,我們想做一個通過第三方登陸,我們就可以按照這種方式來完成。這種方式要求每次用戶都要授權給程序,程序才能訪問某個用戶的信息。
b. server-to-server
但是對於一些客戶端程序,我們不可能通過上一種方式,每次都給授權,所以這有了server-to-server這種驗證的方式。本文的代碼主要是這種方式,通過這種方式來訪問某一個用戶google日曆:
b.1: 創建一個service account, 得到 client_id , Email_address, key_file
b.2: 將用戶的日曆share給之前創建的那個service account,並且拿到這個日曆的 calendar_id
b.3: 通過代碼來獲取這個calendar的信息
<?php
session_start ();
require_once 'google-api-php-client/src/Google/Client.php';
require_once 'google-api-php-client/src/Google/Service/Calendar.php';
$client_id = '1039242859127-jvdeilpms8kp84lpsfo5n5jdm9kdrr1e.apps.googleusercontent.com'; //Client ID
$Email_address = '1039242859127-jvdeilpms8kp84lpsfo5n5jdm9kdrr1e@developer.gserviceaccount.com'; //Email Address
$key_file_location = 'qingscal-dda622e5a217.p12';
$calendar_id = '[email protected]';
$client = new Google_Client ();
$client->setApplicationName ( "Client_Library_Examples" );
$key = file_get_contents ( $key_file_location );
$scope = array('https://www.googleapis.com/auth/calendar');
$cred = new Google_Auth_AssertionCredentials ( $Email_address, $scope, $key );
$client->setAssertionCredentials ( $cred );
if ($client->getAuth ()->isAccessTokenExpired ()) {
$client->getAuth ()->refreshTokenWithAssertion ( $cred );
}
$service = new Google_Service_Calendar($client);
// 得到所有這個service account 被share的日曆
$calList = $service->calendarList->listCalendarList();
print_r($service->events->listEvents());
?>
參考文檔: https://groups.google.com/forum/#!searchin/google-calendar-api/service$20account$20$20calendar/google-calendar-api/W3I8E49wuCU/ksI29R6NuDsJ