Wednesday, April 15, 2009

Google Friend Connect - Capture ID

Find out your members' unique ids (sometimes referred to as userid or user id) in Google Friend Connect. Useful for integrating friend connect into your existing web forms, applications or tracking.

Ever have one of those days where that you think something is going to be really easy and 5 hours later you're ready to pull your hair out?

That's how I felt about Google friend Connect. Don't get me wrong it's extremely easy if you are only playing with the provided gadgets but the developer's section can make you squirm.

Google does a good job of explaining the initial pieces of code you need in your page in order to connect to the API:
http://code.google.com/apis/friendconnect/articles/inpage_integration.html#setup

What Google doesn't give you is a quick example on capturing only the unique userid. Here's the code to make that happen.

Step 1: Paste this in the header section of your webpage


<script src="http://www.google.com/jsapi" type="text/javascript" charset="utf-8"></script>

<script type="text/javascript" charset="utf-8">
google.load('friendconnect', '0.8');
</script>

<script type="text/javascript">
google.friendconnect.container.setParentUrl('/');
google.friendconnect.container.loadOpenSocialApi({
site: 'XXXXXXXXXXXXXXX', // Change this on your site
onload: function() { initAllData(); }
});


function initAllData() {
var req = opensocial.newDataRequest();
req.add(req.newFetchPersonRequest("VIEWER"), "viewer");
req.send(loadData);
}


// load the data using open social
function loadData() {
var req = opensocial.newDataRequest();
req.add(req.newFetchPersonRequest('VIEWER'), 'viewer');
req.send(onLoadCallback);
}


// called after data is loaded
function onLoadCallback(data) {
if(data.get('viewer').getData()) {
var viewer = data.get('viewer').getData();
var name = viewer.getDisplayName();

//The holy grail of code that took me forever to figure out
var userid = viewer.getField( opensocial.Person.Field.ID );

// This code that will update your form field with the userid value. Be sure to change the formname value and the fieldname value to match your form.
document.FORMNAME.FIELDNAME.value = userid;
}
}
</script>



Step 2: Create your form


<form id="FORMNAME" name="FORMNAME" action="http://www.actionhere.com" method="post">
<input size="32" name="FIELDNAME">
<input type="submit" value="Submit">
</form>



Reference Links

Google Friend Connect Website
http://www.google.com/friendconnect

Google Friend Connect API Documentation (Javascript):
http://code.google.com/apis/friendconnect/js_api.html

Supported Open Social Parameters:
http://code.google.com/apis/friendconnect/opensocial_and_gfc.html#VIEWER