Using PHP to invoke Facebook api

真心覺得 Facebook api 的官方文件網站很爛,然後 PHP 的 api 用法囉哩八唆的,還不如直接在 php 裡面用 curl 來得方便。

Facebook api 透過 php 的用法,理想上的流程大致是這樣

  1. 先透過登入頁面(e.g. login.php),取得一個 token 之後,供 call back page (e.g. fb-callback.php)用
  2. 當每次 token 被使用後,回傳的資料內會有下次該使用的 token,並將原 token expire

登入授權

<?php
session_start();

require_once('PATH_TO_AUTOLOAD.PHP');

$fb = new Facebook\Facebook([
	'app_id' => 'APP_ID',
	'app_secret' => 'APP_SECRET',
	'default_graph_version' => 'v2.8'
	]);

$helper = $fb->getRedirectLoginHelper();
$permissions = ['email', 'publish_actions', 'user_friends'];  //permissions want to use

$loginUrl = $helper->getLoginUrl('http://www.example.com/fb-callback.php', $permissions);  //call back url
echo '<a href="' . htmlspecialchars($loginUrl) . '">Log in with Facebook!</a>';
?>

Call back 處理,拿到 token 做事情,下面例子是用 curl 取得朋友清單(taggable friends)

<?php
session_start();

require_once('PATH_TO_AUTOLOAD.PHP');

$fb = new Facebook\Facebook([
	'app_id' => 'APP_ID',
	'app_secret' => 'APP_SECRET',
	'default_graph_version' => 'v2.8'
	]);

$helper = $fb->getRedirectLoginHelper();

try 
{
	$accessToken = $helper->getAccessToken();
} 
catch (Facebook\Exceptions\FacebookResponseException $e) 
{
	// When Graph returns an error
	echo 'Graph returned an error: ' . $e->getMessage();
	exit;
} 
catch(Facebook\Exceptions\FacebookSDKException $e) 
{
	// When validation fails or other local issues
	echo 'Facebook SDK returned an error: ' . $e->getMessage();
	exit;
}

if (!isset($accessToken)) 
{
	if ($helper->getError()) 
	{
		header('HTTP/1.0 401 Unauthorized');
		echo "Error: " . $helper->getError() . "\n";
		echo "Error Code: " . $helper->getErrorCode() . "\n";
		echo "Error Reason: " . $helper->getErrorReason() . "\n";
		echo "Error Description: " . $helper->getErrorDescription() . "\n";
	}
	else
	{
		header('HTTP/1.0 400 Bad Request');
		echo 'Bad request';
	}
	exit;
}

// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();

$url = "https://graph.facebook.com/v2.8/me/taggable_friends?fields=name,picture&limit=5&access_token=" . (string)$accessToken;
$headers = array("Content-type: application/json");
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko");

$st = curl_exec($ch);
$result = json_decode($st, TRUE);

foreach ($result['data'] as $friend) {
	echo '<center><img src="' . $friend['picture']['data']['url'] . '"><br>' . $friend['name'] . '</center><br>';
}

?>

p.s. Facebook 的 php api 在這邊,或直接上 github

Leave a Reply

Your email address will not be published. Required fields are marked *