LinkedIn is a top-rated social network for professionals. LinkedIn gives you a lot of APIs to increase the sign-in experience on the web application. If you want to integrate a login system on your website, Login with LinkedIn JavaScript SDK is the easiest and powerful way to do that. Sign in with the LinkedIn feature. It allows users to log in with their LinkedIn account without creating a new account on their website. It helps to reduce the time and cost to implement the login system and get more sign-ups.
LinkedIn’s JavaScript SDK is a suitable way to achieve a user login with a LinkedIn account on a single page without refreshing the page. In this tutorial, we will explain to you how to unified login with LinkedIn using JavaScript SDK. For instance, we will authenticate the user with their LinkedIn account and get user profile data from LinkedIn using the JavaScript SDK.
Create a LinkedIn App
You have to register an application with LinkedIn for using JavaScript SDK. If you have not already registered, create a LinkedIn application first.
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 the left menu panel.
- Down towards the JavaScript, Settings specify the Valid SDK Domains. Now, click on the Update button.
Note: To test on localhost add this domain – http://localhost
Now, go to the Authentication page, copy and keep the Client ID to use it later in the script.
JavaScript
To use the 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>
If you want to use the following javascript methods to unified the 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 data on the webpage.
logout()
– Log the user out from the 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 the LinkedIn button.
<!-- sign in with linkedin button --> <script type="in/Login"></script>
Display the member’s profile data (picture, last name, headline, first name, email address, location, and public profile URL). Besides, You will get a logout link 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>
Save User Data to the Database (jQuery, Ajax, PHP, and MySQL)
After a user logged in via the LinkedIn JavaScript SDK, if you want to store user profile information in the MySQL database, follow the steps given below.
Create Database Table
It would be best if you created a table in the Database to store users
profile information. The following SQL creates a user table with some essential columns in the MySQL database.
JavaScript
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 user profile data to the PHP script (saveUserData.php
) and insert profile information into a MySQL database.
Firstly, 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; }); }
And then, 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)
You have to use the dbConfig.php file 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)
Firstly, we will decode the JSON data and will keep it into a PHP variable ($userData). Before inserting the data in the user’s table, we will check whether the user already exists in the Database and add 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
The LinkedIn JavaScript SDK is beneficial when you want to implement a login system on a page without refreshing the page. Using our example code, you can quickly obtain user profile data from LinkedIn and store data in your Database. Moreover, if you want to use PHP client library instead of JavaScript SDK, follow this tutorial – Login with LinkedIn using PHP
Also, read our previous blog- Login with GitHub OAuth API using PHP