Skip to main content

Implementation of Facebook Graph API in Coldfusion

Facebook has launched a new FB API called Graph that simplifies FB applications development, the new Graph API allows website owners to create Single Sign On (SSO) with Facebook and allow websites owners to be able to import a lot of users information but after their permissions.


The code below written in Coldfusion gives an example on how to Create FB login/logout button and then how to retrieve the created cookie, and use it for further development:
 
  <body>
  <cfoutput>
    <!--- Your FB application IDS --->
    <cfset api_key = "XXXXXXXXXXXXX"/>
    <cfset secret_key = "XXXXXXXXXXXXXX"/>
    <cfset appID = "XXXXXXXXXXXXXX"/>
    <!--- Facebook login/logout button --->
    <p><fb:login-button perms="email,user_birthday" autologoutlink="true"></fb:login-button></p>
    <!--- Facebook login/logout button that publishes to your wall--->
    <p><fb:like></fb:like></p>
    <!--- Facebook script that connects your site to facebook and creates the needed cookies after authentication --->
    <div id="fb-root"></div>
    <script>
      window.fbAsyncInit = function() {
        FB.init({appId: '#appID#', status: true, cookie: true,
                 xfbml: true});
      };
      (function() {
        var e = document.createElement('script');
        e.type = 'text/javascript';
        e.src = document.location.protocol +
          '//connect.facebook.net/en_GB/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
      }());
    </script>
    <!--- End Facebook script that connects your site to facebook and creates the needed cookies after authentication. Now a cookie is created with a name that starts with fbs_ApplicationID --->

    <!--- Function that extracts User ID and access token from FB cookie. Both access_token and user id are needed to extract information related to the user from FaceBook Graph API --->
    <cffunction name="get_facebook_cookie" access="public" output="true" returntype="any">
        <cfargument name="app_id" type="string" required="true">
        <cfargument name="application_secret" type="string" required="true">
        <cfargument name="charToFind" type="string" required="true">
        <cfargument name="chatToRemoveFront" type="string" required="true">
        <cfargument name="chatToRemoveEnd" type="string" required="true">
        <cfset args=arrayNew(1)>
        <cftry>
        <cfset x=StructFind(cookie, trim('fbs_'&'#app_id#'))>
        <cfset args=listtoarray(x,'&')>
        <cfloop from="1" to="#arrayLen(args)#" index="i">
            <cfif FindNoCase("#charToFind#",args[i])>
                <cfset rvalue=#right(args[i],(len(""&args[i])-chatToRemoveFront))#>
                <cfset rvalue=#left(rvalue,(len(""&rvalue)-chatToRemoveEnd))#>
                <cfreturn rvalue />
            </cfif>
        </cfloop>
        <cfcatch type="any">
        <cfreturn 0 />
        </cfcatch>
        </cftry>
    </cffunction>

    <cfset uid=get_facebook_cookie(appID,secret_key,"uid=",4,1)>
    <cfset access_token=get_facebook_cookie(appID,secret_key,"access_token=",14,0)>
    <!--- Get FB User Profile. Profile Information allowed by the user are stored in a struct after deserialized from JSON --->
    <cfhttp url="https://graph.facebook.com/me?access_token=#access_token#&id=#uid#" result="profile"/>
    <cfif IsJSON(profile.filecontent)>
        <cfset prof=DeserializeJSON(profile.filecontent)>
        <cfdump var="#prof#">
    </cfif>
    <!--- Get FB User Friends.
Friends Information allowed by the user are stored in a struct after deserialized from JSON--->
    <cfhttp url="https://graph.facebook.com/me/friends?access_token=#access_token#&id=#uid#" result="friends"/>
    <cfif IsJSON(friends.filecontent)>
        <cfset friendsl=DeserializeJSON(friends.filecontent)>
        <cfdump var="#friendsl#">
    </cfif>

</cfoutput>
  </body>

