Facebook Graph API 用法 (登入/抓資料)

Graph Explorer:
https://developers.facebook.com/tools/explorer?method=GET&path=me%2F&version=v2.2

Graph API: https://developers.facebook.com/docs/graph-api/reference/v2.6/user/

Token: https://developers.facebook.com/docs/facebook-login/access-tokens

PHP SDK: https://developers.facebook.com/docs/php/gettingstarted

Reference:

Examples:

Get login URL:

$fb = new Facebook\Facebook([
  'app_id' => FB_APP_ID,
  'app_secret' => FB_APP_SECRET
]);

$helper = $fb->getRedirectLoginHelper();
$permissions = ['public_profile', 'email', 'user_friends']; // optional
$fb_login_url = $helper->getLoginUrl(base_url() . 'web/fb_listener/', $permissions);

Login callback:

$fb = new Facebook\Facebook([
  'app_id' => FB_APP_ID,
  'app_secret' => FB_APP_SECRET
]);

$helper = $fb->getRedirectLoginHelper();

//$accessToken = 'EAAFVf3uVJHgBwLF7niee06t8BEzFuvZAiPjgpP0Ugg8AzZCyWwGflpdLVXo96pSkgSPRLpUVsr9ZCa0YPpSjqgldzN9iCNBXpjVqy4szn8pzw63yVobwQ0d6iKrnlrtt88kuNmp1PMZD';
try {
	$accessToken = $helper->getAccessToken();
	//logg($accessToken);

	//Param "locale" is must, or FB could return English value.
	$response = $fb->get('/me?fields=id,name,friends,birthday&locale=zh_TW', $accessToken);
	//getDecodedBody() is very important to parse FB objects.
	$user = $response->getDecodedBody();

	//$response = $fb->get('/me/picture?type=large', $accessToken);
	//$picture = $response->getHeaders();
	//logg($picture['Location']);

	$response = $fb->get('/me/picture?type=large', $accessToken);
	logg($picture['Location']);
} catch(Facebook\Exceptions\FacebookResponseException $ex) {
	// When Facebook returns an error
	echo $ex->getMessage();
	exit();
} catch(Facebook\Exceptions\FacebookSDKException $ex) {
	// When validation fails or other local issues
	echo $ex->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;
}

Note:

  • Need to submit a request to obtain birthday value in Facebook Developer.
  • Birthday value could be null
  • When adding a new permission, the permission name need to be added when building FB login URL
    $permissions = ['public_profile', 'email', 'user_birthday']; // optional

Image 1

Reference:

  1. Extra params:
    https://developers.facebook.com/docs/graph-api/using-graph-api/
  2. Get birthday data
    https://stackoverflow.com/questions/37698073/get-facebook-birthday-through-php-5-0-sdk
  3. Graph Objects Handling
    https://developers.facebook.com/docs/php/GraphObject/5.0.0