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

NOTE: This article is 3 years or older so its information may no longer be relevant. Read on at your own discretion! Comments for this article have automatically been locked, refer to the FAQ for more details.
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

Hope you found this post useful...

...so please read on! I love writing articles that provide beneficial information, tips and examples to my readers. All information on my blog is provided free of charge and I encourage you to share it as you wish. There is a small favour I ask in return however - engage in comments below, provide feedback, and if you see mistakes let me know.

If you want to show additional support and help me pay for web hosting and domain name registration, donations, no matter how small, are always welcome!

Use of any information contained in this blog post/article is subject to this disclaimer.
comments powered by Disqus
Other posts you may like...