Hướng dẫn instagram login javascript sdk
Show 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 IDBefore 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 OverviewThe following functionality will be implemented for social login with Instagram using JavaScript API.
Create Database TableTo 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 SDKJavaScript Code: <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.
// 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 // Authenticate instagram function instagramLogin() { authenticateInstagram( 'InstagramClientID', 'InstagramRedirectURI', login_callback //optional - a callback function ); return false; } The // Save user data to the database function saveUserData(userData){ $.post('userData.php', {oauth_provider:'instagram',userData: JSON.stringify(userData)}, function(data){ return true; }); } The // Display user profile details function displayUserProfileData(userData){ $('#userData').html(' 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 // 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: <div id="status">div> <a href="javascript:void(0)" onclick="instagramLogin();">Login with Instagrama> <div id="userData">div> Store Profile Data in the Database
// Database configuration
// Load the database configuration file ConclusionOur 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 |