Search code examples
javascriptphpinstagraminstagram-apiinstafeedjs

How to use instafeed.js to get logged in users images


I'm building an application where users can click a button to show all of their Instagram images on a page, but in order to do that I need userId and accessToken. How do I get these?

NOTE: If it makes any difference: I'm not trying to get just my own images, but anyone who uses my app to log into their account.

I have this code:

<script>
var feed = new Instafeed ({
    get: "user",
    userId: ,
    accessToken: ""
});
feed.run();
</script>

<div id="instafeed"></div>

And I get a verification code by clicking on a link (note I removed cliend_id and redirect_uri):

    <a href="https://api.instagram.com/oauth/authorize/?client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&response_type=code">Get Instagram images</a>

Then this returns a code like '1251251...' which I grab with GET, but after that what do I do? How do I get userId and accesToken from this?

I'm not sure if I'm on the right track, but any help would be appreciated!


Solution

  • Answering my own question, as I figured it out:

    $url = 'https://api.instagram.com/oauth/access_token';
    
    $data = array(
        'client_id' => $clientId,
        'client_secret' => $clientSecret,
        'grant_type' => 'authorization_code',
        'redirect_uri' => $redirectUri,
        'code' => $code
    );
    
    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data),
        ),
    );
    
    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    

    $clientId, $clientSecret and $redirectUri are taken from: https://instagram.com/developer/clients/manage/

    $code is the code from your url and $result contains the userId and accessToken if successful.

    Thanks to: How do I send a POST request with PHP?