JavaScript

Best JavaScript SDK tut with nice demo


reference :

http://thinkdiff.net/facebook/new-javascript-sdk-oauth-2-0-based-fbconnect-tutorial/

New JavaScript SDK & OAuth 2.0 based FBConnect Tutorial

by  on JULY 22, 2011 in FACEBOOK

facebook Today Facebook released their updated JavaScript SDK . Now the authentication system is based on OAuth 2.0 and HTTPS. So I updated my previous tutorial by writing this new post. In this post I’ll show you using javascript how could you easily integrate facebook connect (login/logout) features in your site. Additionally how to use Facebook API to get user’s information. Here I only used JavaScript no back-end PHP or any server side language.

In this tutorial I’ll explain:

  1. Facebook Authentication Process
  2. Facebook new JavaScript Usage
  3. Facebook Connect Authentication
  4. How to get extended permission to get more informations
  5. How to use graph api
  6. How to show stream publish prompt and share prompt
  7. How to publish post in user’s wall using graph api
  8. How to get additional information by FQL Query
  9. How to set status using old legacy api (REST api) calling
  10. How to show ajax loader when interactive with facebook

 

Before proceeding:
Demo App 

1.    Facebook Authentication Process

This is how facebook authorization process will work. We will follow this process in code.

2.    Facebook new JavaScript Usage