Comments

  1. Thanks this is great, however I am getting the following error:

    Error validating application.
    OAuthException

    Any suggestions?

    ReplyDelete
  2. What's weird is that if I use this code to generate the token, and then manually lookup this url in my browser, it works...but ONLY if i have TWO (2) question marks in there,.. strange!!!

    https://graph.facebook.com/<>??access_token=<>

    ^This works in the browser but WONT work via cfhttp!!

    How is that possible?

    ReplyDelete
  3. aha, i was able to get it working by changing a few settings:





    the numbers you were using to measure the strings were off by 1 on each variable!

    ReplyDelete
  4. For the Anonymous, this error means that the cookie does not exist on your webserver anymore, you have to refresh the page to recreate the cookie. To sort out this create an exception handling and in the catch refresh the page.

    ReplyDelete
  5. Great Dental, what is the browser your using?

    ReplyDelete
  6. I got it to work and created an open source project based on your work: http://facebookgraph.riaforge.org/

    ReplyDelete
  7. Yes I noticed that. Thank you Great Job. Actually I tested my code on firefox and explorer and it is working, i needs minor enhancement to check if the cookie exists, also I will add some lines for publishing on wall. Let us try to collaborate on this. Have u tested the code on chrome?

    ReplyDelete
  8. Sounds good, send me your email via this conect form:

    http://www.greatdentalwebsites.com/Contact-Us

    We can then discuss further collaboration on development.

    ReplyDelete
  9. With me both worked, what version of explorer you used?

    ReplyDelete
  10. struct error:

    message Error processing access token.
    type OAuthException

    i can see buttons login and like, but after that show the error

    ReplyDelete
  11. Create exception handling cftry to catch the exception when the user is not authenticated, if you want me to do it for you let me know.

    ReplyDelete
  12. This is a great help, thanks for posting it. It did not work for me as well but all I had to do was remove the "me" part of the first CFHTTP url and the "me/" part of the second CFHTTP url.

    Do you know did the API change or is there some functionality of the "me" part of the URL that I am missing?

    Thanks again for posting.

    ReplyDelete
  13. I have tested the code before I published it, "me" directs graph API to publish to your wall. Anyway there is a newer post that has a full example on how to publish to your wall and to your friends walls as well. Thank you for your feedback.

    ReplyDelete
  14. I'm getting:

    Security: The requested template has been denied access to createobject(java)

    Seems to happen upon outputting the results of the cfhttp request

    I get the access token and id with no problem but when its sent over using cfhttp it seems not to authenticate.

    ReplyDelete
  15. Omar,

    Please try to use the example in the below URL it is newer and 100% working:

    http://blog.abusalah.info/2010/08/coldfusion-facebook-graph-api-publish.html

    ReplyDelete
  16. Jesus MORE old FB code that doesn't work. I'm wondering exactly what the problem is. Does Facebook just make changes so fast that nobody can keep up? Is the API so delicate that code working on one server needs major mystery tweaking so that it will work on a second? Where did the FB "API Key" go? Can't find it on Facebook Developer page although there is a hint that it's the same thing as the APP ID except it never works either.

    Hasn't ANYONE got a nice stable implementation of the Facebook API in Coldfusion?

    ReplyDelete
  17. Please identify what your problem is? did you try to implement the code and it did not work? as I can see you were not able to find the API keys, if this is the case, please search FB to find the keys. If the code is not working please send me the error your getting.

    I'm sharing my code for free and it was tested and worked on different browsers.

    ReplyDelete
  18. first and second cfhttp calls should be https://graph.facebook.com/#uid# AND https://graph.facebook.com/#uid#/friends?access_token=#access_token# respectively

    ReplyDelete
  19. this is very good and running nice.

    ReplyDelete

Post a Comment

Popular posts from this blog

Error: Write to Disk Access Denied - Troubleshooting - BitTorrent

I have downloaded Bit Torrent software and when trying to download I got an error after few seconds saying:

Error: Write to Disk Access Denied
Solving this problem is so simple:
Shut down BitTorrent program.
Go to Start and in the small search box on top of windows start button start typing Bittorrent and the program will show, right click with the mouse on the icon and Run as Administrator.
All ur problems are sorted out now and you can enjoy downloading...
Good Luck.

Importing SSL certs to Coldfusion Railo's keystore

If you are having the below error:
Railo 3.3.4.003 Error (javax.net.ssl.SSLHandshakeException)Messagesun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested targetCausejavax.net.ssl.SSLHandshakeException

This means you are trying to invoke an https webservice. to invoke an SSL webserver you need to import the certificate into Railo by using keytool command. Below are the steps on how to do this:

1- use fire fox to open the webservice and click on the padlock as shown on the below image:

2-Click on more information as below:
 3- Click on View Certificate as below:
4-Click on details as below:
 5- Now export the certificate and save it to your computer with .cer extension.

6- Search in railo folder for the keytool command location, in my case it was under railo\jdk\bin

7-  Search in railo folder for the cacerts location, in my case it was under railo\lib\railo-s…

Publish to Wordpress using JSON API plugin and Coldfusion

I was using Postie to automatically publish to wordpress blog. I was searching a better method of publishing using soap api or json api. I found an excellent json plugin that can be used to publish posts and comments to wordpress.
Please follow the below step by step, this code will let you publish automatically for froma different interface to wordpress rather than using postie or email.

Step one: Install json plugin, enable the plugin and then go to settings > JSON API and  activate post

Step two: you have to modify the file: yourwordpressdirectory/wp-content/plugins/json-api/controllers/post.php

Please replace the file content with the below or add the missing Authenticate method. This method is necessary to authenticate a user to wordpress to be able to post content without a valid session.


<?php /* Controller name: Posts Controller description: Data manipulation methods for posts */ classJSON_API_Posts_Controller{ publicfunctioncreate_post(){ global$json_api; $this->authenticate()…