Hướng dẫn instagram login javascript sdk

Instagram Login through API is the easiest way to integrate login system in the web application. Login with Instagram allows the user to log into the website with their Instagram account without registration. Instagram provides API or SDK for server-side and client-side authentication that used to implement Instagram Login functionality on the website. Client-side authentication is a user-friendly way to integrate Instagram Login using JavaScript.

The Instagram API allows the user to authenticate with an Instagram account from the web application. Using JavaScript SDK, you can implement the user login system with Instagram on a single page without page refresh. The Instagram API authentication require an access_token to get the user profile data from Instagram. In this tutorial, we will show you how to implement Login with Instagram using JavaScript SDK and store the Instagram profile data in the database using jQuery, Ajax, PHP, and MySQL.

Instagram Client ID

Before get started to implement Instagram Login with JavaScript API on the website, you need a Client ID. This Client ID needs to be registered on Instagram Developer Panel.

If you don’t already register your Instagram Application, follow this step-by-step tutorial to register new Client ID – How to register Instagram App and create Client ID

Functionality Overview

The following functionality will be implemented for social login with Instagram using JavaScript API.

  • Authenticate with the Instagram account.
  • Retrieve the user’s profile data from Instagram.
  • Save profile data in the database using PHP and MySQL.
  • Display the profile data of the user.

Create Database Table

To store the user’s profile data, a table needs in the database. The following SQL creates a users table with some basic 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 jQuery and Ajax, include the jQuery library first.

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

The following JavaScript code 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.
  • 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 instagramLogin() function is used to authenticate with Instagram account. The client ID and redirect URL need to be specified 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() function show the retrieved profile information to the user.

// Display user profile details
function displayUserProfileData(userData){
    $('#userData').html('

Instagram ID: '+userData.id+'

Name: '+userData.full_name+'

Picture:

Instagram Profile: click to view profile

'
); }

After the page refresh, 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:
Initially, the Login with Instagram button will be displayed. By clicking the button, Instagram authentication popup will appear. If the login is successful, the login status and the user profile data will be shown.


<div id="status">div>


<a href="javascript:void(0)" onclick="instagramLogin();">Login with Instagrama>


<div id="userData">div>

Store Profile Data in the Database

dbConfig.php
The dbConfig.php file is used to connect and select the database.

// 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
The posted JSON data is decoded using json_decode() function in PHP. Based on the oauth_provider and oauth_uid, we will check whether the user already exists in the database and insert or update the user data into the users table using PHP and MySQL.

// 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 example code helps you to integrate Instagram login in the website without page refresh. The user can login with their Instagram account in 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.

Login with Facebook using JavaScript SDK

Are you want to get implementation help, or modify or enhance the functionality of this script? Submit Paid Service Request

If you have any questions about this script, submit it to our QA community - Ask Question