如何在PHP中获取Tumblr API的用户OAuth?

时间:2015-11-18 00:50:12

标签: php api http oauth tumblr

使用默认的Tumblr v2 API,我可以连接到我的应用程序,并从我自己的帐户中检索帖子。但是,我希望用户能够连接他们的自己的帐户。我试图解决这个问题,但我并不完全确定如何使用OAuth(即时使用this class)。这是怎么做到的?

我用来检索信息中心帖子的代码是:

$consumerKey = 'xxx';
  $consumerSecret = 'xxx';
  $tumblr = new Tumblr\API\Client(
    $consumerKey,
    $consumerSecret
  );

var_dump( $tumblr->getDashboardPosts() ); // using var_dump for testing purposes only

此代码有效,但它只返回我的PERSONAL帐户的代码。

1 个答案:

答案 0 :(得分:1)

I figured it out, thanks to Github user seejohnrun.

require_once 'include/util.php';

  $consumerKey = 'XXX';
  $consumerSecret = 'XXX';
  $client = new Tumblr\API\Client($consumerKey, $consumerSecret);
  $requestHandler = $client->getRequestHandler();
  $requestHandler->setBaseUrl('https://www.tumblr.com/');

  // If we are visiting the first time
  if (!$_GET['oauth_verifier']) {

      // grab the oauth token
      $resp = $requestHandler->request('POST', 'oauth/request_token', array());
      $out = $result = $resp->body;
      $data = array();
      parse_str($out, $data);

      // tell the user where to go
      echo '<a href="https://www.tumblr.com/oauth/authorize?oauth_token=' . $data['oauth_token'].'"> GO </a>';
      $_SESSION['t']=$data['oauth_token'];
      $_SESSION['s']=$data['oauth_token_secret'];

  } else {

      $verifier = $_GET['oauth_verifier'];

      // use the stored tokens
      $client->setToken($_SESSION['t'], $_SESSION['s']);

      // to grab the access tokens
      $resp = $requestHandler->request('POST', 'oauth/access_token', array('oauth_verifier' => $verifier));
      $out = $result = $resp->body;
      $data = array();
      parse_str($out, $data);

      // and print out our new keys we got back
      $token = $data['oauth_token'];
      $secret = $data['oauth_token_secret'];
      echo "token: " . $token . "<br/>secret: " . $secret;

      // and prove we're in the money
      $client = new Tumblr\API\Client($consumerKey, $consumerSecret, $token, $secret);
      $info = $client->getUserInfo();
      echo "<br/><br/>congrats " . $info->user->name . "!";

  }