1/30/2012

[php で OAuth を使ってみる:第十回] 4square のチェックインスポットを取得する

4square のチェックインスポットを OAuth を使って取得してみる。
※この情報は 2012 年 1 月現在のものです。仕様が変更される可能性は充分にあるので、ご了承ください。

1. アプリを登録する
OAuth Consumer Registration にアクセスし、アプリの登録を行う。
APPLICATION NAME: アプリ名
APPLICATION WEB SITE: アプリ本体の URL
CALLBACK URL: ユーザによる認証動作後にリダイレクトする URL(「4.」でアップする php)

※全ての情報は登録後でも変更できるので、気楽に。

2. 使うキーを確認する
My OAuth Consumers にある「Client ID」と、「Client Secret」を確認する。これが今後必要となるキー。

3. 認証受け渡し用の php を用意する
下記に必要な事項を埋め、アプリのディレクトリにアップする。
<?php
$consumer_key = 'xxxxxxxxxxxxxxxx'; // 「2.」で確認した「Client ID」
$consumer_secret = 'xxxxxxxxxxxxxxxx'; // 「2.」で確認した「Client Secret」
$callback = 'callback する URL'; // この場合はこの php 本体

if (empty($_GET['code'])) {
// ユーザの認証前、4square にリダイレクトする
  $auth_url = 'https://foursquare.com/oauth2/authenticate?';
  $auth_url .= 'client_id='. $consumer_key;
  $auth_url .= '&response_type=code';
  $auth_url .= '&redirect_uri='. $callback;

  header('Location: '. $auth_url);
} else {
// ユーザの認証後、リダイレクトで帰ってきた後
  $accees_token_url = 'https://foursquare.com/oauth2/access_token?';
  $accees_token_url .= 'client_id='. $consumer_key;
  $accees_token_url .= '&client_secret='. $consumer_secret;
  $accees_token_url .= '&grant_type=authorization_code';
  $accees_token_url .= '&redirect_uri='. $callback;
  $accees_token_url .= '&code='. $_GET['code'];

  $result = json_decode(file_get_contents($accees_token_url), true);
  $access_token = $result['access_token'];

  echo "<script type='text/javascript'>location.href = 'アプリ本体の URL';</script>";
}
?>

4. チェックインスポットを検索して表示する
<?php
// php の文字コードが utf-8 であっても文字化けしたので記載
header('Content-type: application/json; charset=utf-8');

$query = 'モスバーガー'; // 検索語句

$spot_url = 'https://api.foursquare.com/v2/venues/search?';
$spot_url .= 'client_id='. 'xxxxxxxxxxxxxxxx'; // 「2.」で確認した「Client ID」
$spot_url .= '&client_secret='. 'xxxxxxxxxxxxxxxx'; // 「2.」で確認した「Client Secret」
$spot_url .= '&access_token='. 'xxxxxxxxxxxxxxxx'; // 「4.」で取得した access_token
$spot_url .= '&ll=34.985214,135.758593'; // 任意の緯度経度
$spot_url .= '&llAcc=1000'; // 1,000m 四方が対象
$spot_url .= '&limit=20'; // 20 件取得
// スポット名で検索する場合
if ($_COOKIE['query']) $spot_url .= '&query='. urlencode($query); // urlencode しないと取得できない
// 結果は json で返ってくるので、そのまま echo してやる
echo file_get_contents($spot_url);
?>
例えばこの php をアプリ本体の Javascript で読み込み、結果で出た json を Javascript で解析してレイアウト後に表示する、などができる。

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.