Login with LinkedIn using JavaScript SDK

LinkedIn is world’s most popular social network for professionals. LinkedIn provides various API to enhance the sign-in experience on the web application. If you want to integrate login system on your website, Login with LinkedIn is an easiest and powerful way to do that. Sign in with LinkedIn feature allow users to log in with their LinkedIn account without creating a new account on your website. It helps to reduce time and cost to implement login system and get more sign-ups.

LinkedIn’s JavaScript SDK is a convenient way to implement user login with LinkedIn account on a single page without page refresh. In this tutorial, we will show you how to integrate Login with LinkedIn using JavaScript SDK. In this example script, we will authenticate the user with their LinkedIn account and retrieve the user profile data from LinkedIn using JavaScript SDK.

Create LinkedIn App

You need to register an application with LinkedIn for using JavaScript SDK. If you have not already registered, create a LinkedIn application first.
Do you want a step-by-step guide to creating a LinkedIn app? Go through this tutorial – How to Create LinkedIn App

If you have an existing application, do the following settings to use JavaScript SDK.

  • Select your App on My Apps page.
  • Click the JavaScript link from left menu panel.
  • Under the JavaScript Settings specify the Valid SDK Domains. Click the Update button.
    linkedin-login-javascript-sdk-app-valid-domain-settings-codexworld

    Note that: To test on localhost add this domain – http://localhost

Go to the Authentication page, copy and keep the Client ID for later use in the script.

linkedin-login-javascript-sdk-app-client-id-codexworld

JavaScript

In order to use SDK functionality, include the LinkedIn JavaScript library in your web page and specify your LinkedIn App API Key.

<script type="text/javascript" src="//platform.linkedin.com/in.js">
    api_key: App_Client_ID
    authorize: true
    onLoad: onLinkedInLoad
    scope: r_basicprofile r_emailaddress
</script>

The following JavaScript methods are used to integrate LinkedIn login process on a single page.

  • onLinkedInLoad() – Setup an event listener to make an API call once auth is complete.
  • getProfileData() – Use the API call to request the member’s profile data.
  • displayProfileData() – Display member profile information in the webpage.
  • logout() – Log the user out from LinkedIn account.
  • removeProfileData() – Hide profile information from the web page.
<script type="text/javascript">
    // Setup an event listener to make an API call once auth is complete
    function onLinkedInLoad() {
        IN.Event.on(IN, "auth", getProfileData);
    }
    
    // Use the API call wrapper to request the member's profile data
    function getProfileData() {
        IN.API.Profile("me").fields("id", "first-name", "last-name", "headline", "location", "picture-url", "public-profile-url", "email-address").result(displayProfileData).error(onError);
    }

    // Handle the successful return from the API call
    function displayProfileData(data){
        var user = data.values[0];
        document.getElementById("picture").innerHTML = '<img src="'+user.pictureUrl+'" />';
        document.getElementById("name").innerHTML = user.firstName+' '+user.lastName;
        document.getElementById("intro").innerHTML = user.headline;
        document.getElementById("email").innerHTML = user.emailAddress;
        document.getElementById("location").innerHTML = user.location.name;
        document.getElementById("link").innerHTML = '<a href="'+user.publicProfileUrl+'" target="_blank">Visit profile</a>';
        document.getElementById('profileData').style.display = 'block';
    }

    // Handle an error response from the API call
    function onError(error) {
        console.log(error);
    }
    
    // Destroy the session of linkedin
    function logout(){
        IN.User.logout(removeProfileData);
    }
    
    // Remove profile data from page
    function removeProfileData(){
        document.getElementById('profileData').remove();
    }
</script>

HTML

Create the Sign In with LinkedIn button.

<!-- sign in with linkedin button -->
<script type="in/Login"></script>

Display the member’s profile data (picture, first name, last name, email address, headline, location, and public profile URL). Also, a logout link will be provided for logout the user from the LinkedIn account.

<!-- display profile info -->
<div id="profileData" style="display: none;">
    <p><a href="javascript:void(0);" onclick="logout()">Logout</a></p>
    <div id="picture"></div>
    <div class="info">
        <p id="name"></p>
        <p id="intro"></p>
        <p id="email"></p>
        <p id="location"></p>
        <p id="link"></p>
    </div>
