Integrating Instagram Graph API in PHP or Laravel

In this article we learned Instagram Basic Display API Setup so read this article before proceed. Now we are integrating instagram graph api in php or laravel.

Step 1 : Authenticate the Test User

Construct the Authorization Window URL below, replacing {app-id} with your Instagram app’s ID (from the App Dashboard > Products > Instagram > Basic Display > Instagram App ID field) and {redirect-uri} with your website URL that you provided in Valid OAuth Redirect URIs.

https://api.instagram.com/oauth/authorize?client_id={app-id}&redirect_uri={redirect-uri}&scope=user_profile,user_media&response_type=code

Authenticate your Instagram test user by signing into the Authorization Window. Then click Authorize to grant your app access to your profile data. Upon success, the page will redirect you to the redirect URI you included in the previous step and append an Authorization Code. For example:

https://socialsizzle.herokuapp.com/auth/?code=AQDp3TtBQQ…#_

Note that #_ has been appended to the end of the redirect URI, but it is not part of the code itself. Copy the code (without the #_ portion) so you can use it in the next step.

Step 2 : Create the access token and get the instagram media

First of all create a route get-photos in your web.php file inside the routes directory.

Route::get('/get-photos', 'IGController@getMedia');
Route::get('/ig-redirect-uri', 'IGController@igRedirectUri'); //this is the url earlier we added in app setup in facebook developer console

Now create a controller IGController.php and add the below code.

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class IGController extends Controller
{

	public $authData;

	public $auth_table = 'ig_auth_data';

	public function __construct(){

	}

	public function generateIGToken(){

		$ig_atu = "https://api.instagram.com/oauth/access_token";

		$ig_data = [];

		$ig_data['client_id'] = "293856835968089"; //replace with your Instagram app ID

		$ig_data['client_secret'] = "63a0fad18c422116c7f861fbf683a0"; //replace with your Instagram app secret

		$ig_data['grant_type'] = 'authorization_code';

		$ig_data['redirect_uri'] = url('/'). '/ig-redirect-uri'; //create this redirect uri in your routes web.php file

		$ig_data['code'] = "JSDFRG54TERYGSDGDS4RWEFS"; //this is the code you received in step 1 after app authorization

		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, $ig_atu);

		curl_setopt($ch, CURLOPT_POST, 1);

		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($ig_data));

		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		$ig_auth_data = curl_exec($ch);

		curl_close ($ch);

		$ig_auth_data = json_decode($ig_auth_data, true);

		if (!isset($ig_auth_data['error_message'])) {

			$this->authData['access_token'] = $ig_auth_data['access_token'];

			$this->authData['user_id'] = $ig_auth_data['user_id'];


			DB::table($this->auth_table)->insert([
				'access_token' 	=> $this->authData['access_token'],
				'user_id'		=> $this->authData['user_id'],
				'valid_till'	=> time(),
				'expires_in'	=> 3600,
				'created_at'	=> date('Y-m-d H:i:s')
			]);

		}

	}


	public function refreshIGToken($short_access_token){

		$client_secret = "63a0fad8218c422116c7f861fbf683a0"; //replace with your Instagram app secret

		$ig_rtu = 'https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_secret='.$client_secret.'&access_token='.$short_access_token;

		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, $ig_rtu);
		
		curl_setopt($ch, CURLOPT_HEADER, 0);

		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		$ig_new = curl_exec($ch);

		curl_close ($ch);

		$ig_new = json_decode($ig_new, true);

		if (!isset($ig_new['error'])) {

			$this->authData['access_token'] = $ig_new['access_token'];

			$this->authData['expires_in'] = $ig_new['expires_in'];

			DB::table($this->auth_table)
			->where('access_token', '<>', '')
			->update([
				'access_token'	=> $ig_new['access_token'],
				'valid_till'	=> time(),
				'expires_in'	=> $ig_new['expires_in']
			]);

		}

	}


	public function getMedia(){

		/*check token available and valid*/

		$igData = DB::table($this->auth_table);

		if ($igData->count() > 0) {

			$igDataResult = $igData->first();

			$curTimeStamp = time();

			if (($curTimeStamp-$igDataResult->valid_till) >= $igDataResult->expires_in) {
				
				$this->refreshIGToken($igDataResult->access_token);

			}else{

				$this->authData['access_token'] = $igDataResult->access_token;
				$this->authData['user_id'] = $igDataResult->user_id;

			}

		}else{
			$this->generateIGToken();
		}

		/*check token available and valid*/

		$ig_graph_url = 'https://graph.instagram.com/me/media?fields=id,media_type,media_url,username,timestamp,caption&access_token='.$this->authData['access_token'];

		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, $ig_graph_url);
		
		curl_setopt($ch, CURLOPT_HEADER, 0);

		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		$ig_graph_data = curl_exec($ch);

		curl_close ($ch);

		$ig_graph_data = json_decode($ig_graph_data, true);

		$ig_photos = [];

		if (!isset($ig_graph_data['error'])) {

			foreach ($ig_graph_data['data'] as $key => $value) {

				if ($value['media_type'] == 'IMAGE') {
					$ig_photos[] = $value['media_url'];
				}
				
			}

		}

		//use this if want json response
		//return response()->json($igPhotos);

		return $igPhotos;

	}

	public function igRedirectUri(){
		//write your code here to check the response from oauth redirect uri which you setup in facebook developer console
	}

}

After adding the above code replace {app-id}{app-secret}{redirect-uri}, and {code} with your Instagram app ID, Instagram app secret, your redirect URI, and the code we sent you during authorization. Now open the route get-photos in your browser and you will get your photos of instagram in the array form.

That’s it now you can list your instagram photos or videos in your laravel or php website. And before integrating instagram graph api in php or laravel you must read Instagram Basic Display API Setup to get your {app-id}{app-secret}{redirect-uri}.

To learn about curl in php read the article how to run curl get or post api in php.

If you want more tutorials about APIs then visit our APIs page regularly. Subscribe Your Email and follow us on facebooktwittertumblrlinkedin and if you like this article then share this.