Skip to content

Instantly share code, notes, and snippets.

@kejyun
Created December 13, 2012 10:56
Show Gist options
  • Save kejyun/4275706 to your computer and use it in GitHub Desktop.
Save kejyun/4275706 to your computer and use it in GitHub Desktop.
在PHP使用Google API(V3)取得使用者的Gmail通訊錄清單
<?php
function getEmailList($xml = '' , $access_token = '' , &$contact_list = array()) {
if (empty($xml)) {
return false;
}
$doc = new DOMDocument;
$doc->loadXML($xml);
$xpath = new DOMXPath($doc);
$contacts = $xpath->query("//gd:email");
// 撈取email跟姓名
foreach ($contacts as $contact) {
// 使用者編號
$user_id = $contact->parentNode->getElementsByTagName('id')->item(0)->textContent;
$key = sha1($user_id);
$contact_list[$key]['id'] = $user_id;
$contact_list[$key]['email'] = $contact->getAttribute('address');
$contact_list[$key]['user_name'] = $contact->parentNode->getElementsByTagName('title')->item(0)->textContent;
}
// 撈取使用者照片
$entrys = $doc->getElementsByTagName('entry');
foreach ($entrys as $entry) {
// 使用者編號
$user_id = $entry->getElementsByTagName('id')->item(0)->nodeValue;
$key = sha1($user_id);
$links = $entry->getElementsByTagName('link');
foreach ($links as $link) {
if ($link->attributes->getNamedItem("type")->nodeValue=='image/*') {
$contact_list[$key]['photo'] = $link->attributes->getNamedItem("href")->nodeValue.'?access_token='.$access_token;
break;
}
}
}
}
require_once './src/Google_Client.php';
session_start();
$page_info = $contact_list = array();
$client = new Google_Client();
$client->setApplicationName('Google Contacts PHP Sample');
$client->setScopes("https://www.google.com/m8/feeds/contacts/default/full");
// 設定API Key資訊
$client->setClientId('insert_your_oauth2_client_id');
$client->setClientSecret('insert_your_oauth2_client_secret');
$client->setRedirectUri('insert_your_redirect_uri');
$client->setDeveloperKey('insert_your_developer_key');
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
// 如果Session有Token資料,設定為要使用的token
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
// 登出清除taken
unset($_SESSION['token']);
$client->revokeToken();
}
// 取得AccessToken
$access_token_string = $client->getAccessToken();
$access_token_object = json_decode($access_token_string);
// echo $access_token_string;
if ($access_token_string) {
// 如果有Token資料
$req = new Google_HttpRequest("https://www.google.com/m8/feeds/contacts/default/full");
$val = $client->getIo()->authenticatedRequest($req);
$xml_string = $val->getResponseBody();
$doc = new DOMDocument;
$doc->loadXML($xml_string);
$xpath = new DOMXPath($doc);
$xpath->registerNamespace('gd', 'http://schemas.google.com/g/2005');
// 分頁相關資料 : 總資料量
$info = $xpath->query("//openSearch:totalResults");
foreach ($info as $tmp) {
$page_info['totalResults'] = $tmp->nodeValue;
}
// 分頁相關資料 : 起始索引
$info = $xpath->query("//openSearch:startIndex");
foreach ($info as $tmp) {
$page_info['startIndex'] = $tmp->nodeValue;
}
// 分頁相關資料 : 每頁資料量
$info = $xpath->query("//openSearch:itemsPerPage");
foreach ($info as $tmp)
{
$page_info['itemsPerPage'] = $tmp->nodeValue;
}
// 分頁相關資料 : 總頁數
if ($page_info['itemsPerPage'] > 0) {
$page_percent = $page_info['totalResults'] / $page_info['itemsPerPage'];
$page_info['itemsTotalPage'] = ($page_info['totalResults'] % $page_info['itemsPerPage']==0) ? (int)floor($page_percent) : (int)floor($page_percent)+1;
}
else {
$page_info['itemsTotalPage'] = 0;
}
// 取得Gmail通訊錄資訊
if ($page_info['totalResults'] > 0) {
getEmailList($xml_string , $access_token_object->access_token ,$contact_list);
// 若有其他資料,取得所有分頁資料
for ($page=2; $page <= $page_info['itemsTotalPage']; $page++) {
$index = $page_info['itemsPerPage']*($page-1)+1;
$req = new Google_HttpRequest("https://www.google.com/m8/feeds/contacts/default/full?start-index={$index}");
$val = $client->getIo()->authenticatedRequest($req);
$xml_string = $val->getResponseBody();
getEmailList($xml_string , $access_token_object->access_token ,$contact_list);
}
echo '<table border="1px">';
echo "<tr><th>流水號</th><th>姓名</th><th>Email</th></tr>";
$i=1;
foreach ( $contact_list as $contact ) {
echo "<tr><td>{$i}</td><td>{$contact['user_name']}</td><td>{$contact['email']}</td></tr>";
$i++;
}
echo '</table>';
}
else {
echo '沒有任何資料。';
}
// 儲存access_token
$_SESSION['token'] = $client->getAccessToken();
}
else {
// 尚未授權
$auth = $client->createAuthUrl();
}
if (isset($auth)) {
print "<a class=login href='$auth'>Connect Me!</a>";
}
else {
print "<a class=logout href='?logout'>Logout</a>";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment