Facebook SDK Grails Plugin
Groovy Java Shell
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
grails-app
scripts
src/groovy/grails/plugins/facebooksdk
web-app/WEB-INF
.gitignore
FacebookSdkGrailsPlugin.groovy
README.md
application.properties
plugin.xml

README.md

Facebook SDK Grails Plugin

Introduction

The Facebook Platform is a set of APIs that make your application more social. Read more about integrating Facebook with your web site on the Facebook developer site.

This project contains the open source Facebook SDK Grails Plugin that allows you to integrate the Facebook Platform on a website/app powered by Grails.

This plugin is a port of the official Facebook PHP SDK V3.1.1 to Grails 2.0.

It supports the latest OAuth2.0 authentication (required since October 1st 2011).

Facebook SDK Grails Plugin provides :

Getting started with a demo app

If you want to quickly run the SDK on a demo app, you can download Facebook SDK Grails demo.

Plugin Installation

Declare the plugin dependency in the BuildConfig.groovvy file, as shown here:

grails.project.dependency.resolution = {
		inherits("global") { }
		log "info"
		repositories {
				//your repositories
		}
		dependencies {
				//your regular dependencies
		}
		plugins {
				//here go your plugin dependencies
				runtime ':facebook-sdk:0.2.0'
		}
}

Plugin Config

Create a Facebook app on Facebook Developers, in order to get your own app ID and app secret.

Add your Facebook app parameters to your grails-app/conf/Config.groovy:

grails.plugins.facebooksdk.appId = {APP_ID}
grails.plugins.facebooksdk.appPermissions = {APP_PERMISSIONS}
grails.plugins.facebooksdk.appSecret = {APP_SECRET}

Facebook App Service Usage

Reference facebookAppService from any of your grails artefacts (controllers, domain, services...) to automatically inject it.

def facebookAppService

The plugin automatically run a filter that create the following data in request scope.

request.facebook.app.id = YOU_APP_ID
request.facebook.app.permissions = YOU_APP_PERMISSIONS
request.facebook.app.secret = YOU_APP_SECRET

request.facebook.user.id = CURRENT_USER_ID

request.facebook.authenticated = TRUE_OR_FALSE

User Id

You can check if current user has authorized your app and is authenticated, get userId from facebookAppService. It will return 0 if user is not authenticated (or if he has not authorized your app).

def userId = facebookAppService.getUserId()
if (userId) {
	println "User authenticated (id=${userId})"
} else {
	println "User not authenticated"
}

User Access Token

If current user is authenticated, you can get his private accessToken from facebookAppService.

If the app is running on a website, the access token will be automatically fetched in exchange for the authorization code returned by Facebook JS SDK signed request cookie. It is recommended to wrap this code in a try/catch block since external HTTP calls to Facebook Graph API might be executed.

If the app is running on Facebook.com, the access token will be extracted from the signed request params (passed through the canvas iFrame).

try {
	String userAccessToken = facebookAppService.getUserAccessToken()
} catch (Exception exception) {
	// Something went wrong...
}

By default, after initial request, access token is stored in session scope for better performance: another reason to surround all your Facebook Graph API calls in try/catch in order to catch expired/invalid access tokens.

Controller integration

Facebook Graph Client usage

To perform Facebook Graph API call, use the FacebookGraphClient without access token for public data or with an access token for private data. FacebookGraphClient is a thin groovy wrapper around the rock solid RestFB java library. It will return JSON-based graph objects.

To play with the API, you might use the grails console from your project root and get user token or app token from Facebook Access Token Tool.

grails console

Initialization

import grails.plugins.facebooksdk.FacebookGraphClient
// For public data
def facebookClient = new FacebookGraphClient()
// For private data (access token required)
def userAccessToken = facebookAppService.getUserAccessToken() // Or any app/user token
def facebookClient = new FacebookGraphClient(userAccessToken)

Fetching Single Objects

def user = facebookClient.fetchObject("me") // Requires a user access token
def page = facebookClient.fetchObject("cocacola")
println "User name: " + user.name
println "Page likes: " + page.likes

Fetching Multiple Objects in One Call

def fetchObjectsResults = facebookClient.fetchObjects(["me", "cocacola"])
println "User name: " + fetchObjectsResults["me"].name
println "Page likes: " + fetchObjectsResults["cocacola"].likes

Fetching Connections

def myFriends = facebookClient.fetchConnection("me/friends")
def myFeed = facebookClient.fetchConnection("me/feed")
println "Count of my friends: " + myFriends.size()
println "First item in my feed: " + myFeed[0]

Searching

// Searching is just a special case of fetching Connections -
// all you have to do is pass along a few extra parameters.
def publicSearch = facebookClient.fetchConnection("search", [q:"watermelon", type:"post"])
println "Public search: " + publicSearch[0].message
// Targeted search
def targetedSearch = facebookClient.fetchConnection("me/home", [q:"Mark", type:"user"])
println "Posts on my wall by friends named Mark: " + targetedSearch.size()

Fetching Insights

// Fetching Insights data is as simple as fetching a Connection
def insights = facebookClient.fetchConnection("PAGE_ID/insights")
for (insight in insights) println insight.name

