You are on page 1of 7

Games and Game Platform : OpenSocial JavaScript Library Documentation

This page last changed on Apr 08, 2011 by keith.carpentier.

Introduction
Games on the MocoSpace platform live inside of an iframe hosted on a MocoSpace page. To complete integration you must provide us with the URL for your game, which will become the target of the iframe, and this URL will receive the necessary information required to retrieve information from the MocoSpace API (the OAuth access token). This URL must be secure as the OAuth access token to make OpenSocial API requests will be included as a request parameter (see OpenSocial API for details on its usage) and this should never be shared. We provide a JavaScript library that makes requests to our OpenSocial REST API directly so knowledge on how the API works and can be used it not required. However, you may wish to make use of the REST API directly for server to server calls. See the OpenSocial API Documentation for more.

Library Requirements
The opensocial javascript library provides helper methods to retrieve data from the opensocial API as well as post changes. The following is required to use the library:

<script language="javascript" type="text/javascript" src="http://img.mocospace.com.edgesuite.net/wk/js/ opensocial/1.5/opensocial.js"></script>

Note that the OpenSocial API uses OAuth 2.0 standards as outlined at: http://tools.ietf.org/html/draftietf-oauth-v2-10 Make sure to check regularly to see if newer versions of the opensocial JS library have been released.

Objects
The following opensocial objects are inflated within the opensocial JS library: Person - see http://wiki.opensocial.org/index.php?title=Opensocial.Person_(v0.9) for details. One additional field has been added named 'locale' which returns the locale of the user to be used for internationalization. This will have the standard format such as en_US or es_US (ISO-639 language code + ISO-3166 country code). Activity - see http://wiki.opensocial.org/index.php?title=Opensocial.Activity_(v0.9) for details. Used to create an activity item for the user (the user associated with the access token used in the request), which will appear in the What's Up feed of the user's friends. Collection - see http://wiki.opensocial.org/index.php?title=Opensocial.Collection_(v0.9) for details. Currently requesting a user's friends is the only method that will return more than one object. Collection provides a mechanism to page results efficiently. DataResponse - see http://wiki.opensocial.org/index.php?title=Opensocial.DataResponse_(v0.9) for details. Holds any error information associated with a failed request (if the requests fails) and holds the successful data.

Methods
The JS library provided attempts to mimic the requests outlined in the opensocial API: http:// wiki.opensocial.org/index.php?title=Opensocial_(v0.9) with the following differences: As the existing container does not support the full gadget functionality and instead runs in a standard iframe, there is no concept of bundling requests to be executed simultaneously. As a result, there is no need for a data request object. Instead requests are made one at a time and return the same response item one would expect.

Document generated by Confluence on Apr 08, 2011 17:16

Page 1

Not all end points are supported including the ability to store in app data on a global and user level. opensocial.fetchPerson(id, opt_params, callback): Description: fetches MocoSpace User info. Private information will only be included for users who have installed the game and have allowed profile access to the user associated with the access token used. Parameters: id - of the user to be returned. This must either be '@me' indicating the current MocoSpace user playing the game or valid ids of MocoSpace users. This is a required field. opt_params - map of parameters to be used in determining the fields to be included in the response. User's id, displayName, and thumbnail url will always be included in the response. callback - function to be executed upon completion of the request. It will be passed a single parameter which is an instance of opensocial.ResponseItem. The response will either include the data returned or error information indicating why it failed. Example:

var params = {}; params[opensocial.PeopleRequestFields.PROFILE_DETAILS] = [ opensocial.Person.Field.ABOUT_ME, opensocial.Person.Field.STATUS ]; opensocial.fetchPerson('@me',params, function(data) { if (data.hadError()) { alert("Error fetching my info?! "+data.getErrorMessage()); } else { alert("Current player id: "+data.getData().getField(opensocial.Person.Field.ID)); } });

opensocial.fetchFriends(id, opt_params, callback): Description: fetches a MocoSpace User's friends with ability to sort and page. Can only fetch friends of a user who has installed the game. Private information will only be included for users who have installed the game and have allowed profile access to the user associated with the access token used. Parameters: id - of the user whose friends are to be returned. This must either be '@me' indicating the current MocoSpace user playing the game or valid ids of MocoSpace users. This is a required field. opt_params - map of parameters to be used in determing the fields, order, max size, and start index of the results. Note that filtering is not supported at this time. User's id, displayName, and thumbnail url will always be included in the response. callback - function to be executed upon completion of the request. It will be passed a single parameter which is an instance of opensocial.ResponseItem. The response will either include the data returned or error information indicating why it failed. Example:

