Login with Instagram using JavaScript SDK

Instagram Login through API is the easiest way to integrate the 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 verification that used to actualize Instagram Login usefulness on the website. Client-side confirmation is easy to use approach to incorporate Instagram Login utilizing 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 verification requires an access_token to get the client profile information from Instagram. In this instructional exercise, we will tell you the best way to execute Login with Instagram utilizing JavaScript SDK and store the Instagram profile information in the database utilizing jQuery, Ajax, PHP, and MySQL.

Instagram Client ID

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

On the off chance that you don't as of now register your Instagram Application, pursue this well-ordered instructional exercise to enlist a new Client ID.

Functionality Overview

The accompanying usefulness will be actualized for social login with Instagram utilizing JavaScript API.

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

Create Database Table

To store the client's profile information, a table needs in the database. The accompanying SQL makes a clients table with some fundamental fields in the MySQL database.

CREATE TABLE `users` (
 `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,
) 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 on the web page.
  • Save profile data in the database.
  • Store user data in the session using the 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
                    accessToken = popup.location.hash.slice(14); //slice #access_token= from string
                    if(callback != undefined && typeof callback == 'function'){
            catch(evt) {
                // Permission denied
        }, 100);

function login_callback(){
    //alert("You are successfully logged in! Access Token: "+accessToken);
        type: "GET",
        dataType: "jsonp",
        url: "https://api.instagram.com/v1/users/self/?access_token="+accessToken,
        success: function(response){
            // Change button and show status
            $('.btn-text').text('Logout from Instagram');
            $('#status').text('Thanks for logging in, ' + response.data.username + '!');
            // Display user data
            // Save user data
            // Store user data in sessionStorage
            sessionStorage.setItem("userLoggedIn", "1");
            sessionStorage.setItem("provider", "instagram");
            sessionStorage.setItem("userData", JSON.stringify(response.data));

The instagramLogin() a function is used to authenticate with an Instagram account. The client ID and redirect URL need to be specified in the authenticateInstagram() function.

// Authenticate instagram
function instagramLogin() {
        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){

Instagram ID: '+userData.id+'

Name: '+userData.full_name+'

Picture: +userData.profile_picture+'"/>

Instagram Profile: +userData.username+'">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
    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
            $('.btn-text').text('Logout from Instagram');
            $('#status').text('Thanks for logging in, ' + userData.username + '!');
            // Display user data
        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
    $('.btn-text').text('Login with Instagram');
    $('#status').text('You have successfully logout from Instagram.');

HTML Code:
Initially, the Login with the Instagram button will be displayed. By clicking the button, an 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

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

// Database configuration
$dbHost     "localhost";
$dbUsername "root";
$dbPassword "root";
$dbName     "dbname";

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

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

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
// 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);
$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);
// 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);

Related Articles

Comments 0