Integrating your PHP site with Google Friend Connect and Open Social

Building Your Socialized Site

So Open Social is a promising 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 persistent data and publish notices/alerts called activities. In order to utilize these, you must provide authentication 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

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 , simply execute the following code:

google.friendconnect.renderSignInButton(\{ 'id': 'target-id', 'text' : 'Click here to join ', 'style': 'standard' \});

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.

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.

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);
}

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

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 article: http://www.int6.org/web/integrating-php-site-google-friend-connect-open-social/