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:

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="" type="text/javascript" charset="utf-8"></script>

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

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

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

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

// 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;

Step 2: Create your form

<form id="FORMNAME" name="FORMNAME" action="" method="post">
<input size="32" name="FIELDNAME">
<input type="submit" value="Submit">

Reference Links

Google Friend Connect Website

Google Friend Connect API Documentation (Javascript):

Supported Open Social Parameters: