• Home
  • New Entries
  • Popular Entries
  • Submit a Story
  • About

Integrating your PHP site with Google Friend Connect and Open Social ...

I’ve been working on integrating PHP with Google Friend Connect and Open Social for a few days for one of my Kohana based projects. Although there are plenty of documentation around, there is no PHP example around. So i’ve hacked on my own and decided to publish it on my blog to help the others.

So Open Social is a promosing platform.  There are lots of containers these days and number is increasing every day. If you decided to cook your own Open Social powered platform or integrate into your existing project, please continue reading on.

It should be noted that Open Social is not just gadgets and widgets for your web project. With Open Social, your project can be a container or can store persistant data and publish notices/alerts called activities. In order to utilize these, you must provide authenticatio to your users. You can just go and code it yourself. But, it was the web2.0 way.

Now with web2.5, thanks to Google Friend Connect (so the OpenAuth and maybe the Facebook Friend Connect),  the authentication process is also centralized now. Users already struggle with user/pass combination for most sites they’re visiting.  We don’t want to add another to the list, we can just use the GFC as our authentication provider.

So, if we summarize up:

    * We want a platform based on/powered by Open Social
    * To utilize the Open Social at maximum, we need an authentication system
    * For authenticating, instead of cooking our own, we’ll implement the GFC which supports Open Social

So everything seems okay, as there are documentation for related parties around. The problem is that, especially for the GFC part, PHP documentation and examples are so poor or even does not exists. So in this post, you can see a sample how i cooked these together. It should be noted that i use Kohana as the base framework but i’ll try to clean the Kohana related code from the examples.

Step 1 - Create a login page and put GFC login button

We should let the users to login the site, so we should put a login button.  The GFC documentation about login button states;

    Users of your site need a way to sign into Friend Connect, but since they won’t be sharing their Friend Connect password with your site, the interface will be a little different from a standard login username and password form. Create a link that will open a new window to the Friend Connect authentication page by using the following code:

    <a href="#" onclick="google.friendconnect.requestSignIn();">Sign in</a>

    Friend Connect can also dynamically generate a login button for you to use. To render a button that looks like example of a sign in button, simply execute the following code:

    google.friendconnect.renderSignInButton({ id: arget-id, ext : Click here to join , istyle: istandard });

First of all, we should register our site over GFC.  When the registration is complete, goto  Member’s Gadgets tab and generate the code for gadget.  The code should have a line with site id. Note your site ID to somewhere as we’ll use it for more than once.

    site: ‘XXXXXXXXXXXXXXXXXXXX’

Now first we should create a div to render the login button.

    <div id=”gfc_login”></div>

We should also init the google friend connect on our site

    <script type=”text/javascript” src=”http://www.google.com/jsapi”></script><!– Load the Google AJAX API Loader –>
    <script type=”text/javascript”> <!– Load the Google Friend Connect javascript library. –>
    google.load(’friendconnect’, ‘0.8′);
    </script>
    <script type=”text/javascript”> <!– Initialize the Google Friend Connect OpenSocial API. –>
    google.friendconnect.container.setParentUrl(’/’ /* location of rpc_relay.html and canvas.html */);
    google.friendconnect.container.initOpenSocialApi({
    site: ‘XXXXXXXXXXXXXXXXXXXX’, /* put here your site ID */
    onload: function(securityToken) {
    if (!window.timesloaded) {
    window.timesloaded = 1;
    } else {
    window.timesloaded++;
    }
    if (window.timesloaded > 1) { /* on the second reload redirect to profile page */
    window.top.location.href = “/profile”;
    }
    }
    });
    </script>

The GFC button refreshs the container page after logging in so that, the onload function counts the refreshes. Using that count, it redirects user to profile page on our site after a succesful login.

Finally we put the GFC login button on the page.

<script type=”text/javascript”>
google.friendconnect.renderSignInButton({ ‘id’: ‘gfc_login’, ‘text’ : ‘Login ‘, ’style’: ‘long’ });
</script>

Now when a user logins using the button, the site will redirect the users browser to profile page.



Step 2 - Login Continued - PHP Part

