Posting on Facebook wall using oauth2 library

I have already covered posting on twitter in an earlier post. Today, lets see how we can post on Facebook.

To post on facebook, first create an app on facebook. Note that we need to submit the app for review on facebook if we want to write on users FB wall. However, for development purpose we do not need to get it reviewed.

We will be using oauth2 library. Lets first create a config object, which specifies ClientID, ClientSecret, auth urls, callback etc.

var FACEBOOK = &oauth2.Config{
	ClientID:     "",
	ClientSecret: "",
	Endpoint : oauth2.Endpoint{AuthURL:"https://graph.facebook.com/oauth/authorize", TokenURL: "https://graph.facebook.com/oauth/access_token"},
	RedirectURL:  "http://localhost:9000/Save",
	Scopes : []string{"publish_actions","user_location", "user_about_me", "read_friendlists"},
}

Now lets create a controller action where user will come to authorise. In revel, it looks like

func (c Facebook) AuthoriseFacebook() revel.Result {
	authUrl := FACEBOOK.AuthCodeURL(FACEBOOK.RedirectURL)
	return c.Redirect(authUrl)
}

When user comes to “/AuthoriseFacebook” he is redirected to Facebook authorisation url and sees a dialog, where he can authorise our app.

The user is then redirected to RedirectURL as specified in config.

In the redirected url, we will get a code (access_token), which we need to save in our database. Using gorm and revel, it looks along following lines

func (c Facebook) Save(code string) revel.Result {
	var tok *oauth2.Token
	var err error
	var user *models.User
	tok, err = FACEBOOK.Exchange(nil, code)
        facebookAccount = models.FacebookAccount{AccessToken: tok.AccessToken, RefreshToken: tok.RefreshToken, UserId:user.Id, Expiry : tok.Expiry.UnixNano()}
	}

	c.Begin()
	defer func() {
		if (c.Txn != nil) {
			c.Rollback()
		}
	}()
	c.Txn.Save(&facebookAccount)
	c.Commit()
}

Here we are saving access_token in a FacebookAccount domain, to use it later to post on user’s behalf.

Now to post on user’s behalf

func (c Facebook) Post() revel.Result {
	httpClient := FACEBOOK.Client(nil, &oauth2.Token{AccessToken:facebookAccount.AccessToken, Expiry: time.Unix(0,facebookAccount.Expiry)})
	httpClient.Post("https://graph.facebook.com/me/feed?message={urlencodedmessage}&access_token="+ facebookAccount.AccessToken, "text/plain", bytes.NewBufferString(""))
	return c.RenderText("Done")
}

And we are done!

Let me know, if you know of any better ways!

~~ Whizdumb ~~
Email : sachin.xpert@gmail.com