Phanix
Phanix

Just writing

使用 PHP 调用 Facebook api

真心觉得Facebook api 的官方文件网站很烂,然后PHP 的api 用法啰哩八唆的,还不如直接在php 里面用curl 来得方便。

Facebook api 透过php 的用法,理想上的流程大致是这样

  1. 先透过登入页面(eg login.php),取得一个token 之后,供call back page (eg 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>';
}

?>

ps Facebook 的php api 在这边,或直接上github

Original link: Phanix's Blog

CC BY-NC-ND 2.0 版权声明

喜欢我的文章吗?
别忘了给点支持与赞赏,让我知道创作的路上有你陪伴。

加载中…

发布评论