How To Drive More Engagement By Integrating Instagram API on PHP Website

0
Shares
How To Drive More Engagement By Integrating Instagram API on PHP Website
2.2 (44%) 5 votes

Recently, we’ve been working on a PHP project, and one of our clients wanted to display his Instagram pictures directly on a web page.

Do you think it is possible? Is there a way to do this?

Absolutely!

Instagram API is the solution. After successfully integrating it, we thought to share the process of integrating Instagram API. A complete step-by-step tutorial from scratch to help you learn how to integrate Instagram API in a PHP web page.

Let’s Get Started

First, go to https://instagram.com/developer/ and login to Instagram.

1

If you don’t have an account, simply create one through sign up form.Then click on ‘Register Your Application’.

2

 

Now, click on ‘Register New Client’.

3

In the next page, you’ll see a registration page, fill out all the required fields, and enter your valid redirect URL to use in your web application.

For those who don’t know what is valid redirect URL, it is a callback point of the app.

In simple terms, just think how the authentication for Facebook works after the end-user accepts the permissions, “something” has to be called, right? To get back to the app, and that’s “something” is the redirect URL.

Moving forward, click on ‘Manage’ and copy the Client ID, Client Secret and Valid Redirect URLs.

5

 

6

Once you have Client ID, Client Secret, and Valid Redirect URLs, it’s time to create a web page ‘Instagram.php’.

Creating ‘Instagram.php’

<?php
$apiKey = "59f2affac4f80abcc2775f1d72343122"; //client id
$apiReturnback = "http://dev2.spaceo.in/project/socialapp/success.php";
$api_auth_url = 'https://api.instagram.com/oauth/authorize';

$loginUrl = $api_auth_url . '?client_id=' . $apiKey . '&redirect_uri=' . urlencode($apiReturnback) . '&scope=' . implode('+',array('basic')) . '&response_type=code';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Signup with Instagram</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="starter-template" style="margin-top: 300px;">
<center><a href="<?php echo $loginUrl; ?>" class="btn btn-primary"><i class="fa fa-instagram"></i> Signup with instagram</a></center>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js" integrity="sha384-THPy051/pYDQGanwU6poAc/hOdQxjnOEXzbT+OuUAFqNqFjL+4IGLBgCJC3ZOShY" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>

NOTE: remember to change the $apikey and $apireturnback.

Put the $apikey which we got earlier from manage client page.

In $apireturnback, put the valid redirect URLs which we got from Instagram’s manage client page earlier.
Once, the ‘Instagram.php’ is created, create a file ‘config.php’. Again, you can name the file whatever you want, but it’ll be better if you name the file properly.

Now, put the below code inside ‘config.php’ file.

<?php
class config
{
const TOKEN_URL = 'https://api.instagram.com/oauth/access_token'; //API_OAUTH_TOKEN_URL
const API_URL = 'https://api.instagram.com/v1/'; //API_URL
const OAUTH_URL = 'https://api.instagram.com/oauth/authorize'; //API_OAUTH_URL

private $apikey = "6dd74ef8144815ae91ca7432c3213d67";
private $apisecret = "55b0ec76b31694f4f8282cd1ad8abfab";
private $callbackurl = "http://dev2.spaceo.in/project/socialapp/success.php";
private $accesstoken;
private $signedheader = false;

public function setAccessToken($data)
{
$token = is_object($data) ? $data->access_token : $data;

$this->accesstoken = $token;
}
public function getAccessToken()
{
return $this->accesstoken;
}
public function setApiKey($apiKey)
{
$this->apikey = $apiKey;
}
public function getApiKey()
{
return $this->apikey;
}
public function setApiSecret($apiSecret)
{
$this->apisecret = $apiSecret;
}
public function getApiSecret()
{
return $this->apisecret;
}
public function setApiCallback($apiReturnback)
{
$this->callbackurl = $apiReturnback;
}
public function getApiCallback()
{
return $this->callbackurl;
}

public function getAuthToken($code, $token = false)
{
$Data = array(
'grant_type' => 'authorization_code',
'client_id' => $this->getApiKey(),
'client_secret' => $this->getApiSecret(),
'redirect_uri' => $this->getApiCallback(),
'code' => $code
);

$result = $this->AuthCall($Data);

return !$token ? $result : $result->access_token;
}

private function AuthCall($Data)
{

$Host = self::TOKEN_URL;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Host);
curl_setopt($ch, CURLOPT_POST, count($Data));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($Data));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 90);
$jsonData = curl_exec($ch);

if (!$jsonData) {
throw new InstagramException('Error: AuthCall() - cURL error: ' . curl_error($ch));
}
curl_close($ch);

return json_decode($jsonData);
}

public function getUserMedia($id = 'self', $limit = 0)
{
$params = array();

if ($limit > 0) {
$params['count'] = $limit;
}

return $this->makeRequest('users/' . $id . '/media/recent', strlen($this->getAccessToken()), $params);
}

protected function makeRequest($function, $auth = false, $params = null, $method = 'GET')
{
if (!$auth) {
// if the call doesn't requires authentication
$authMethod = '?client_id=' . $this->getApiKey();
} else {
// if the call needs an authenticated user
if (!isset($this->accesstoken)) {
throw new InstagramException("Error: _makeCall() | $function - This method requires an authenticated users access token.");
}

$authMethod = '?access_token=' . $this->getAccessToken();
}

$paramString = null;

if (isset($params) && is_array($params)) {
$paramString = '&' . http_build_query($params);
}

$apiCall = self::API_URL . $function . $authMethod . (('GET' === $method) ? $paramString : null);

// we want JSON
$headerData = array('Accept: application/json');

if ($this->signedheader) {
$apiCall .= (strstr($apiCall, '?') ? '&' : '?') . 'sig=' . $this->headerSign($function, $authMethod, $params);
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiCall);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerData);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_TIMEOUT, 90);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, true);

