JavaScript

Instagram: Like and Unlike

Step 1: Register A New Client here.

Fill in:

Instagram fill form

Copy the CLIENT ID you get after you submit the form.

 

Step 2: Prompt to get Access Token from Users, and Request for Likes with PHP

So the onclick event I have:

$('#social').on 'click', '.instagram .likes', ->
  mediaId = $(this).data('media-id')
  if !$(this).hasClass('liked')
    $(this).addClass('liked')
    Instagram.likePost mediaId, => console.log 'liked'
  else
    $(this).removeClass('liked')
    Instagram.unlikePost mediaId, => console.log 'unliked'

And inside Instagram.coffee:

Instagram =
  hasAccessToken: ->
    localStorage.getItem('accessToken')
 
  getAccessToken: ->
    clientId = "4axxxxa41axxxxda9cxxxx54axxxxb00"
    redirectUri = "http://localhost/redirect.html" # redirect to this page once the authentication is done
    url = "https://instagram.com/oauth/authorize/?client_id=#{ clientId }&response_type=token&scope=likes&redirect_uri=#{ redirectUri }"
    window.open url, 'authenticate', "width=800,height=700"
 
   likeActions: (mediaId, like, done) ->
     if !Modernizr.localstorage
       console.log "doesn't support localstorage!"
       return
 
     if !@hasAccessToken()
       console.log 'no access token'
       @getAccessToken()
     else
       console.log 'has access token'
       accessToken = localStorage.getItem('accessToken')
       url = "./instagram/index.php?like=#{ like }&mediaId=#{ mediaId }&token=#{ accessToken }"
       $.ajax(url: url, type: 'GET', complete: done)
 
  likePost: (mediaId, done) ->
    @likeActions(mediaId, true, done)

  unlikePost: (mediaId, done) ->
    @likeActions(mediaId, false, done)

And redirect.html is where the page goes when the authentication is done:

<!DOCTYPE html>
<html>
<head>
<title>Redirect</title>
</head>
<body>
<script>
    accessToken = location.href.replace(/(.*)access\_token\=/, '')
    localStorage.setItem('accessToken', accessToken)
    window.close() // close window after storing accessToken in localStorage
</script>
</body>
</html>

 

Step 3: Edit index.php

This is where the requests are wrapped and handled:

<?php

require 'instagram.class.php';
// get the file here: http://cosenary.github.io/Instagram-PHP-API/

// initialize class
$instagram = new Instagram(array(
  'apiKey' => '4axxxxa41axxxxda9cxxxx54axxxxb00',
  'apiSecret' => '8c0xxxxxx44845xxxxxxxe43axxxfeaf'
));

$like = $_GET['like'];
$token = $_GET['token'];
$media_id = $_GET['mediaId'];

$instagram->setAccessToken($token);

if ($like === "true") {
  $instagram->likeMedia($media_id);
} else {
  $instagram->deleteLikedMedia($media_id);
}

?>

 

Reference:

  • http://jelled.com/instagram/access-token
  • http://cosenary.github.io/Instagram-PHP-API/
  • http://instagram.com/developer/endpoints/likes/
  • http://stackoverflow.com/questions/20929799/instagram-you-cannot-like-this-media/25417365#25417365
Standard