The user is logged in now using GFC but our server-side code is still not aware of it.  As the login page redirects to profile, we should programmaticly check it in our profile page so that our server-side code will be also aware of it.

So very first thing we have to do in profile page is check if the user is logged in. GFC puts a authentication cookie on the system when a user logs in so we should check it our server side code.

    function user_logged_in()
    {
    $fc_cookie_id=”fcauthXXXXXXXXXXXXXXXXXXXX”;
    if(isset($_COOKIE[$fc_cookie_id])) // if there exists the friend connect cookie
    {
    $this->session->set(’logged_in’,TRUE); // set session variable
    $this->session->set(’fcauth’,$_COOKIE[$fc_cookie_id]);
    return true;
    }
    else
    return false;
    }

$fc_cookie_id is the name of the GFC cookie thats on the system. Note that the name uses our site ID.
So we check for the cookie and if we find it, that means GFC logged the user in. There we should have some session stuff for easy future access. Also we set a session variable called fcauth, which will contain the value of the GFC cookie. We’ll use this value when we make REST based requests to Open Social on behalf of the logged in user. (Please note that $this->session() is call to Kohana PHP frameworks Session Library. You can just use $_SESSION[] if you’re not working with Kohana.

So when you call the user_logged_in() function in your profile page, it’ll check for a fcauth cookie. If it found it’ll read the fcauth token to session and return True. If not it’ll return a False value.

Before proceeding on the Open Social part, let’s put some options for users; invite-friends, settings and logout. These options utilize the GFC API so in our profile page we should also initialize the GFC.

    <script type=”text/javascript” src=”http://www.google.com/jsapi”></script><!– Load the Google AJAX API Loader –>
    <script type=”text/javascript”> <!– Load the Google Friend Connect javascript library. –>
    google.load(’friendconnect’, ‘0.8′);
    </script>
    <script type=”text/javascript”> <!– Initialize the Google Friend Connect OpenSocial API. –>
    google.friendconnect.container.setParentUrl(’/’ /* location of rpc_relay.html and canvas.html */);
    google.friendconnect.container.initOpenSocialApi({
    site: ‘XXXXXXXXXXXXXXXXXXXX’, /* put your site ID here */
    onload: function(securityToken){
    }
    });
    </script>

Then, just put these links on the profile page.

    <a href=”#” onclick=”google.friendconnect.requestSettings();”>Settings</a>
    <a href=”#” onclick=”google.friendconnect.requestInvite();”>Invite</a>
    <a href=”/logout”>Logout</a>

The settings and invite options will automaticly will be handled by GFC. But for logout we must provide the code as we’ve sessions for the authenticated user. As our logout link redirects the user to logout page let’s check it out.

In the logout page, we should clear any sessions for the user.

    $this->session->set(’logged_in’,FALSE);

Then to page should also include the GFC logout script.

    <script type=”text/javascript” src=”http://www.google.com/jsapi”></script><!– Load the Google AJAX API Loader –>
    <script type=”text/javascript”> <!– Load the Google Friend Connect javascript library. –>
    google.load(’friendconnect’, ‘0.8′);
    </script>
    <script type=”text/javascript”> <!– Initialize the Google Friend Connect OpenSocial API. –>
    google.friendconnect.container.setParentUrl(’/’ /* location of rpc_relay.html and canvas.html */);
    google.friendconnect.container.loadOpenSocialApi({
    site: ‘XXXXXXXXXXXXXXXXXXXX’, /* put your site ID here */
    onload: function(securityToken) {
    if (!window.timesloaded) {
    window.timesloaded = 1;
    google.friendconnect.requestSignOut();
    } else {
    window.timesloaded++;
    }
    if (window.timesloaded > 1) {
    window.top.location.href = “/”;
    }
    }
    });
    </script>

Similar to login, the script will refresh the page after the user logouts. So we count the refreshes and then redirect the user to our index page.

Step 3 - Putting Open Social in


Now our user can sign in and out and even can invite friends and change the settings on our profile page. As we’ve completed the authentication part we can move on embedding Open Social APIs. The Open Social RESTful API’s allows us to use fcauth cookies when making requests about user information.  Remember that we’ve already stored that data in a session variable called fcauth and we’ll use that value when making our requests.

So here’s an example request that we’ll return users information - whom was logged in using GFC.

    $response=$this->make_request(”http://www.google.com/friendconnect/api/people/@viewer/@self?fcauth=” . $_SESSION["fcauth"]);

You should note that parametere fcauth that we provide with the value stored on the session variable. Now let’s see our make request function which is basicly utilizes the CURL to making a RESTful call.

    private function make_request($url)
    {
    $timeout=5;
    $max_retries=5;
    $useragent = “Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11″;
    $curl=curl_init();
    curl_setopt ( $curl, CURLOPT_URL,$url);
    curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $curl, CURLOPT_CONNECTTIMEOUT, $timeout );
    curl_setopt ( $curl, CURLOPT_USERAGENT, $useragent );
    $retry=0;
    $data=”";
    while($data==”" AND $retry < $max_retries)
    {
    $data=curl_exec($curl);
    $retry++;
    }
    curl_close($curl);

    // response will be in json format, decode it and return
    return json_decode($data);
    }

The response will in JSON format, which is lot easier than to process XML. We just call json_decode on the data and we’ll have the repsonse data as an object.

So the response will be similar to this:
opensocial response



Now with few changes, your own Google Friend Connect + Open Social based PHP application is ready. This is just getting started part as you must utilize the Open Social API for building your socialized platform.

 Original Source:
http://www.regularsexpressions.com/devel/integrating-php-site-google-friend-connect-open-social/

AddThis Social Bookmark Button

Posted at 01:04:09 pm | Permalink | Posted in PHP  Google  

Related Stuff

  • MooV: Using cutting edge Video phones and Software Video Phones - coupling all that with VoIP and empowering the disabled.

  • Moo Telecom: VoIP communications made easy - Ring anyway with the fun and ease of using a normal phone

  • TagR:Mobile Social Network with Real Time Locations Based services, and Ambience Intelligence, VoiP, IM, Skype, Googletalk, Mapping, Flickr, Events, Calendaring, Scheduling, SecondLife Support

  • ClearSMS : ClearSMS is a Web-based application that lets you send bulk SMS messages to your customers, contacts, or just about anyone.

  • Jajah:jah is a VoIP (Voice over IP) provider, founded by Austrians Roman Scharf and Daniel Mattes in 2005[1]. The Jajah headquarters are located in Mountain View, CA, USA, and Luxembourg. Jajah maintains a development centre in Israel.

  • Skype: It’s free to download and free to call other people on Skype. Skype the number one voice over ip software

  • PrivatePhone: a free local phone number with voicemail and messages you can check online or from any phone.

Top Stuff

MessengerFX

e-messenger

ILoveIM

Top 20 Ruby CMS

eBuddy

MSN Web Messenger



About Ajaxlines

Ajaxlines is a project focused on providing its audience with a database of most of Ajax related articles, resources, tutorials and services from around the world.

Its purpose is to showcase the power of Ajax and to act as a portal to the Ajax development community.


Search


Topics

  • .Net (162)
  • Ajax (82)
  • Ajax Games (10)
  • Articles (95)
  • Bookmarking (35)
  • Calendar (20)
  • Chat (45)
  • ColdFusion (3)
  • CSS (75)
  • Email (23)
  • Facebook (83)
  • Flash (19)
  • Google (54)
  • Html (27)
  • Image (11)
  • International Calls & VOIP (7)
  • Java (54)
  • Javascript (265)
  • jQuery (159)
  • JSON (61)
  • Perl (2)
  • PHP (156)
  • Presentation (19)
  • Python (3)
  • Resources (2)
  • RSS (8)
  • Ruby (29)
  • Storage (4)
  • Toolkits (103)
  • Tutorials (217)
  • UI (11)
  • Utilities (174)
  • Web2.0 (18)
  • XmlHttpRequest (28)
  • YUI (12)

© 2006 www.ajaxlines.com. All Rights Reserved. Powered by IRange