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.
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.
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.
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.
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.
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.
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.