cosenary / Instagram-PHP-API

An easy-to-use PHP Class for accessing Instagram's API.
http://cosenary.github.com/Instagram-PHP-API
BSD 3-Clause "New" or "Revised" License
1.46k stars 782 forks source link

modifyRelationship not working? #3

Closed ViktorShinova closed 12 years ago

ViktorShinova commented 12 years ago

Hi, I've been using your instagram API and thanks for putting it up.

Now I'm working at the stage where I can follow/unfollow users.

However when I tried the simple example given

$instagram->modifyRelationship('follow', 1574083);

it doesn't work.

do you mind showing me how your modifyRelationship func works?

Cheers.

cosenary commented 12 years ago

Thanks for using my Instagram Class! I'll post you more information about this issue, when I'm back from holiday, so please be patient.

Best Regards, Christian

ViktorShinova commented 12 years ago

no worries mate, have a good holiday!

cosenary commented 12 years ago

Hi,

here are the necessary steps:

  1. Login the user which should perform the action (follow / unfollow / block / unblock / approve / deny)

    Thus, you are modifying a relationship, you have to add the according scope "relationships". Get login URL.

  2. After Instagram redirects the user back to your application (API callback URL), you have to grab its access token.
<?php
    $code = $_GET['code'];
    $token = $instagram->getOAuthToken($code, true);
?>

Store the access token in your database for later usage. Further information: Authenticate user

  1. Login a user by setting its access token and follow the user with the id 1574083.
<?php
    // Set access token, previously stored in your database
    $instagram->setAccessToken($token);

    // and execute the action (in this case: follow)
    $result = $instagram->modifyRelationship('follow', 1574083);
?>
  1. A successful response should look like this:
{
      "meta": {
        "code": 200
      },
      "data": {
        "outgoing_status": "follows",
        "target_user_is_private": false
      }
}

So, you can easily check whether your request was successful, if the response-code is 200. $success = $result->meta->code;

Hope that I could help you, by providing you with the necessary information.

All the best, Christian

ViktorShinova commented 12 years ago

thanks for the info! I actually missed out the Get login URL. step. It works.

However, I am having trouble getting back access token when navigating to over pages.

Whenever I navigate to other pages, or refresh the callback page. Everything is gone.

Example: index.php -> "login" -> success.php?code=d4ef0f53a6de4bc2a415e0c219d83397 display info Your username is: xxxxx Your userid is: 1234567899

then when I refresh the success.php page, or navigate to follow.php page for instance, everything is gone. display info Your username is: Your userid is:

I tried to store the token "code=d4ef0f53a6de4bc2a415e0c219d83397" into a session but it doesn't work.

I tried using getAccessToken() but no luck either.

Am I doing missing out some steps?

cosenary commented 12 years ago

The code you get returned in the callback URL success.php?code=d4ef0f53a6de4bc2a415e0c219d83397 is only part of the OAuth workflow and doesn't authenticates the user. What you need is the access-token:

<?php
    // receive the OAuth code
    $code = $_GET['code'];
    // and exchange it for an OAuth token
    $token = $instagram->getOAuthToken($code, true);
    // store token in session
    $_SESSION['access_token'] = $token;
?>

Now the varibale $token contains the user's access-token, which you need for all user requests. So, this is the token you have to store in your session.

On each page, that requires an authenticated user, simply set the user's access-token, which you have stored in a session before:

<?php
    $token = $_SESSION['access_token'];
    $instagram->setAccessToken($token);
?>

That's it! Now you can execute an action (eg. modifyRelationship()). Let me know whether this works for you.

Best Regards, Christian

ViktorShinova commented 12 years ago

Thanks for the quick reply! Unfortunately, it didn't work for me. Let me show you my code.

index.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Charset -->
    <meta charset="utf-8">

    <!-- Meta -->
    <title>Instagram - OAuth Login</title>

    <!-- CSS -->
    <style type="text/css">
      * {
        margin: 0px;
        padding: 0px;
      }

      a.button {
        background: url(instagram-login-button.png) no-repeat transparent;
        cursor: pointer;
        display: block;
        height: 29px;
        margin: 50px auto;
        overflow: hidden;
        text-indent: -9999px;
        width: 200px;
      }

      a.button:hover {
        background-position: 0 -29px;
      }
    </style>
  </head>
  <body>

    <?php
      require 'instagram.class.php';

      // Setup class
      $instagram = new Instagram(array(
          'apiKey'      => '12313123123',
          'apiSecret'   => '123123abcabc',
          'apiCallback' => 'http://www.test.com/example/success.php'
      ));

      // Display the login button
      $loginUrl = $instagram->getLoginUrl(array(
                                              'basic',
                                              'likes',
                                              'relationships'
                                            ));
      echo "<a class=\"button\" href=\"$loginUrl\">Sign in with Instagram</a>";
    ?>

  </body>
</html>

success.php

<?php
session_start();

require 'instagram.class.php';

