Created
July 31, 2015 05:37
-
-
Save fddcddhdd/a81ac4ac759ae721ded6 to your computer and use it in GitHub Desktop.
Google Contacts(Gmailのアドレス帳) APIのサンプルコード。その2(アクセストークン取得して、アドレス帳にアクセスする
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// アプリケーション設定 | |
define('CONSUMER_KEY', 'xxxx.apps.googleusercontent.com'); //クライアント ID | |
define('CONSUMER_SECRET', 'password mitaina'); // パスワードみたいなもの | |
define('CALLBACK_URL', 'http://xxx.com/contacts/callback.php'); | |
// URL | |
define('TOKEN_URL', 'https://accounts.google.com/o/oauth2/token'); // アクセストークンを取得するURL | |
define('INFO_URL', 'https://www.google.com/m8/feeds/contacts/default/full'); // Contacts(アドレス帳の)API | |
//-------------------------------------- | |
// アクセストークンの取得 | |
//-------------------------------------- | |
// | |
$request_header = array( | |
"Content-Type: application/x-www-form-urlencoded", | |
); | |
$request_body = array( | |
'code' => $_GET['code'], | |
'grant_type' => 'authorization_code', | |
'redirect_uri' => CALLBACK_URL, | |
'client_id' => CONSUMER_KEY, | |
'client_secret' => CONSUMER_SECRET, | |
); | |
$options = array('http' => array( | |
'method' => 'POST', | |
'header' => implode("\r\n", $request_header), | |
'content' => http_build_query($request_body) | |
)); | |
$res = file_get_contents(TOKEN_URL, false, stream_context_create($options)); | |
// アクセストークンが取得できなかったら終了! | |
$token = json_decode($res, true); | |
if(isset($token['error'])){ | |
echo 'エラー発生'; | |
exit; | |
} | |
$access_token = $token['access_token']; | |
// 自分のアドレス帳一覧を取得&表示する(MAX1000件) | |
$params = array('access_token' => $access_token, | |
'max-results' => 1000 | |
); | |
$url = INFO_URL . '?' . http_build_query($params) ; | |
$res = file_get_contents($url); | |
echo "<pre>".htmlspecialchars($res)."<pre>"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment