Main Contents:

Key Summary

This article provides a step-by-step guide on implementing Facebook Login using the JavaScript SDK v2.1, enabling developers to integrate social login functionality into their applications. It includes code snippets and explanations for setting up the SDK, handling user authentication, and fetching user data. Key points include:

  • Purpose:
    • Demonstrates how to use the Facebook JavaScript SDK v2.1 to implement a login feature, allowing users to authenticate via their Facebook accounts and retrieve specific user information (e.g., email, name, friend lists).
  • Key Code Components:
    • SDK Initialization:
      javascript
      CollapseWrapRun
      Copy

window.fbAsyncInit = function() {

 FB.init({

   appId: ‘YOUR_APP_ID’,

   cookie: true, // Enable cookies for session access

   xfbml: true, // Parse social plugins

   version: ‘v2.1’ // Use API version 2.1

 });

};

(function(d, s, id) {

 var js, fjs = d.getElementsByTagName(s)[0];

 if (d.getElementById(id)) return;

 js = d.createElement(s); js.id = id;

 js.src = “//connect.facebook.net/en_US/sdk.js”;

 fjs.parentNode.insertBefore(js, fjs);

  • }(document, ‘script’, ‘facebook-jssdk’));
    • Loads and initializes the Facebook SDK with the app ID, enabling cookies and social plugins.
  • Login Function:
    javascript
    CollapseWrapRun
    Copy

function fb_login() {

 FB.login(function(response) {

   if (response.authResponse) {

     console.log(‘Welcome! Fetching your information…. ‘);

     access_token = response.authResponse.accessToken; // Get access token

     user_id = response.authResponse.userID; // Get FB UID

     FB.api(‘/me?fields=id,name,friendlists’, function(response) {

       user_email = response.email; // Get user email

       console.log(response);

       alert(user_email);

       // Store data in database

     });

   } else {

     console.log(‘User cancelled login or did not fully authorize.’);

   }

 }, {

   scope: ‘publish_stream,email,read_friendlists’ // Requested permissions

 });

  • }
    • Initiates the login process, retrieves the access token and user ID, and fetches specific fields (id, name, friendlists) via the FB.api call.
    • Handles success (user data retrieved) and failure (user cancels or denies permissions) cases.
  • Permissions and Scope:
    • Default permissions: email, public_profile, user_friends.
    • Additional permissions (e.g., publish_stream, read_friendlists) require Facebook App Review to function fully.
    • The scope parameter specifies permissions requested during login, which users must approve.
  • Implementation Details:
    • The FB.api call uses query parameters (fields=id,name,friendlists) to limit returned data for efficiency.
    • The code is embedded in an HTML page with a clickable image to trigger the login function.
    • Example app ID (572516629527309) is provided for demonstration, but developers must use their own app ID from the Facebook Developer Portal.
  • Support and Stability:
    • Facebook guarantees stable support for API v2 for at least two years, ensuring reliability for developers.
  • Full Working Code:
    • Combines SDK initialization, login function, and an HTML interface with a login button (<a href=”#” onclick=”return fb_login();”>).
    • Displays user email via an alert and logs response data for debugging or database storage.
  • InApps Insight:
    • The Facebook Login API V2 simplifies social authentication, enhancing user experience in e-commerce and other applications.
    • InApps Technology can integrate this functionality into client projects, streamlining user onboarding and leveraging secure, scalable social login solutions to boost engagement and functionality.
Read More:   Update 12 Must-Have Features to Make Your Real Estate App Successful in 2022

Login with Facebook API V2 is an article sent to you by the InApps editorial team. Hope readers will have more useful knowledge at www.inapps.net

You are viewing the article: Login with Facebook API V2

In this blog, we will explain how to implement login with facebook using Javascript SDK v2.1.

window.fbAsyncInit = function() {
FB.init({
appId : ‘YOUR_APP_ID’,
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : ‘v2.1’ // use version 2.1
});
};
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = “//connect.facebook.net/en_US/sdk.js”;
fjs.parentNode.insertBefore(js, fjs);
}(document, ‘script’, ‘facebook-jssdk’));

By help of above code, we can load sdk and initialize required parameters.

We have created a function which will call facebook login API, fetch response and allows developer to write code to handle different success/failure cases.

function fb_login(){
FB.login(function(response) {
if (response.authResponse) {
console.log(‘Welcome! Fetching your information…. ‘);
//console.log(response); // dump complete info
access_token = response.authResponse.accessToken; //get access token
user_id = response.authResponse.userID; //get FB UID
FB.api(‘/me?fields=id,name,friendlists’, function(response) {
user_email = response.email; //get user email
console.log(response);
alert(user_email);
// you can store this data into your database
});
} else {
//user hit cancel button
console.log(‘User cancelled login or did not fully authorize.’);
}
}, {
scope: ‘publish_stream,email,read_friendlists’
});
}

In the above example, we have passed a scope parameter, by which Facebook will identify and ask all required permissions to user.

Facebook by default gives access to email, public_profile and user_friends permission. If the developer wants to get other information, he has to get them reviewed from Facebook for the app using the App settings tab. Unless it is reviewed and approved by Facbook, this parameter will not work as expected.

In FB.api, we have passed query parameters. FB will only return these many values in response if passed.

Facebook has announced stable support for at least 2 years for API v2.

Read More:   Update 3 Web Development Trends to Watch-Out for in 2016-17

Below is the full working code.

<title>Facebook Login JavaScript Example</title>
<meta charset=”UTF-8″>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : ‘572516629527309’,
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : ‘v2.1’ // use version 2.1
});
};
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = “//connect.facebook.net/en_US/sdk.js”;
fjs.parentNode.insertBefore(js, fjs);
}(document, ‘script’, ‘facebook-jssdk’));
function fb_login(){
FB.login(function(response) {
if (response.authResponse) {
console.log(‘Welcome! Fetching your information…. ‘);
//console.log(response); // dump complete info
access_token = response.authResponse.accessToken; //get access token
user_id = response.authResponse.userID; //get FB UID
FB.api(‘/me?fields=id,name,friendlists’, function(response) {
user_email = response.email; //get user email
console.log(response);
alert(user_email);
// you can store this data into your database
});
} else {
//user hit cancel button
console.log(‘User cancelled login or did not fully authorize.’);
}
}, {
scope: ‘publish_stream,email,read_friendlists’
});
}
</script>
<a href=”#” onclick=”return fb_login();”>
<img src=”http://www.myclientpage.com/images/fb_login.gif”>
</a>
<div id=”status”></div>

Follow this to make sure you’ve got Login with Facebook API V2. Save and share with those around you these extras.
To learn more about ECOMMERCE DEVELOPMENT

Contact us:
www.inapps.net

Rate this post
As a Senior Tech Enthusiast, I bring a decade of experience to the realm of tech writing, blending deep industry knowledge with a passion for storytelling. With expertise in software development to emerging tech trends like AI and IoT—my articles not only inform but also inspire. My journey in tech writing has been marked by a commitment to accuracy, clarity, and engaging storytelling, making me a trusted voice in the tech community.

Let’s create the next big thing together!

Coming together is a beginning. Keeping together is progress. Working together is success.

Let’s talk

Get a custom Proposal

Please fill in your information and your need to get a suitable solution.

    You need to enter your email to download

      Success. Downloading...