switch ($method) {
case 'POST':
curl_setopt($ch, CURLOPT_POST, count($params));
curl_setopt($ch, CURLOPT_POSTFIELDS, ltrim($paramString, '&'));
break;
case 'DELETE':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
}

$jsonData = curl_exec($ch);

// split header from JSON data
// and assign each to a variable
list($headerContent, $jsonData) = explode("\r\n\r\n", $jsonData, 2);

// convert header content into an array
$headers = $this->runHeaders($headerContent);

// get the 'X-Ratelimit-Remaining' header value
$this->_xRateLimitRemaining = $headers['X-Ratelimit-Remaining'];

if (!$jsonData) {
throw new InstagramException('Error: _makeCall() - cURL error: ' . curl_error($ch));
}

curl_close($ch);
return json_decode($jsonData);
}

private function headerSign($endpoint, $authMethod, $params)
{
if (!is_array($params)) {
$params = array();
}
if ($authMethod) {
list($key, $value) = explode('=', substr($authMethod, 1), 2);
$params[$key] = $value;
}
$baseString = '/' . $endpoint;
ksort($params);
foreach ($params as $key => $value) {
$baseString .= '|' . $key . '=' . $value;
}
$signature = hash_hmac('sha256', $baseString, $this->apisecret, false);

return $signature;
}
private function runHeaders($headerContent)
{
$headers = array();

foreach (explode("\r\n", $headerContent) as $i => $line) {
if ($i === 0) {
$headers['http_code'] = $line;
continue;
}

list($key, $value) = explode(':', $line);
$headers[$key] = $value;
}

return $headers;
}
}

NOTE: Again, change the $apikey, $apisecret and $callbackurl same as earlier we changed in the ‘Instagram.php’ file.

This ‘Config.php’ file, contains API calls, functions & array that we need for authentication.

For the welcome page, after end-user authorize the Instagram, we’ll need to create a ‘success.php’ file.

Creating Success.php

<?php
require 'instagram/config.php';
// receive authentication code parameter
$code = $_GET['code'];
// check whether the user has permissio access
if (isset($code)) {
$obj = new config();
// receive OAuth token object
$data = $obj->getAuthToken($code); ----------------------> Described after code complete

$username = $data->user->username;
// store user access token
$obj->setAccessToken($data);
// now you have access to all authenticated user methods
$result = $obj->getUserMedia();
} else {
// check whether an error occurred
if (isset($_GET['error'])) {
echo 'An error occurred: ' . $_GET['error_description'];
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>User Media</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<?php
// display all user likes
foreach ($result->data as $media) {
?>
<div class="col-xs-6 col-md-3">
<?php
$content = '<li class="thumbnail">';
// output media
if ($media->type === 'video') {
// video
$poster = $media->images->low_resolution->url;
$source = $media->videos->standard_resolution->url;
$content .= "<video class=\"media video-js vjs-default-skin\" width=\"250\" height=\"250\" poster=\"{$poster}\"
data-setup='{\"controls\":true, \"preload\": \"auto\"}'>
<source src=\"{$source}\" type=\"video/mp4\" />
</video>";
} else {
// image
$image = $media->images->low_resolution->url;
$content .= "<img class=\"media\" src=\"{$image}\"/>";
}
// create meta section
$avatar = $media->user->profile_picture;
$username = $media->user->username;
$comment = $media->caption->text;
$content .= "<div class=\"content\">
<div class=\"avatar\" style=\"background-image: url({$avatar})\"></div>
<p>{$username}</p>
<div class=\"comment\">{$comment}</div>
</div>";
// output media
echo $content . '</li>';
?>
</div>
<?php
}
?>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js" integrity="sha384-THPy051/pYDQGanwU6poAc/hOdQxjnOEXzbT+OuUAFqNqFjL+4IGLBgCJC3ZOShY" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>

Once you create all these files, it’s time to see the output!

Ok so open the ‘Instagram.php’ and it should look like:

7

Next, click on the “Signup with Instagram” button, and it will redirect you to the Instagram login page. Enter your credentials there.

8

After you click on “Log in”, you’ll see a request page for authorization like shown in below image. Click on “Authorize” button.

9

As soon as you hit the Authorize button, it will redirect to your callback URL (“Success.php”) page. Here, we’ve redirected to the page that contains our media files (Images,videos).

10

That’s it.

This is how you can integrate Instagram API into your PHP web page. Here, we’ve just fetched our Instagram page’s images in the web page.

With Instagram API integration, you can get the contents like…

  • User info
  • User feeds
  • User media
  • User likes
  • User follows
  • User follower
  • User Relationship
  • Search media
  • Get media
  • Popular media
  • Media likes
  • Media comments
  • Like media
  • Delete like media
  • Get location
  • Get location media
  • Search location

Note, you will need permissions to get access above contents, you can modify these permissions from manage client section.

If you find any difficulty, you can contact our developers to resolve it.

However, the need for integrating Instagram API has dramatically increased. Nowadays, most website owners include this in their web pages. In fact, many of our clients have also included this feature in their projects. We’re super active in mobile app development world as well. If you’re looking to hire mobile app development company, you can contact us. We’ve worked with the finest entrepreneurs and helped them turn their ideas into a reality.

Don’t miss to copy the source code. Click the link below.

 

This page was last edited on September 18th, 2018, at 3:13.
 
0
Shares
 

Have an App Idea?

Get your free consultation now