facebook Graph API - 友達リストの取得 | ベンチャー企業 CIO: 池谷 義則ブログ&経営、ビジネス、プログラミング技術や便利なオープンソースの紹介

ベンチャー企業 CIO: 池谷 義則ブログ&経営、ビジネス、プログラミング技術や便利なオープンソースの紹介

SKYAVY, INC. CIOの池谷義則のブログ & ベンチャー企業 & 経営、ビジネス、プログラミング技術や便利なオープンソースの紹介

facebook の Graph APIを利用して、友達リストの取得をする方法を紹介します。
昨今では、SNSとの連携と利用がウェブサイトを運営する上で非常に重要なファクターな訳で・・・
ログインはもちろんですが、今回はこの機能!

前提条件として、ユーザーのInfiniteAccessTokenはすでに取得済みという感じで進めます。


$this->fbToken = $this->user->getFbInfiniteAccessToken();
$this->friends = array();
if (!empty($this->fbToken)) {
  $fbApiConfigs = sfConfig::get('app_facebook_api');  // get facebook APP keys in array
  $fbConnect = new myFacebookConnect($fbApiConfigs['key'], $fbApiConfigs['secret']);


  // get Japanese name
  $fbDataJP = $fbConnect->graph('me/friends', $this->fbToken, array('id', 'name'), 'ja_JP');


  if (isset($fbDataJP['data'])) {
    // put data into array
    foreach ($fbDataJP['data'] as $v) {
      $data = array(
        'id' => $v['id'],
        'name' => $v['name'],
        'name_ja' => $v['name'],
      );
      $this->friends[$v['id']] = $data;
    }
  }


  // get English name
  $fbDataEn = $fbConnect->graph('me/friends', $this->fbToken, array('id', 'name'), 'en_US');
  if (isset($fbDataEn['data'])) {
    foreach ($fbDataEn['data'] as $v) {
      $this->friends[$v['id']]['name_en'] = $v['name'];
    }
  }


}
名前の取得ですが、日本語名、英語名、その他言語の名前は、その都度リクエストを飛ばさないと取得できないようです・・・ 一回のリクエストで取得できないので、2回飛ばしています。

ここで呼ばれている myFacebookConnect クラスは、こんな感じです。かなり他のfunctionを割愛していますw

class myFacebookConnect {
  protected $api_key    = '';
  protected $api_secret   = '';
  protected $redirect_uri = '';
  
  function __construct($api_key, $api_secret, $callback_url = '') {
    $this->api_key      = $api_key;
    $this->api_secret   = $api_secret;  
    $this->redirect_uri = $callback_url;  
  }


  /**
   * Get info using Facebook Graph
   * 
   * @param $method
   * @param $access_token
   */
  function graph ($method = 'me', $access_token = null, $fields = array( 'id', 'name', 'first_name', 'middle_name', 'last_name', 'gender', 'locale', 'languages', 'link', 'username', 'age_range', 'third_party_id', 'installed', 'timezone', 'updated_time', 'verified', 'bio', 'birthday', 'cover', 'currency', 'id', 'devices', 'education', 'email', 'hometown', 'location', 'favorite_athletes', 'favorite_teams', 'picture', 'quotes', 'website', 'work' ), $locale = 'ja_JP') {
    $graph_url = 'https://graph.facebook.com/'.urlencode($method).'?fields='.urlencode(implode(',',$fields)).'&locale='.$locale.'&width=250&height=250&access_token=' . urlencode($access_token);
    $ch = curl_init($graph_url);
    curl_setopt($ch,CURLOPT_HEADER, false);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch,CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_CAINFO,dirname(__FILE__) . '/fb_ca_chain_bundle.crt');


    $c    = json_decode(curl_exec($ch), true);
    $info   = curl_getinfo($ch);
    
    if ($info['http_code'] !== 200) {
      if (isset($c['error']['message'])) {
        //throw new myFacebookException($c['error']['message']);
        Email::create(null, 'test', 'error', array("text" => $c['error']['message']))->to("error@creww.me")->send();
      }
      else {
        //throw new myFacebookException('Couldn\'t connect to the facebook server. Http code: '.$info['http_code']);
        Email::create(null, 'test', 'error', array("text" => 'Couldn\'t connect to the facebook server. Http code: '.$info['http_code']))->to("error@creww.me")->send();


      }
    }


    return $c;
  }


}

で、結果として今回は、自分の友達リストを取得して、画像・名前表示をして、JavaScriptで名前検索。ボタンクリックで、個別にfacebookメッセージを送れるようにする機能を実装しました。

図1 : 表示画面


図2 : ボタンをクリックすると・・・


今回は、独自のmyFacebookConnectクラスを使っていますが、facebookが提供しているPHPのSDKもあるので、そっちの方がいいかもですw
https://developers.facebook.com/docs/php/gettingstarted/4.0.0

あと、友達リスト取得のfacebookドキュメントはこちらです
https://developers.facebook.com/docs/graph-api/reference/v2.1/user/friends

参考: 
https://developers.facebook.com/docs/php/gettingstarted/4.0.0
https://developers.facebook.com/docs/graph-api/reference/v2.1/user/friends