Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

This is the second part out of a series of posts showing how to integrate with Facebook. The first part went through the necessary steps of setting up a Facebook app and getting a pre-authenticated token ready. This part will get down to the actual PHP code needed to do the posting.

I would suggest glancing over the part 1 of this post series, however if you already know how to set up an App and get a token, this article should be easy to follow on its own.

So to recap, this is the information that was collected in the first post:
  • Apps ID ($fbappkey)
  • App Secret ($fbappsecret)
  • Page ID ($fbpageid)
  • Access token ($fbaccesstoken_tmp)


The values for these variables should be stored somewhere like a configuration file or a database. Importantly, the access token so far is a temporary 2-hour access token, so it has to be extended and the extended token stored and used subsequently instead of this one.
 Variables
$fbappkey = 'xxx';
$fbappsecret = 'xxx';
$fbpageid = 'xxx';
$fbaccesstoken_tmp = 'xxx';


The temporary access token lasts around 2 hours, this is clearly not feasible to use all the time, but luckily Facebook allows for this token to be extended to a 60 day validity period. Once a token is expired, you need to get a new one, which means going to the Graph API Explorer as shown in the first part of this series.

The code below shows how to get this extended token. Ideally this code should run once every 60 days (or whenever the token expires). In my case I added this code to my blog's configuration screen. The resulting token should be stored along with the other variables above. This is the token that will be used to post to Facebook.
 Extending a temporary token
try {
FacebookSession::setDefaultApplication($fbappkey, $fbappsecret);
$session = new FacebookSession($fbaccesstoken_tmp);
$session = $session->getLongLivedSession();
$fbaccesstoken = $session->getToken();
}
catch (Exception $e) {
// handle any exceptions here, this stops processing as an example
die($e->getMessage());
}




Now that the access token is sorted out, the next thing that should be done is to make sure that the Facebook session we are going to create is valid. If a session is not valid, it means that the token has expired.
 Session Validation
// start and validate session first
try {
FacebookSession::setDefaultApplication($fbappkey, $fbappsecret);
$session = new FacebookSession($fbaccesstoken);
$session->validate();
}
catch (Exception $e) {
// handle any exceptions here, this stops processing as an example
die($e->getMessage());
}


Once the session is validated, a page access token needs to be fetched from Facebook so that the code can post to a Facebook page. A new session is then started with the page token. Using this new session a Facebook request is sent with the content on the post.
 Posting to a Page
// get page access token
$request = new FacebookRequest($session, 'GET', '/' . $fbpageid . '?fields=access_token');
$response = $request->execute();
$result = $response->getGraphObject()->asArray();
$pageToken = $result['access_token'];
// start page session
$pageSession = new FacebookSession($pageToken);
// post to facebook as page
$request = new FacebookRequest(
$pageSession, 'POST', '/' . $fbpageid . '/feed',
array (
'message' => 'This is a cool post',
'link' => 'http://www.example.com/',
'picture' => 'http://www.example.com/postimage.png'
)
);
$response = $request->execute();

Note - as of the 2.9 API version, link preview sub-elements like picture are no longer supported. See this article on how to use an alternative approach to generate link previews correctly: Facebook link previews no longer working when posting via the API - here's how to fix it


The result looks something like this (for the example App I've created in the first part of this article). The posted by information will show your App's name.
fb09.png


Now the last touch is to share the page post to your own feed. This part is optional. The code below creates a separate Facebook post on your behalf, as opposed to posting as a page.

The code is very similar, except the original session is used and the request is a simple link request pointing to the Page post URL.
 Posting to your Feed
// get the post ID
$id = $response->getGraphObject()->getProperty('id');
$postId = substr($id, strrpos($id, '_') + 1); // extract the post ID for linking
// share the page post to user's feed
$request = new FacebookRequest(
$session, 'POST', '/me/feed',
array (
'message' => 'This is a cool post',
'link' => 'http://www.facebook.com/' . $postId
)
);
$request->execute();


That's all there is to it. Of course the code should have exception handling added and there is a bit of extra work to store all of the necessary variables for the App ID, etc.

Soon I will be implementing Google Plus and Tweeter API integrations, so stay tuned.

-i

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.