Main Aim: To get access_token so I may display my Instagram feed on the website.
Currently, to get an access token, we go to this url and click on Authorize to get the code, further exchanged for access_token.
https://api.instagram.com/oauth/authorize
?client_id={app-id}
&redirect_uri={redirect-uri}
&scope=user_profile,user_media
&response_type=code
Now, if I am writing a PHP-curl script to send this access_token and get my posts, how will I get an access token each time, I can not really click on authorize every time my API requests data, further, clicking authorize every 60 days is also not a long term solution for me.
So I was hoping if there was a way ( that I could call this URL, and get authorization code directly? )
So far my script:
$authURL = "https://api.instagram.com/oauth/authorize
?client_id=$client_id
&redirect_uri=$redirect_uri
&scope=user_profile,user_media
&response_type=code";
//STEP 1, GET THE AUTHORIZATION CODE (i am stuck here, how to get code from only PHP,
//without external clicks..)
//https://www.redirecturl.com?code=AQgw#_
$authorization_code = '48FduaX0g.....VZIj';
//STEP 2 GIVE THE CODE FOR TOKEN
$url = 'https://api.instagram.com/oauth/access_token';
$myjson = "
{'client_id': $client_id,
'client_secret': $client_secret,
'grant_type':'authorization_code',
'redirect_uri':$redirect_uri,
'code': $authorization_code
}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $myjson);
$result = curl_exec($ch);
curl_close($ch);
$insta_details = json_decode($result);
echo $insta_details['access_token'];
curl -X GET \
'https://graph.instagram.com/17841405793187218/media?access_token=IGQVJ...'
The authorization step requires human interaction to login with a username / password. So there is no way to do that via only PHP.
But if you just need to display a feed on a website using PHP, you can use this package: https://packagist.org/packages/espresso-dev/instagram-basic-display-php
Grab the code
in the callback after auth:
$code = $_GET['code'];
And then use this following methods:
getOAuthToken()
to het the initial tokengetLongLivedToken()
to get the long-lived token valid for 60 daysStore the long-lived token so that can be used to retrieve the posts and just call the refreshToken()
method every 50 days or so to refresh the token in the background and update the token you're using.