So in the figure you are seeing how authentication will work in your site. Now we will implement that. Firstly you’ve to setup a facebook application to get the application id. You can setup application from here . Or if you have already setup a facebook application then just copy the application id and replace with xxxxxxxxxxx. Remember oauth: true is new addition in this latest javascript sdk that enables your site for OAuth 2.0 authentication.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
window.fbAsyncInit = function() {
        FB.init({ appId: 'Your_APP_ID',
            status: true,
            cookie: true,
            xfbml: true,
            oauth: true});
        showLoader(true);
        function updateButton(response) {
            button       =   document.getElementById('fb-auth');
            userInfo     =   document.getElementById('user-info');
            if (response.authResponse) {
                //user is already logged in and connected
                FB.api('/me', function(info) {
                    login(response, info);
                });
                button.onclick = function() {
                    FB.logout(function(response) {
                        logout(response);
                    });
                };
            } else {
                //user is not connected to your app or logged out
                button.innerHTML = 'Login';
                button.onclick = function() {
                    showLoader(true);
                    FB.login(function(response) {
                        if (response.authResponse) {
                            FB.api('/me', function(info) {
                                login(response, info);
                            });
                        } else {
                            //user cancelled login or did not grant authorization
                            showLoader(false);
                        }
                    }, {scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
                }
            }
        }
        // run once with current status and whenever the status changes
        FB.getLoginStatus(updateButton);
        FB.Event.subscribe('auth.statusChange', updateButton);
    };
    (function() {
        var e = document.createElement('script'); e.async = true;
        e.src = document.location.protocol
            + '//connect.facebook.net/en_US/all.js';
        document.getElementById('fb-root').appendChild(e);
    }());

This is the most efficient way to load the javascript SDK in your web site. And in this way the sdk will load asynchronously so it does not block loading other elements of your page. Details of FB.init method .

And your html tag should be

1
2
<!DOCTYPE html>

3.    Facebook Connect Authentication

On the first part of the code you will see 2 Facebook api functions called

1
2
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);

After loading the facebook javascript library, this method getLoginStatus() called and checked the user authentication status and it will send the response toupdateButton() method.

FB.Event.subscribe() this method registered the auth.statusChange with facebook. That means if user successfully login or authorized your app or logout or cancel login process, it will trace that and call updateButton() method with the response. In thisupdateButton() method you’ll see the code of authentication that follows the first figure. In the full source code you’ll see 2 additional methods

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
function login(response, info){
    if (response.authResponse) {
        var accessToken                                =   response.authResponse.accessToken;
        userInfo.innerHTML                             = '<img src="https://graph.facebook.com/ ' + info.id + '/picture">' + info.name
            + "<br /> Your Access Token: " + accessToken;
        button.innerHTML                               = 'Logout';
        showLoader(false);
        document.getElementById('other').style.display = "block";
    }
}
function logout(response){
    userInfo.innerHTML                             =   "";
    document.getElementById('debug').innerHTML     =   "";
    document.getElementById('other').style.display =   "none";
    showLoader(false);
}

Those are called when user successfully login and authorized your app and when user logout.

4.    How to get extended permission to get more informations

On the first part of the code you’ll see the code that will run when user click login.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
//user is not connected to your app or logged out
    button.innerHTML = 'Login';
    button.onclick = function() {
        showLoader(true);
        FB.login(function(response) {
            if (response.authResponse) {
                FB.api('/me', function(info) {
                    login(response, info);
                });
            } else {
                //user cancelled login or did not grant authorization
                showLoader(false);
            }
        }, {scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
    }

In this part you’ll see scope where you can provide extended permission parameters name. Don’t provide all permissions, only think which information you may need for your site. Here is details about permissions .

1
{scope:'email,user_birthday,status_update,publish_stream,user_about_me'}

5.    How to use graph api

In the new javascript sdk, the authentication code is only changed, everything else remains same. To fully understand graph api visit the link  . Now i’ll show you, how to use graph api using javascript sdk. There is a method FB.api  . Using this method you can call graph api .

1
2
3
FB.api('/me', function(response) {
  alert(response.name);
});

By calling this method it will show logged in user name. For another example check 7 number point.

6.    How to show stream publish prompt and share prompt

There is another javascript sdk method named FB.ui . Using the code you can prompt user for stream publish or share your page.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
        showLoader(true);
        FB.ui(
        {
            method: 'stream.publish',
            message: '',
            attachment: {
                name: name,
                caption: '',
                description: (description),
                href: hrefLink
            },
            action_links: [
                { text: hrefTitle, href: hrefLink }
            ],
            user_prompt_message: userPrompt
        },
        function(response) {
            showLoader(false);
        });
    }
    function share(){
        showLoader(true);
        var share = {
            method: 'stream.share',
            u: 'http://thinkdiff.net/'
        };
        FB.ui(share, function(response) {
            showLoader(false);
            console.log(response);
        });
    }

You’ve to provide parameters when you call streamPublish() method.

1
2
3
4
5
6
function showStream(){
    FB.api('/me', function(response) {
        //console.log(response.id);
        streamPublish(response.name, 'I like the articles of Thinkdiff.net', 'hrefTitle', 'http://thinkdiff.net', "Share thinkdiff.net");
    });
}

7.    How to publish post in user’s wall using graph api

In my demo you’ll see another customized method named graphStreamPublish(). This is also a graph api example.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
function graphStreamPublish(){
        showLoader(true);
        FB.api('/me/feed', 'post',
        {
            message     : "I love thinkdiff.net for facebook app development tutorials",
            link        : 'http://ithinkdiff.net ',
            picture     : 'http://thinkdiff.net/iphone/lucky7_ios.jpg',
            name        : 'iOS Apps & Games',
            description : 'Checkout iOS apps and games from iThinkdiff.net. I found some of them are just awesome!'
        },
        function(response) {
            showLoader(false);
            if (!response || response.error) {
                alert('Error occured');
            } else {
                alert('Post ID: ' + response.id);
            }
        });
    }

This method uses FB.api() and does a HTTP POST request to http://graph.facebook.com/me/feed url with some parameters to publish a feed on user’s wall.

8.    How to get additional information by FQL Query

Facebook Query Language  enables you to use a SQL-style interface to query the data exposed by the Graph API . It provides for some advanced features not available in the Graph API, including batching multiple queries into a single call. Checkout the tables  to know which data of facebook user you can retrieve. In the demo’s source code you’ll see

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
function fqlQuery(){
        showLoader(true);
        FB.api('/me', function(response) {
            showLoader(false);
            var query       =  FB.Data.query('select name, profile_url, sex, pic_small from user where uid={0}', response.id);
            query.wait(function(rows) {
                document.getElementById('debug').innerHTML =
                    'FQL Information: '"<br />" +
                    'Your name: '      +  rows[0].name                                                            + "<br />" +
                    'Your Sex: '       +  (rows[0].sex!= undefined ? rows[0].sex : "")                            + "<br />" +
                    'Your Profile: '   "<a href='" + rows[0].profile_url + "'>" + rows[0].profile_url + "</a>" + "<br />" +
                    '<img src="'       +  rows[0].pic_small + '" alt="" />' + "<br />";
            });
        });
    }

9. How to set status using old legacy api (REST api) calling

You can still use the old legacy api . In my demo you’ll see a text box, write something and click ‘Status Set Using Legacy Api Call’ You’ll see your facebook status will update.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
function setStatus(){
        showLoader(true);
        status1 = document.getElementById('status').value;
        FB.api(
        {
            method: 'status.set',
            status: status1
        },
        function(response) {
            if (response == 0){
                alert('Your facebook status not updated. Give Status Update Permission.');
            }
            else{
                alert('Your facebook status updated');
            }
            showLoader(false);
        }
    );
}

10. How to show ajax loader when interactive with facebook

In the source code you will see a method showLoader(), and you’ll see several places of the source code this method is called.

1
2
3
4
5
6
function showLoader(status){
       if (status)
           document.getElementById('loader').style.display = 'block';
       else
           document.getElementById('loader').style.display = 'none';
   }

Full Source Code of this project. Or direct download from github

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
<!DOCTYPE html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>New JavaScript SDK & OAuth 2.0 based FBConnect Tutorial | Thinkdiff.net</title>
        <!--
            @author: Mahmud Ahsan (http://mahmud.thinkdiff.net)
        -->
    </head>
    <body>
        <div id="fb-root"></div>
        <script type="text/javascript">
            var button;
            var userInfo;
            window.fbAsyncInit = function() {
                FB.init({ appId: 'YOUR_APP_ID',
                    status: true,
                    cookie: true,
                    xfbml: true,
                    oauth: true});
               showLoader(true);
               function updateButton(response) {
                    button       =   document.getElementById('fb-auth');
                    userInfo     =   document.getElementById('user-info');
                    if (response.authResponse) {
                        //user is already logged in and connected
                        FB.api('/me', function(info) {
                            login(response, info);
                        });
                        button.onclick = function() {
                            FB.logout(function(response) {
                                logout(response);
                            });
                        };
                    } else {
                        //user is not connected to your app or logged out
                        button.innerHTML = 'Login';
                        button.onclick = function() {
                            showLoader(true);
                            FB.login(function(response) {
                                if (response.authResponse) {
                                    FB.api('/me', function(info) {
                                        login(response, info);
                                    });
                                } else {
                                    //user cancelled login or did not grant authorization
                                    showLoader(false);
                                }
                            }, {scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
                        }
                    }
                }
                // run once with current status and whenever the status changes
                FB.getLoginStatus(updateButton);
                FB.Event.subscribe('auth.statusChange', updateButton);
            };
            (function() {
                var e = document.createElement('script'); e.async = true;
                e.src = document.location.protocol
                    + '//connect.facebook.net/en_US/all.js';
                document.getElementById('fb-root').appendChild(e);
            }());
            function login(response, info){
                if (response.authResponse) {
                    var accessToken                                 =   response.authResponse.accessToken;
                    userInfo.innerHTML                             = '<img src="https://graph.facebook.com/ ' + info.id + '/picture">' + info.name
                                                                     + "<br /> Your Access Token: " + accessToken;
                    button.innerHTML                               = 'Logout';
                    showLoader(false);
                    document.getElementById('other').style.display = "block";
                }
            }
            function logout(response){
                userInfo.innerHTML                             =   "";
                document.getElementById('debug').innerHTML     =   "";
                document.getElementById('other').style.display =   "none";
                showLoader(false);
            }
            //stream publish method
            function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
                showLoader(true);
                FB.ui(
                {
                    method: 'stream.publish',
                    message: '',
                    attachment: {
                        name: name,
                        caption: '',
                        description: (description),
                        href: hrefLink
                    },
                    action_links: [
                        { text: hrefTitle, href: hrefLink }
                    ],
                    user_prompt_message: userPrompt
                },
                function(response) {
                    showLoader(false);
                });
            }
            function showStream(){
                FB.api('/me', function(response) {
                    //console.log(response.id);
                    streamPublish(response.name, 'I like the articles of Thinkdiff.net', 'hrefTitle', 'http://thinkdiff.net', "Share thinkdiff.net");
                });
            }
            function share(){
                showLoader(true);
                var share = {
                    method: 'stream.share',
                    u: 'http://thinkdiff.net/'
                };
                FB.ui(share, function(response) {
                    showLoader(false);
                    console.log(response);
                });
            }
            function graphStreamPublish(){
                showLoader(true);
                FB.api('/me/feed', 'post',
                    {
                        message     : "I love thinkdiff.net for facebook app development tutorials",
                        link        : 'http://ithinkdiff.net ',
                        picture     : 'http://thinkdiff.net/iphone/lucky7_ios.jpg',
                        name        : 'iOS Apps & Games',
                        description : 'Checkout iOS apps and games from iThinkdiff.net. I found some of them are just awesome!'
                },
                function(response) {
                    showLoader(false);
                    if (!response || response.error) {
                        alert('Error occured');
                    } else {
                        alert('Post ID: ' + response.id);
                    }
                });
            }
            function fqlQuery(){
                showLoader(true);
                FB.api('/me', function(response) {
                    showLoader(false);
                    //http://developers.facebook.com/docs/reference/fql/user/ 
                    var query       =  FB.Data.query('select name, profile_url, sex, pic_small from user where uid={0}', response.id);
                    query.wait(function(rows) {
                       document.getElementById('debug').innerHTML =
                         'FQL Information: '"<br />" +
                         'Your name: '      +  rows[0].name                                                            + "<br />" +
                         'Your Sex: '       +  (rows[0].sex!= undefined ? rows[0].sex : "")                            + "<br />" +
                         'Your Profile: '   "<a href='" + rows[0].profile_url + "'>" + rows[0].profile_url + "</a>" + "<br />" +
                         '<img src="'       +  rows[0].pic_small + '" alt="" />' + "<br />";
                     });
                });
            }
            function setStatus(){
                showLoader(true);
                status1 = document.getElementById('status').value;
                FB.api(
                  {
                    method: 'status.set',
                    status: status1
                  },
                  function(response) {
                    if (response == 0){
                        alert('Your facebook status not updated. Give Status Update Permission.');
                    }
                    else{
                        alert('Your facebook status updated');
                    }
                    showLoader(false);
                  }
                );
            }
            function showLoader(status){
                if (status)
                    document.getElementById('loader').style.display = 'block';
                else
                    document.getElementById('loader').style.display = 'none';
            }
        </script>
        <h3>New JavaScript SDK & OAuth 2.0 based FBConnect Tutorial | Thinkdiff.net</h3>
        <button id="fb-auth">Login</button>
        <div id="loader" style="display:none">
            <img src="ajax-loader.gif" alt="loading" />
        </div>
        <br />
        <div id="user-info"></div>
        <br />
        <div id="debug"></div>
        <div id="other" style="display:none">
            <a href="#" onclick="showStream(); return false;">Publish Wall Post</a> |
            <a href="#" onclick="share(); return false;">Share With Your Friends</a> |
            <a href="#" onclick="graphStreamPublish(); return false;">Publish Stream Using Graph API</a> |
            <a href="#" onclick="fqlQuery(); return false;">FQL Query Example</a>
            <br />
            <textarea id="status" cols="50" rows="5">Write your status here and click 'Status Set Using Legacy Api Call'</textarea>
            <br />
            <a href="#" onclick="setStatus(); return false;">Status Set Using Legacy Api Call</a>
        </div>
    </body>
</html>

Additionally if you use PHP SDK 3.0 or this new way of javascript sdk to authenticate your site you can enable oAuth Migration in the application setting.

Hope it will help you to understand new javascript sdk.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s