Accessing Graph API

Once you have an instance of the Facebook\Facebook service and obtained an access token, you can begin making calls to the Graph API.

In this example we will send a GET request to the Graph API endpoint /me. The /me endpoint is a special alias to the user node endpoint that references the user or Page making the request.

$fb = new Facebook\Facebook([/* . . . */]);

// Sets the default fallback access token so we don’t have to pass it to each request

$fb->setDefaultAccessToken(‘{access-token}’);

try {

$response = $fb->get(‘/me’);

$userNode = $response->getGraphUser();

} 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;

}

echo ‘Logged in as ‘ . $userNode->getName();

The get() method will return a Facebook\FacebookResponse which is an entity that represents an HTTP response from the Graph API.

To get the response in the form of a nifty collection, we call getGraphUser() which returns a Facebook\GraphNodes\GraphUser entity which represents a user node.

If you don’t care about fancy collections and just want the response as a plain-old array, you can call the getDecodedBody() method on the FacebookResponse entity.

try {

$response = $fb->get(‘/me’);

} catch(Facebook\Exceptions\FacebookSDKException $e) {

// . . .

exit;

}

$plainOldArray = $response->getDecodedBody();

Share this post
[social_warfare]
Authentication and Authorization
Facebook service class – Facebook\Facebook

Get industry recognized certification – Contact us

keyboard_arrow_up