Instagram login via API is the easiest way to integrate the login system into a web application. Login with Instagram permits the user to log into the website with their own Instagram account. Instagram gives you an SDK or API for server-side and client-side authentication that used to implement Instagram Login functionality on the site. Client-side authentication is a user-friendly way to unify Instagram login using JavaScript.
The Instagram API permits the user to authenticate with an Instagram account from the web application. Therefore, By Using JavaScript SDK, you can implement the user login system with Instagram on a single page without page refresh. The Instagram API user needs an access_token to get user profile data from Instagram. In this article, we will explain to you how to implement Login with Instagram using JavaScript SDK and store Instagram profile data in the database using Ajax, jQuery, PHP, and MySQL.
Instagram Client ID
Before proceeding to implement Instagram Login with JavaScript API on the website, you need a Client ID. This Client ID requires to be registered on Instagram Developer Panel.
Functionality Overview
The following functions given below will be implemented for social Login with Instagram by using JavaScript API.
- Firstly, Authorise with the Instagram account.
- Secondly, retrieve the user’s profile data from Instagram.
- Thirdly, save profile data in the database using PHP and MySQL.
- And at last, display the profile data of the user.
Create Database Table
It would be best if you made a table in the database to store the user’s profile data. The following SQL creates a user table with some required fields in the MySQL database.
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `oauth_provider` enum('instagram','facebook','google','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, `gender` varchar(5) COLLATE utf8_unicode_ci NOT NULL, `picture` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `link` 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;
Login with Instagram using JavaScript SDK
JavaScript Code:
The example code uses Ajax and jQuery, include the jQuery library first.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The JavaScript code given below handles the Instagram authentication process.
- Authenticate with Instagram API.
- Get the access token via OAuth API.
- Retrieve profile data by the access token.
- Display user data in the web page.
- Save profile data in the database.
- Now, store user data in the session using window sessionStorage property.
// Access token is required to make any endpoint calls, // http://instagram.com/developer/endpoints/ var accessToken = null; var authenticateInstagram = function(instagramClientId, instagramRedirectUri, callback) { // Pop-up window size, change if you want var popupWidth = 700, popupHeight = 500, popupLeft = (window.screen.width - popupWidth) / 2, popupTop = (window.screen.height - popupHeight) / 2; // Url needs to point to instagram_auth.php var popup = window.open('instagram_auth.php', '', 'width='+popupWidth+',height='+popupHeight+',left='+popupLeft+',top='+popupTop+''); popup.onload = function() { // Open authorize url in pop-up if(window.location.hash.length == 0) { popup.open('https://instagram.com/oauth/authorize/?client_id='+instagramClientId+'&redirect_uri='+instagramRedirectUri+'&response_type=token', '_self'); } // An interval runs to get the access token from the pop-up var interval = setInterval(function() { try { // Check if hash exists if(popup.location.hash.length) { // Hash found, that includes the access token clearInterval(interval); accessToken = popup.location.hash.slice(14); //slice #access_token= from string popup.close(); if(callback != undefined && typeof callback == 'function'){ callback(); } } } catch(evt) { // Permission denied } }, 100); }; }; function login_callback(){ //alert("You are successfully logged in! Access Token: "+accessToken); $.ajax({ type: "GET", dataType: "jsonp", url: "https://api.instagram.com/v1/users/self/?access_token="+accessToken, success: function(response){ // Change button and show status $('.instagramLoginBtn').attr('onclick','instagramLogout()'); $('.btn-text').text('Logout from Instagram'); $('#status').text('Thanks for logging in, ' + response.data.username + '!'); // Display user data displayUserProfileData(response.data); // Save user data saveUserData(response.data); // Store user data in sessionStorage sessionStorage.setItem("userLoggedIn", "1"); sessionStorage.setItem("provider", "instagram"); sessionStorage.setItem("userData", JSON.stringify(response.data)); } }); }
The use of the instagramLogin()
the function requires specifying the client ID and the redirect URL in the authenticateInstagram()
function.
// Authenticate instagram function instagramLogin() { authenticateInstagram( 'InstagramClientID', 'InstagramRedirectURI', login_callback //optional - a callback function ); return false; }
The saveUserData()
function post the user’s profile data to the userData.php
file using jQuery and Ajax.
// Save user data to the database function saveUserData(userData){ $.post('userData.php', {oauth_provider:'instagram',userData: JSON.stringify(userData)}, function(data){ return true; }); }
The displayUserProfileData()the
function shows the retrieved profile information to the user.
// Display user profile details function displayUserProfileData(userData){ $('#userData').html('<p><b>Instagram ID:</b> '+userData.id+'</p><p><b>Name:</b> '+userData.full_name+'</p><p><b>Picture:</b> <img src="'+userData.profile_picture+'"/></p><p><b>Instagram Profile:</b> <a target="_blank" href="https://www.instagram.com/'+userData.username+'">click to view profile</a></p>'); }
After refreshing the page, if the user already logged in with Instagram, the user data will be retrieved from the sessionStorage.
// Get user data from session storage $(document).ready(function(){ if(typeof(Storage) !== "undefined"){ var userLoggedIn = sessionStorage.getItem("userLoggedIn"); if(userLoggedIn == '1'){ // Get user data from session storage var provider = sessionStorage.getItem("provider"); var userInfo = sessionStorage.getItem("userData"); var userData = $.parseJSON(userInfo); // Change button and show status $('.instagramLoginBtn').attr('onclick','instagramLogout()'); $('.btn-text').text('Logout from Instagram'); $('#status').text('Thanks for logging in, ' + userData.username + '!'); // Display user data displayUserProfileData(userData); } }else{ console.log("Sorry, your browser does not support Web Storage..."); } });
The instagramLogout()
function log out the user from the login session of Instagram.
// Logout from instagram function instagramLogout() { // Remove user data from sessionStorage sessionStorage.removeItem("userLoggedIn"); sessionStorage.removeItem("provider"); sessionStorage.removeItem("userData"); sessionStorage.clear(); $('.instagramLoginBtn').attr('onclick','instagramLogin()'); $('.btn-text').text('Login with Instagram'); $('#status').text('You have successfully logout from Instagram.'); $('#userData').html(''); }
HTML Code:
Firstly, the Login with the Instagram button will be shown. Secondly, by clicking the button, Instagram authentication popup will appear. At last, if the Login is successful, the login status and the user profile data will be shown.
<!-- Display login status --> <div id="status"></div> <!-- Instagram login or logout button --> <a href="javascript:void(0)" onclick="instagramLogin();">Login with Instagram</a> <!-- Display user profile data --> <div id="userData"></div>
Store Profile Data in the Database
dbConfig.php
To connect and select the database you have to use the dbConfig.php file is used.
<?php // Database configuration $dbHost = "localhost"; $dbUsername = "root"; $dbPassword = "root"; $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); } ?>
userData.php
It decodes the JSON data posted by using the json_decode () function in PHP. Based on oauth_provider and oauth_uid, we will check if the user already exists in the database and update the user data in the user’s table using PHP and MySQL.
<?php // Load the database configuration file include 'dbConfig.php'; // Decode json data $userData = json_decode($_POST['userData']); // If user data not empty if(!empty($userData)){ // User profile info $oauth_provider = $_POST['oauth_provider']; $full_name = $userData->full_name; $full_name_arr = explode(' ',$full_name); $first_name = !empty($full_name_arr[0])?$full_name_arr[0]:''; $last_name = !empty($full_name_arr[1])?$full_name_arr[1]:''; $link = 'https://www.instagram.com/'.$userData->username; // Check whether the user data already exists in the 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 = '".$first_name."', last_name = '".$last_name."', email = '', gender = '', picture = '".$userData->profile_picture."', link = '".$link."', 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 in the database $query = "INSERT INTO users SET oauth_provider = '".$oauth_provider."', oauth_uid = '".$userData->id."', first_name = '".$first_name."', last_name = '".$last_name."', email = '', gender = '', picture = '".$userData->profile_picture."', link = '".$link."', created = '".date("Y-m-d H:i:s")."', modified = '".date("Y-m-d H:i:s")."'"; $insert = $db->query($query); } } ?>
Conclusion
Our instance code will help you to integrate Instagram Login on the website without page refresh. The user can log in with their Instagram account on a single page without any page reload. If you want to extend the social login accounts availability, add Instagram to the existing social login system.
Also, read our previous blog- Login with Instagram using PHP