</div>

Login with LinkedIn using PHP

Save User Data to the Database (jQuery, Ajax, PHP, and MySQL)

After user logged in via LinkedIn JavaScript SDK, if you want to store the user profile information into the MySQL database, follow the below steps.

Create Database Table
To store user profile information a table needs to be created in the database. The following SQL creates a users table with some basic columns in the MySQL database.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `oauth_provider` enum('','linkedin') COLLATE utf8_unicode_ci NOT NULL,
 `oauth_uid` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `first_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `last_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `location` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `picture` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `profile_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

JavaScript
We will use jQuery and Ajax to send the user profile data to the PHP script (saveUserData.php) and insert the profile information into the MySQL database.

At first, include the jQuery library.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

The saveUserData() function posts the user profile data to saveUserData.php file using jQuery Ajax.

// Save user data to the database
function saveUserData(userData){
    $.post('saveUserData.php', {oauth_provider:'linkedin',userData: JSON.stringify(userData)}, function(data){ return true; });
}

Place the saveUserData() function in the displayProfileData() method to save user profile data in the database.

// Handle the successful return from the API call
function displayProfileData(data){
    var user = data.values[0];
    document.getElementById("picture").innerHTML = '<img src="'+user.pictureUrl+'" />';
    document.getElementById("name").innerHTML = user.firstName+' '+user.lastName;
    document.getElementById("intro").innerHTML = user.headline;
    document.getElementById("email").innerHTML = user.emailAddress;
    document.getElementById("location").innerHTML = user.location.name;
    document.getElementById("link").innerHTML = '<a href="'+user.publicProfileUrl+'" target="_blank">Visit profile</a>';
    document.getElementById('profileData').style.display = 'block';
    
    // Save user data
    saveUserData(user);
}

Database Configuration (dbConfig.php)
The dbConfig.php file is used to connect and select the MySQL database.

<?php
// Database configuration
$dbHost     "localhost";
$dbUsername "root";
$dbPassword "*****";
$dbName     "codexworld";

//Create connection and select DB
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);

if (
$db->connect_error) {
    die(
"Unable to connect database: " $db->connect_error);
}
?>

Insert User Data to the Database (saveUserData.php)
At first, JSON data would be decoded and stored into PHP variable ($userData). Before inserting the data in the users table, we will check whether the user already exists in the database and insert or update the user data.

<?php
//Load the database configuration file
include 'dbConfig.php';

//Convert JSON data into PHP variable
$userData json_decode($_POST['userData']);
if(!empty(
$userData)){
    
$oauth_provider $_POST['oauth_provider'];
    
    
//Check whether user data already exists in database
    
$prevQuery "SELECT * FROM users WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$userData->id."'";

    
$prevResult $db->query($prevQuery);
    if(
$prevResult->num_rows 0){
        
//Update user data if already exists
        
$query "UPDATE users SET first_name = '".$userData->firstName."', last_name = '".$userData->lastName."', email = '".$userData->emailAddress."', location = '".$userData->location->name."', picture = '".$userData->picture->pictureUrl."', profile_url = '".$userData->publicProfileUrl."', modified = '".date("Y-m-d H:i:s")."' WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$userData->id."'";
        
$update $db->query($query);
    }else{
        
//Insert user data
        
$query "INSERT INTO users SET oauth_provider = '".$oauth_provider."', oauth_uid = '".$userData->id."', first_name = '".$userData->firstName."', last_name = '".$userData->lastName."', email = '".$userData->emailAddress."', location = '".$userData->location->name."', picture = '".$userData->pictureUrl."', profile_url = '".$userData->publicProfileUrl."', created = '".date("Y-m-d H:i:s")."', modified = '".date("Y-m-d H:i:s")."'";
        
$insert $db->query($query);
    }
}
die(
'success');
?>

Conclusion

LinkedIn JavaScript SDK is very useful when you want to implement login system on a single page without page refresh. Using our example code you can easily retrieve the user’s profile information from LinkedIn and store data in your database. If you want to use PHP client library instead of JavaScript SDK, follow this tutorial – Login with LinkedIn using PHP

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

RELATED TUTORIALS

Leave a reply

keyboard_double_arrow_up