Executing FQL Queries

String query = "SELECT uid, name FROM user WHERE uid=220439 or uid=7901103"
def users = facebookClient.executeQuery(query)
println "Users: " + users

Executing Multiple FQL Queries in One Call

Map queries = [users:"SELECT uid, name FROM user WHERE uid=220439 OR uid=7901103", likers:"SELECT user_id FROM like WHERE object_id=122788341354"]
multiqueryResults = facebookClient.executeMultiquery(queries)
println "Users: " + multiqueryResults.users
println "People who liked: " + multiqueryResults.likers

Metadata/Introspection

// You can specify metadata=1 for many calls, not just this one.
// See the Facebook Graph API documentation for more details. 
def userWithMetadata = facebookClient.fetchObject("me", [metadata:1])
println "User connections  " + userWithMetadata.metadata.connections

Passing Parameters

// You can pass along any parameters you'd like to the Facebook endpoint.
Date oneWeekAgo = new Date() - 7
def filteredFeed = facebookClient.fetchConnection("me/feed", [limit:3, until:"yesterday", since:oneWeekAgo])
println "Filtered feed count: " + filteredFeed.size()

Selecting Specific Fields

def user = facebookClient.fetchObject("me", [fields:"id, name"])
println "User name: " + user.name

Publishing a Message and Event

// Publishing a simple message.
def publishMessageResponse = facebookClient.publish("me/feed", [message:"RestFB test"])
println "Published message ID: " + publishMessageResponse.id

// Publishing an event
Date tomorrow = new Date() + 1
Date twoDaysFromNow = new Date() + 2
def publishEventResponse = facebookClient.publish("me/events", [name:"Party", start_time:tomorrow, end_time:twoDaysFromNow])
println "Published event ID: " + publishEventResponse.id

Publishing a Photo or a Video

// Publishing an image to a photo album is easy!
// Just specify the image you'd like to upload and RestFB will handle it from there.
def publishPhotoResponse = facebookClient.publishFile("me/photos", [message, "Test cat"], "/cat.png")
println "Published photo ID: " + publishPhotoResponse.id
// Publishing a video works the same way.
facebookClient.publish("me/videos", [message, "Test cat"], "/cat.mov")

Deleting

Boolean deleted = facebookClient.deleteObject("some object ID")
out.println("Deleted object? " + deleted)

Using the Batch Request API

List batchResponses = facebookClient.executeBatch(["me", "m83music/feed"]);
// Responses are ordered to match up with their corresponding requests.
println "Me object " + batchResponses[0]
println "M83 feed " + batchResponses[1]

Error Handling

All FacebookClient methods may throw com.restfb.exception.FacebookException, which is an unchecked exception as of RestFB 1.6.

These are the FacebookException subclasses that you may catch:

  • FacebookJsonMappingException
  • FacebookNetworkException
  • FacebookGraphException
  • FacebookOAuthException
  • FacebookQueryParseException
  • FacebookResponseStatusException

For more info, check RestFB java library documentation.

Facebook JS Taglib usage

Current tag lib has 3 tags (but other are coming soon...).

facebook:init

To initialize Facebook JS SDK in your GSP views, simply insert initJS tag, after HTML body tag. The only required attribute is appId.

<facebook:initJS appId="${facebook.app.id}" />

Optional attributes are :

  • autoGrowth Call FB.setAutoGroth() after page rendering (default to false)
  • channelUrl Channel File
  • cookie Enable cookies to allow the server to access the session (default to true)
  • locale Define JS SDK locale (default to server locale)
  • status Check login status (default to false)
  • xfbml Parse XFBML (default to false)

facebook:loginLink

For the user to connect/install your app, use loginLink tag.

<facebook:loginLink appPermissions="${facebook.app.permissions}">Login</facebook:loginLink>

Optional attributes are :

  • appPermissions Facebook app permissions/scope
  • cancelURL Cancel URL for redirect if login is canceled (if not defined, nothing happens)
  • elementClass HTML element 'class' attribute value
  • elementId HTML element 'id' attribute value
  • returnURL Return URL for redirect after login (if not defined page will be reloaded)

You might also use Facebook JS SDK Login button (but do not forget to set xfbml attributes to true in facebook:init tag).

<html xmlns:fb="http://ogp.me/ns/fb#">
...
<fb:login-button scope="${facebook.app.permissions}"></fb:login-button>

facebook:logoutLink

For the user to logout from your app and Facebook.com, use logoutLink tag.

<facebook:logoutLink>Logout</facebook:logoutLink>

Optional attributes are :

  • elementClass HTML element 'class' attribute value
  • elementId HTML element 'id' attribute value
  • nextURL Next URL for redirect after logout (if not defined page will be reloaded)

Bugs

To report any bug, please use the project Issues section on GitHub.

Alpha status

This is an alpha release. The underlying APIs are generally stable, however we may make changes to the library in response to developer feedback.

Feedback

The Facebook SDK Grails Plugin is not an official Facebook SDK such as Javascript, PHP, iOS and Android SDKs.

It is developped by Affinitiz, a french social media web agency.

The Facebook Grails SDK is licensed under the Apache Licence, Version 2.0.