CyberPolicy is monitoring news of the coronavirus (COVID-19) outbreak and has activated a business continuity plan in response to the situation. We have implemented precautionary and preparedness measures to reduce exposure to the coronavirus and are prepared to maintain normal business operations.
X

How to Create a Fan-gated Facebook Tab with Rails and JavaScript

Facebook APIs got you down? Try the following step-by-step guide to an awesome fan page
===================================

Hopefully you weren't beating your head against the FB APIs too long before you turned to a Google search. The following is a soup-to-nuts guide for creating a Facebook fan page with content customized for fans vs. non-fans (i.e. visitors pre- and post-like).

A little background: we had a fan page on FB that wasn't really doing anything for us, an idea for content that might be useful to people -- and a design to make things pretty. We wanted 1) visitors to see a custom tab, not just the wall, 2) our fans to get some useful info for liking us, and 3) to be able to poll our fans for answers to insurance-related questions.

Now that we have the basic requirements, what's stopping us? Well, first [what's a custom tab](#the_nuts) and [how do we populate it with content?](#tab_content) Then, [how do we know when a user likes our page?](#user_likes) Last, [how do we get the Facebook userID](#userID) from the tab so we can track unique votes on our polls?

Prereqs.
-------

1. [A Facebook account](#prereq_1)
2. [A fan page of some kind](#prereq_2)
3. [Developer access](#prereq_3)

If you've already got a handle on these, skip the soup and go straight to [the nuts](#the_nuts). =]

1. A Facebook account:


Odds are you already have one of these, but I said soup-to-nuts dammit, and I didn't want all these likes, unlikes, pages and apps getting posted to my real profile while I was writing this, so here's an overview.

Go to www.facebook.com and fill out the Sign Up form on the right hand side.

Facebook sign up form



Click the Sign Up button and answer the security CAPTCHA.

Facebook account creation



You can skip the next two or three steps and go directly to confirming your account's email.

We don't need to add friends, this will be a dev account.

Facebook account setup step 1
Account settings step 1 - skip it



Again, we don't really care, this account is for dev/test purposes

Facebook account setup step 2
Account settings step 2 - skip it



I like to add a profile photo so I can tell my accounts apart at a glance.

Facebook account setup step 3
Account settings step 3 - skip or complete it



If you haven't already, go to your email and confirm the account you signed up with. Click the link or the Complete Sign-up button.

Facebook email address confirmation
This is especially important if you forget your password... I've heard.



E voila...

Facebook profile
Your super awesome dev account is ready to go.





Prereqs. continued



2. A fan Page:



Because, well, everyone wants to be liked, even companies. =]

Facebook profile footer
Click the create a page link.



Pick a page type, I'm going with "Company, Organization, or Institution."

Create a page 01
Create page - step 1 of 6



Choose a category, fill in the Company Name and agree to the Facebook Pages Terms before clicking the Get Started button.

Create a page 02
Create page - step 2 of 6



Fill in the CAPTCHA answers to prove you're human.

Create a page 03
Create page - step 3 of 6



Add a profile photo for the company

Create a page 04
Create page - step 4 of 6



Go ahead and skip this step, we're not ready for actual fans yet.

Create a page 05
Create page - step 5 of 6



Add a description to the about blurb, this will show up in the fan page beneath the available tabs. It get's truncated, so keep it short and sweet.

Create a page 06
Create page - step 6 of 6



Bada-bing-bang-boom!

Create a page final
Your company page is ready for customization.




Prereqs. continued (last one though, I promise)



3. Developer access:



This will give you access to the apps section of the facebook developers portal.

Click on the Developers link in the footer navigation.

Developer access



or go directly to http://developers.facebook.com and click Apps

Developers section



Click Allow to add the developer app to your profile.

Developer app auth



And there you are, a full fledged Facebook developer. Wouldn't your mom be proud?

Developers ‐> Apps





What is a custom tab?



### Ans: It's just a Facebook app that lives in the left nav of your fan page. ##

Wait, really? Yup, that's it, let's see what it takes.

### Create a Facebook Page Tab App ##

Click the Create New App button at the top of the Apps section.

create a new app
Create app - step 1 of N



Fill in a name and accept the Terms before clicking the Continue button.

new app name
Create app - step 2 of N



WTF? Srsly? OK, so if you see something like the following error,

Your account must be verified before you can take this action. Please verify your account by adding your mobile phone or credit card.
Create app - fail =[



Just go to Account -> Account Settings -> mobile and run through that whole rigamarole. I don't feel like screen-capping it. =P

Now that your account is 'verified', clicking Continue in the dialog will take you to the Settings -> Basic page for your new app.

Brand new Facebook app
Sweet, we're almost there.



Now let's make it a Page Tab. Click the Page Tab section at the bottom of the Basic settings and fill in Page Tab Name, Page Tab URL and Secure Page Tab URL. You can also edit the logo and icon for the App/Tab on this page.

Make it a Page Tab
I've pointed the URL at my local dev server for the moment. This will work as long as I'm the only one accessing the app. i.e. during development.



After you click Save Changes, you'll get a nice little confirmation at the top of the section.

Settings Saved
If you leave out the Secure Page Tab URL, you'll see a warning. Don't Panic... unless it's after October 2011, then, Panic!



I made Facebook App that works as a Page Tab, now what?

### Add the Page Tab to your Fan page ##

Click View App Profile Page

App profile link



Click Add to My Page

Add to My Page



A lightboxed dialog pops up with a list of Pages that you have admin access to. Click Add to Page for the fan page you created earlier.

Add to Page



Close the dialog and go to your fan page. You can get there by searching for the company name or by going to you profile and clicking the page name in the Pages section.

Profile navigation - go to page



Sweet! Now we have a Fan page with a custom tab. What's in there?

Fan page custom tab



Oh, snap!

Custom Page tab broken content
...well, it's to be expected really, we haven't started serving the content yet. =D



Serve the content for your FB App with a Rails application



#### 1. Create the app


[keith : demos]$ rails new facebook_app && cd facebook_app
create
create README
create Rakefile
...
create vendor/plugins/.gitkeep

[keith : facebook_app]$ rails g controller facebook index
create app/controllers/facebook_controller.rb
route get "facebook/index"
invoke erb
create app/views/facebook
create app/views/facebook/index.html.erb
invoke test_unit
create test/functional/facebook_controller_test.rb
invoke helper
create app/helpers/facebook_helper.rb
invoke test_unit
create test/unit/helpers/facebook_helper_test.rb





#### 2. Set up the routes


[keith : facebook_app]$ vim config/routes.rb && head config/routes.rb
FacebookApp::Application.routes.draw do
match "facebook" => 'facebook#index'
...





#### 3. Start the server


[keith : facebook_app]$ rails s
=> Booting WEBrick
=> Rails 3.0.10 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2011-08-29 11:52:38] INFO WEBrick 1.3.1
[2011-08-29 11:52:38] INFO ruby 1.9.2 (2011-02-18) [x86_64-darwin10.7.0]
[2011-08-29 11:52:38] INFO WEBrick::HTTPServer#start: pid=65128 port=3000





Now refresh the Page Tab. Aaaand...

Custom Page tab development content
...toight like a toiger!



Now that we have a fan page, and a page tab pulling content from outside Facebook, let's change the default landing for our visitors. From the Get Started tab of the page click Edit Page.

Fan page - Get Started



This will take you to the Manage Permissions panel for your fan page. Change the Default Landing Tab to your Page Tab App

Fan page - Edit Settings
In my case, NinjaTab



Then you'll want to Save Changes.

Fan page - default landing



To see what your visitors will see, you'll have to log out of Facebook (or open a private browsing session) and go to the fan page you created.

Fan page - public view
As you can see, rather than the Wall, it now goes directly to the NinjaTab



Why did we have to log out first? Well according to [these guys](http://www.socialappshq.com/help/change-default-landing-page-for-facebook-page)



1. Only visitors who are non-fans and non-admins will land on it. Once a user “likes” your page, the page will reload and show them the “fans-only” content (if you’re using a landing tabs application like SocialAppsHQ.)HOWEVER, when a user who was already a fan visits the page, they will always default to the wall.


2. Similarly, page admins will always land on the Wall, whether they “liked” their own page or not. (Unfortunately, these are set by Facebook, and not something anyone can change.)






Sit back, relax a little, pat yourself on the back, you just got through the easy part. Yes, all of the preceding was just to get you to a point where you could start mucking around in the SDKs, now let's handle the sexy bits.



How do I know if a visitor likes my fan page and show them different content accordingly?



### Ans: Parse the signed_request param for the value of parsed_data['page']['liked'] ##

First you need to know about Facebook's signed_request param and what's in it. Whenever Facebook loads your application as a Page Tab it sends a signed_request param to your server. This will let you do things like, verify the request came from Facebook, figure out which page the request came from, and retrieve some basic user info. Note, fb only sends signed_request on the initial load of your app, clicks inside the iframe will not make this available to you.

The [signed_request](https://developers.facebook.com/docs/authentication/signed_request/) consists of an encrypted signature, followed by a dot ('.') followed by a base64url encoded JSON object. The thing to look out for here is the 'url' part of base64url encoding. Basically it strips padding and replaces + and / with - and _ respectively, check out the [wikipedia entry](http://en.wikipedia.org/wiki/Base64#URL_applications) for more details.

All set with signed_request? Good let's move on... oh wait, you probably want to know how to parse the signed_request. Well since this is just a demo I'm gonna show you the quick and dirty way to roll your own parser with Ruby. Libraries are for chumps.

### Set up the like-gate ##

Edit facebook_helper.rb and facebook/index.html.erb to look something like

Fan-gate step 1
You can find the completed code on [github](http://github.com/keithwoody/facebook_app_in_rails)



Now our Page Tab will have the following content

Fan-gate step 1b



And after adding a helper to parse the signed_request param, we can make user_likes_page? return a meaningful truthiness.

Fan-gate signed_request parser



Once they like the Page, fans will see

Fan-gate post-like content
Boosh!





How do I get the Facebook userID of the visitor viewing my fan page?



### Ans: Use the Facebook JavaScript SDK to grab the userID from the response. ##

This was by far the most error prone, face-palming, bastardly part of the project. Let's jump right in!

#### Prep for using the JavaScript SDK ##

First we'll add a channel_url route and action per the SDK [best practices](https://developers.facebook.com/docs/reference/javascript/FB.init/)

Edit your routes.rb file and add the following below your original route
`match "facebook/channel.html" => 'facebook#channel', :as => :facebook_channel `

Then add a channel action to the facebook controller, something like

Facebook JS SDK custom channel



Good, now add the .js lib and the FB.init block to your application layout, along with a fbml login tag.

add sdk to layout



You'll also need to set the FACEBOOK_APP_ID to the App ID/API Key from your App summary in the Facebook developer portal in some environment.

With any luck, the Page tab should show...

Fan page js didn't do anything
...hmph! a fat load of "nothing changed"... except that space at the top



Let's dig down and see if we can figure out what's going on. From the JavaScript console of your browser call the `FB.login()` function to see if the SDK is even functioning for us.

FB.login() in console



That should pop up a login dialog, but if you've been following along exactly, you'll most likely see

An error occurred with Ninja Fans! Please try again later.



It took me for-fricking-ever to finally figure out that you need some additional settings in your App configuration. i.e. If you want to have facebook users interact with your application via the JS SDK, you need to set the Canvas URL in App on Facebook section of the Basic settings.

App on Facebook settings



More specifically, [if you want to get a user's ID they need to log in to your Facebook App](http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=site%3Awww.hyperarts.com+%22can+i+access+user+data%22+facebook), and in order for them to log in, you need to fill in the previous settings. Don't forget to Save Changes.

App on Facebook settings - saved



So we're hooked up to the API, now when we call login() from the console, you'll get the login dialog if you're not signed in to facebook yet, or an authorization dialog if you are

App Request for Permission



#### Let's add something for the user to do where we need to track their userID ##

Say we want to know which users clicked our special ninja link. First we need a special ninja link, add it to the fan-only section
`

We let fans click this <%= link_to 'special ninja link', '#', :id =>'ninja' %>

`

Then we need some JavaScript to check for a user that's authorized our App.

Javascript to retrieve userID
Remember you can find all this on [github](http://github.com/keithwoody/facebook_app_in_rails)



#### Let's walk through that real quick ##
Lines 5-11 define a function that gets called in our click handler when the user is logged in and already authed or after they login and allow the App access.
Lines 13-28 uses jQuery to override the click handler of the ninja link and

1. checks if they're logged in to facebook and have our app authorized already
2. asks them to login and auth if they're not
3. responds with one message for authed users

App Allowed


4. responds with another message for users that decline to allow access

App Declined




Holy Crap! Are we really done?
--------------------------

Well let's see, we've got a fan Page with a custom Page Tab, that we set to be the Default Landing Tab. The content of our App is customized for Likers vs. non-likers, and we can pull the userID from Facebook when we need it. I'm going to call that good. Hope this has helped you. It'll be out of date any day now. FML.

Facebook custom tab completed



### To recap the caveats and gotchas I ran into ##

1. Upload your logos and Icons as GIFs or Facebook will transcode them into hideous caricatures.
2. Remember to set your App's Canvas URL if you want to be able to log users into it.
3. The Custom landing will only be default for not-logged-in-to-facebook users and non-fans, i.e. once they like the page any subsequent visits will take them to the Wall.

© 2010 - CoverHound LLC - All rights reserved.
PO Box 9070, Carlsbad, CA. 92018-9070
CoverHound© is a trademark of CoverHound LLC
DBA: CoverHound Insurance Solutions - CA License
No. 6005304