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
    Replies
    1. the same error : Invalid token
      Did you solve the problem?

      Delete
  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

Top Google Adsense Alternatives

Google Adsense is a web tool that allows publishers in the Google Network of content sites to automatically serve text, image, video, and rich media adverts that are targeted to site content and audience. These adverts are administered, sorted, and maintained by Google, and they can generate revenue on either a per-click or per-impression basis.  Google servers advertisers using google adwords platform, while adsense is the publishers platform. Google Adsense is the top Ad Publishers platform over the web ranking number one in web advertising industry. Adsense offers contextual advertisements that covers web sites, blogs, games, videos, mobile browsing etc. What made Google Adsense no. 1 is the reliability, stability, variety of services and large number of publishers including google it self. Also google has a fair platform that detects invalid clicks so google successfully protects its advertisers and also offers its best publishers top CPC. Two reasons are behind people think

The Semantic Web

Semantic Web aims to create a meaning and define inter-relationship for information available on the web In the early stages of the World Wide Web (web) it was necessary to develop standards to view web content (HTML language) and to create communication channels (N-Tier applications, email, ftp, etc.). As the web started to be the world’s largest knowledge base, accessible world wide, it became important to develop tools to transfer knowledge between cultures. However, it is still not possible for applications and agents to interoperate with other applications and agents without having a predefined, human created common framework of the meaning of the information being transferred on both sides. Semantic Web (SW) alleviates this problem by providing a common framework that allows data to be shared and reused across application, enterprise, and community boundaries [W3C Semantic Web, 2019]. A clear example on SW application is schema.org. Google, Bing, Yahoo use schema

Arabs In London

I was not able to watch Arabs in London episodes during the last holy month of Ramadan. I watched it recently on MBC. I was really impressed by the performance of some actors and actresses. The most impressive one was Mais Hamdan who was able to present the Palestinian accent efficiently. This TV series was written and directed by Anwar Qawadri a Syrian director who studied and lived in London. The below video is about 8 minutes show when Sami finds out that his friend Eddy (Adnan) passed away.