Google+ API をPHPから使ってみる
Google+ APIが一般公開された(Getting Started on the Google+ API - Google+ Developers Blog)のを受けて、PHPでアクセスしてみました。 シンプルなOAuth2のBEARERトークンなのでcurlエクステンションで書いてみても良いのですが、以前作った簡易OAuth2クラスLightOAuth2(Google Code Archive - Long-term storage for Google Code Project Hosting.)を使ってみました。
アクティビティを取得するコードのサンプルを以下に示します。Google APIコンソールでクライアントID、シークレット、コールバックURLを登録して実行します。
デフォルトでは、example_googleplus.phpがファイル名ですが、CALLBACKとあわせて適当に変更してください。
まだ、Google+ APIの種類は少ないようですが、整備が進むといろいろできそうです。
<?php require_once('LightOAuth2.php'); define('CLIENT_ID','<your client id>'); define('CLIENT_SECRET','<your client secret>'); define('SCOPE','https://www.googleapis.com/auth/plus.me'); $entry = array('authorize'=>'https://accounts.google.com/o/oauth2/auth', 'access_token'=>'https://accounts.google.com/o/oauth2/token'); // path for the application script (it should be registered on Google API console) define('CALLBACK','http://www.example.com/example_googleplus.php'); $oauth = new LightOAuth2(CLIENT_ID, CLIENT_SECRET); session_start(); if (!isset($_SESSION['access_token'])) { if (!isset($_GET['code'])) { // get authorization code $opts = array('scope'=>SCOPE); $url = $oauth->getAuthUrl($entry['authorize'], CALLBACK, $opts); header("Location: " . $url); exit(); } // get access token $obj = $oauth->getToken($entry['access_token'], CALLBACK, $_GET['code']); $_SESSION['access_token'] = $obj->access_token; } // access to proteced resource $oauth->setToken($_SESSION['access_token']); $url = "https://www.googleapis.com/plus/v1/people/me/activities/public"; $response = $oauth->fetch($url); $obj = json_decode($response); print_r($obj); ?>