var params = {}; params[opensocial.PeopleRequestFields.SORT_ORDER] = opensocial.PeopleSortOrder.NETWORK_PRESENCE; params[opensocial.PeopleRequestFields.MAX] = 20; opensocial.fetchFriends('@me',params, function(data) { if (data.hadError()) { alert("Error fetching my friends?! "+data.getErrorMessage()); } else { var friendNames = ""; data.getData().each(function(friend) { if (friendNames != "") friendNames += ", "; friendNames += friend.getField(opensocial.Person.Field.DISPLAY_NAME);

Document generated by Confluence on Apr 08, 2011 17:16

Page 2

} alert("My friends in order of online presence (max 20): "+friendNames); } });

opensocial.createActivity(activity, opt_callback): Description: Used to set game status of the player as viewable from the user's profile page. Status can not be empty or longer than 150 characters. Parameters: activity - configuring the new game status opt_callback - function to be executed upon completion of the request. It will be passed a single parameter which is an instance of opensocial.ResponseItem. If the response is successful, calling getData() will always return null. If failed, then the usual failure methods will provide the cause. Example:

var activity = new opensocial.Activity(); activity.setField(opensocial.Activity.Field.TITLE,'Some new game status!'); activity.setField(opensocial.Activity.Field.STREAM_URL,'trackingAction=123&hello=world'); activity.setField(opensocial.Activity.Field.STREAM_TITLE,'some url text'); opensocial.createActivity(activity, function(data) { if (data.hadError()) { alert("Unable to create activity: "+data.getErrorMessage()); } else { alert("Game Status Set!"); } } );

Resize Containing IFrame


As outlined in the introduction, your game will run in an iframe hosted within the MocoSpace domain. The size of the iframe is by default sized to be 100% of the screen width of the device and take up the remaining length of the page under the MocoSpace header. This means that if your game size is greater than the iframe size given, it will not appear nor will the iframe be scrollable to show the content. To allow for this, the iframe size can be configured by executing the following javascript (most likely placed in an onReady event listener):

MocoSpace.resizeGameIframe();

By default, this will resize the iframe to match the dimensions of your game's document loaded within the iframe. This will allow for games that are too long or wide to fit on the user's screen and will allow the user to scroll to the overflow portions of the page. Optionally a width and height can be specified in pixels. Example setting height to 400px and width to 600px:

MocoSpace.resizeGameIframe(400,600);

Note that zooming is disabled for all devices.

Document generated by Confluence on Apr 08, 2011 17:16

Page 3

Listening for Orientation Change


An orientation change listener within an iframe will never get fired. As a result, this makes listening for such event problematic. This can be overcome by registering an event listener with the MocoSpace namespace as follows (example here will resize the iframe):

MocoSpace.registerOrientationListener(function(orientation) { MocoSpace.resizeGameIframe(); });

Cross Domain Restrictions


Your portion of the code runs within an iframe of a page. The domain of the iframe is different than that used to make OpenSocial API requests. As a result, these requests are cross-domain and cannot be done using the standard AJAX techniques as they will be blocked by the browser. To get around this limitation, the opensocial javascript library uses the following methods:
postMessage and onMessage JS methods

http://www.w3.org/TR/html5/comms.html This is used when making requests to the MocoSpace portion of the JS library to launch the widgets listed below or to request the container make POST requests to the OpenSocial API on behalf of the game (as JSONP only works for GET requests).
JSONP for all OpenSocial API calls.

See http://remysharp.com/2007/10/08/what-is-jsonp/. JSONP will allow for concurrent requests and therefore does not require chaining as is the case with the iframe technique.

Widgets
To ease integration, the library also includes the following widgets. In order to use the invite and Moco Gold widgets, you will need to add the following includes: Moco Gold widget: Opens a JQModal dialog holding an iframe that will allow a user to debit Moco Gold virtual currency to be used by your game. You must pass the name of the item to be purchased and you can optionally pass the url of an image of the item. Launching the widget will have the following results all of which are handled via javascript function callbacks:

onAbort - executed when a user cancels the operation. The function receives no parameters. onError - indicates an unexpected error occurred either loading the iframe or attempting to complete the transaction. The function will include one parameter which is a string indicating the reason for the failure. onSuccess - indicates the transaction was successful and your game has been credited with Moco Gold to be used by the user. The function call will include 4 parameters: - id of the transaction (a unique integer) - timestamp of the transaction as a long in milliseconds - token - an MD5 hash of the following concatenated if the order given: id, amount, timestamp, <your games secret code> to be used to verify that the result is valid. Example of how to verify the hash in Java using Apache Commons DigestUtils:

org.json.JSONObject jsonObject = new org.json.JSONObject("{\"timestamp\": \"123456789\",\"id\":\"123456789\",\"amount\":\"123\",\"result\":\"success\",\"token\": \"abcdef123456789\"}"); String calcToken = org.apache.commons.codec.digest.DigestUtils.md5Hex( jsonObject.get("id")+jsonObject.get("amount")+jsonObject.get("timestamp")+<Your Secret>); if (!jsonObject.get("token").equals(calcToken)) {

Document generated by Confluence on Apr 08, 2011 17:16

Page 4

throw new Exception("Not a valid token!"); }

It is highly recommend that the token is verified by you prior to crediting the user in your game. onAsync - indicates that the user does not have enough Moco Gold to cover the amount requested. A new window will be opened where the user can top-up and then reattempt to purchase your item. You may listen for this case and store the item in a cart or other location to easily allow the user to attempt to purchase it again once they have topped up.

The function takes the following parameters:


The amount of gold you wish to debit (integer) The name of the item the user is purchasing or other text to be shown to the user A mapping of the callback functions to be executed upon completion

Example usage:

MocoSpace.goldTransaction(50,'some item',{ onSuccess: function(id,timestamp,token) { alert("Item purchased: "+id+", timestamp: "+timestamp+", token: "+token); // send back to your servers here to verify token and credit user }, onError: function(reason) { alert("Error getting item: "+reason); }, onAbort: function() { alert("User abort"); }, onAsync: function() { alert("Top-up of MocoGold required"); // store item in your cart here } },"http://some.com/image.gif");

* Invite widget: launches a JQModal dialog where a user can send an invite to 1 or more of his or her MocoSpace friends. The user can append custom text to the invite. Note that the friends listed are in alphabetical order. Parameters passed to the function:

subject of the invite (optional, default is "Come Join Me!") message of the invite that can be modified by the user (optional, default is "Come play this cool game with me!") url_text is the text of the url shown that when clicked will bring invited user to your game (optional, default is "Start Playing") url_link is any additional query parameters that will be passed to the game when a user clicks on the link. The string given should make sure to separate multiple parameters with an ampersand (i.e. url_link = 'param1=123&param2=456') opt_callback function called when invite sent. It takes a single parameter which is the ResponseItem for the request whose data is an array of user IDs who were sent an invitation.

Example usage:

MocoSpace.inviteFriends('Come play tetris with Bob','Bob wants you to come play him in tetris','Start playing','inviting_user_name=bob', function(response) { if (response.hadError()) {

Document generated by Confluence on Apr 08, 2011 17:16

Page 5

alert("Error sending invites: "+response.getErrorMessage()); } else { alert("Invites sent to: "+data.getData()); } } );

Mini Profile Widget: launches a modal dialog displaying basic information about a user with the ability to send a friendship request, instant message, or offline message as well as view the user's profile. Only a user id needs to be provided to launch the widget:

MocoSpace.showProfileInfo(userId);

Optimization
As mentioned in the cross domain restrictions section, the OpenSocial JS library utilizes JSONP to make concurrent requests to the API by inserting javascript tags to the DOM. This functionality can be used on page load for cases where it is known that certain data will be required as soon as possible. Here is an example that would be used in a JSP page where the accessToken is taken from the request:

<html> <head> <script language="javascript" type="text/javascript" src="http://www.mocospace.com/wap2/js/ opensocial.js"></script> <script language="javascript" type="text/javascript"> function fetchMocoUser(data) { me = new opensocial.Person(data.entry); alert("Hello "+me.getField(opensocial.Person.Field.DISPLAY_NAME)); } </script> <script language="javascript" type="text/javascript" src="https://www.mocospace.com/social/people/ @me/@self?oauth_token=<%= request.getParameter("oauth_consumer_key") %>&jsonp=fetchMocoUser"></ script> </head> <body/> </html>

This technique ensures that the data will be available as soon as the page is ready. Note that you can also use page redirects to fetch information using this technique.

Visitor Support
Games on MocoSpace allow for non-logged in users (visitors) to play games. Visitors can do everything a normal player can with the exception of spending MocoGold, chatting, adding friends and exploring other parts of the MocoSpace site. Visitors can be asked to convert to full users at developer defined intervals. To enable visitor support you won't have to do anything. The only thing you need to ensure is that your game can handle a person object that has no friends and only has the Username and userID set. Things you should be aware of: Visitors show up as regular users. Visually the only differences are in the profile picture and the visitor name (which will show up as "Guest_12345"). When visitors are prompted to invite friends, the platform will prompt visitors to sign up. When visitors want to debit MocoGold they will be prompted to sign up.

Document generated by Confluence on Apr 08, 2011 17:16

Page 6

The person object you get from MocoSpace will be empty except for the guest username and a userID. Username and userID will change when a visitor becomes a real user. When a user moves from being a visitor to a real user, the OAUTH token remains the same. We added a new field to Person named isVisitor Visitors cannot receive notifications Example code to determine if a user is a visitor:

var params= {}; params\[opensocial.PeopleRequestFields.PROFILE_DETAILS\] = \[opensocial.Person.Field.IS_VISITOR\]; opensocial.fetchPerson("@me",params, function(data) { if (data.hadError()) alert("Error: "+data.getErrorMessage()); else alert('is '+(data.getData().getField(opensocial.Person.Field.IS\_VISITOR) ? 'NOT' : '')+' a visitor'); }

Also a game may prompt a visitor to upgrade via the following:

MocoSpace.loginOrSignup({ &nbsp;&nbsp;&nbsp;&nbsp;onSuccess: function() { &nbsp;&nbsp;&nbsp;&nbsp;onAbort: function() { alert('Visitor upgraded\!'); }, }, }

alert('Visitor aborted the dialog');

&nbsp;&nbsp;&nbsp;&nbsp;onError: function(errorMsg) { });

alert('Unexpected error: '+errorMsg);

Document generated by Confluence on Apr 08, 2011 17:16

Page 7

You might also like