// Initialize class
$instagram = new Instagram(array(
    'apiKey'      => '12313123123',
    'apiSecret'   => '123123abcabc',
    'apiCallback' => 'http://www.test.com/example/success.php'
));

// Receive OAuth code parameter
$code = $_GET['code'];

// Check whether the user has granted access
if (true === isset($code)) {

  // Receive OAuth token object
  $data = $instagram->getOAuthToken($code, true);
  $_SESSION['access_token'] = $data;

  echo 'Your username is: '.$data->user->username .'<br/>';
  echo 'Your userid is: '.$data->user->id.'<br/>';

    $following = $instagram->getUserFollows();
    //var_dump($following);
    foreach ($following->data as $instausers) {
        echo 'ID: '.$instausers->id.' name: '.$instausers->username.'<br/>';
    }
  echo '<a href="follow.php">Follow Test</a>';

} else {

  // Check whether an error occurred
  if (true === isset($_GET['error'])) {
    echo 'An error occurred: '.$_GET['error_description'];
  }

}

?>

follow.php

<?php
session_start();

$token = $_SESSION['access_token'];
$instagram->setAccessToken($token);

$instagram->modifyRelationship('follow', 1574083);
?>

After going to follow.php, I get HTTP Error 500 (Internal Server Error):

cosenary commented 12 years ago

You have forgotten to include and to initialize the Instagram class in the follow.php file. I've fixed this in the following code, which works now on my server.

I hope that this solves your problem.

success.php

<?php

  session_start();
  require 'instagram.class.php';

  // Initialize class
  $instagram = new Instagram(array(
    'apiKey'      => '12345678',
    'apiSecret'   => 'abcdefg12345678',
    'apiCallback' => 'http://example.com/success.php'
  ));

  // Receive OAuth code parameter
  $code = $_GET['code'];

  // Check whether the user granted access
  if (true === isset($code)) {

    // Grab OAuth callback code
    $token = $instagram->getOAuthToken($code, true);
    $_SESSION['access_token'] = $token;

    // Store user access token
    $instagram->setAccessToken($token);

    // Get user follows
    $following = $instagram->getUserFollows();

    // Display all user follower
    foreach ($following->data as $user) {
      echo 'ID: ' . $user->id . ' Name: ' . $user->username . '<br/>';
    }

    echo '<a href="follow.php">Follow Test</a>';

  } else {

    // Check whether an error occurred
    if (true === isset($_GET['error'])) {
      echo 'An error occurred: ' . $_GET['error_description'];
    }

  }

?>

follow.php

<?php

session_start();
require 'instagram.class.php';

// Initialize class
$instagram = new Instagram(array(
  'apiKey'      => '12345678',
  'apiSecret'   => 'abcdefg12345678',
  'apiCallback' => 'http://example.com/success.php'
));

// Set logged in user
$token = $_SESSION['access_token'];
$instagram->setAccessToken($token);

// Modify the user's relationship to the user with the ID '1574083'
$result = $instagram->modifyRelationship('follow', 1574083);

// Dump request status (success: 200)
var_dump($result->meta->code);

?>
ViktorShinova commented 12 years ago

cool it works! everything is looking good now. however, getting profile data doesn't work anymore. Is now returning null values.

    // Receive OAuth code parameter
    $code = $_GET['code'];
    $token = $instagram->getOAuthToken($code, true);

    echo 'Your username is: '.$token->user->username .'<br/>'; //output null
    echo 'Your userid is: '.$token->user->id.'<br/>';// output null

Previously, it was just getOAuthToken($code) without having to set ($code, true); Based on your API doc, it says false [default] : Returns OAuth token and profile data of the authenticated user.

I tried calling getOAuthToken(), twice, one with true, and the false, and then store the profile data in session, but still no luck.. Seems like I can only call getOAuthToken() once only. Am I missing out something again?

    // Receive OAuth code parameter
    $code = $_GET['code'];
    $token = $instagram->getOAuthToken($code, true);
    $data= $instagram->getOAuthToken($code);

    echo 'Your username is: '.$data->user->username .'<br/>'; //output null
    echo 'Your userid is: '.$data->user->id.'<br/>';// output null

Sorry to bother you too much man. This would be my last issue.

Cheers.

cosenary commented 12 years ago

If you want to get the user-data on the success page, you have to remove the true parameter. Then the method getOAuthToken() returns the whole user-data, including the access-token. To store the token in your session, get it like this: $token->access_token

The updated code should look like this:

// Grab OAuth callback code
$data = $instagram->getOAuthToken($code);
$_SESSION['access_token'] = $data->access_token;

// Store user access token
$instagram->setAccessToken($data);

echo 'Your username is: ' . $data->user->username . '<br/>';
echo 'Your userid is: ' . $data->user->id . '<br/>';

It's great to see that you use my Instagram class. Hopefully it's useful to you. All the best, Christian

ViktorShinova commented 12 years ago

wow awesome! everything works fine now! thanks very much!!! your Instagram API rocks!