OAuth extension, PHP and the Tumblr API

Tumblr’s API v2 now requires that if you’d like to execute user commands such as posting, getting user info, or reblogging on behalf of a Tumblr account, you will need to authenticate via OAuth.  This is basically a method to authenticate an application without disclosing a user’s password credentials to the application.

I will briefly go over the basic steps of OAuth:

  1. User runs application
  2. Application requests a request token from Tumblr, while specifying a callback URL to Tumblr that the user will be redirected to after “allowing” your application.
  3. Tumblr responds, as long as your app is registered, with a request token and a request token secret.  Both are codes.
  4.  Application saves the request token secret for later use, and redirects the user to Tumblr’s authorize service so the user can click ‘Allow’ or ‘Deny’ with regards to your application requesting permissions.
  5. The user is redirected to the callback URL, and assuming they clicked ‘Allow’, Tumblr attaches a GET variable to it by the name of oauth_token
  6. Finally, application uses oauth_token and the request token secret to request the access token and access token secret.
  7. Application can now make requests to the Tumblr api, and can save the access token and access token secret to a database for future use.

Here’s a useful diagram from Twitter:

If a more thorough learning experience is desired, I would recommend hueniverse’s guide to Oauth : http://hueniverse.com/oauth/

 

This guide is for those who wish to work with the PECL OAuth extension for PHP:

http://www.php.net/manual/en/book.oauth.php

In order to install it, you will need access to a dedicated/vps server. If you are under shared hosting and do not have permissions to install php extensions, you either need to request it to your host or use another solution such as Google’s OAuth library : http://code.google.com/p/oauth-php/ (not explained here)

To install the OAuth extension on my VPS, I first needed to install the PCRE (Perl Compatible Regular Expressions) library so the OAuth extension can install correctly. Then I can execute the pecl install command.

On CentOS this command would be:

yum install pcre pcre-devel
pecl install oauth

Solutions for other styles of linux can be found here: http://www.php.net/manual/en/oauth.setup.php

 

Once installed, we can now proceed with actual coding.  The extension provides us with a nice example using Oauth with yahoo’s FireEagle.  We are going to modify this example to work with Tumblr.

<?php
//Tumblr API urls
$req_url = 'http://www.tumblr.com/oauth/request_token';
$authurl = 'http://www.tumblr.com/oauth/authorize';
$acc_url = 'http://www.tumblr.com/oauth/access_token';
 
//Your Application key and secret, found here: http://www.tumblr.com/oauth/apps
$conskey = 'keygoeshere';
$conssec = 'secretgoeshere';
 
//Enable session.  We will store token information here later
session_start();
 
// state will determine the point in the authorization request our user is in
// In state=1 the next request should include an oauth_token.
// If it doesn't go back to 0
if(!isset($_GET['oauth_token']) && $_SESSION['state']==1) $_SESSION['state'] = 0;
try {
 
  //create a new Oauth request.  By default this uses the HTTP AUTHORIZATION headers and HMACSHA1 signature required by Tumblr.  More information is in the PHP docs
  $oauth = new OAuth($conskey,$conssec);
  $oauth->enableDebug();
 
  //If this is a new request, request a new token with callback and direct user to Tumblrs allow/deny page
  if(!isset($_GET['oauth_token']) && !$_SESSION['state']) {
    $request_token_info = $oauth->getRequestToken($req_url, 'http://callbackurl.com/goeshere');
    $_SESSION['secret'] = $request_token_info['oauth_token_secret'];
    $_SESSION['state'] = 1;
    header('Location: '.$authurl.'?oauth_token='.$request_token_info['oauth_token']);
    exit;
 
  //If this is a callback from Tumblr's allow/deny page, request the auth token and auth token secret codes and save them in session
  } else if($_SESSION['state']==1) {
    $oauth->setToken($_GET['oauth_token'],$_SESSION['secret']);
    $access_token_info = $oauth->getAccessToken($acc_url);
    $_SESSION['state'] = 2;
    $_SESSION['token'] = $access_token_info['oauth_token'];
    $_SESSION['secret'] = $access_token_info['oauth_token_secret'];
  } 
  $oauth->setToken($_SESSION['token'],$_SESSION['secret']);
 
  //Post text 'This is a test post' to user's Tumblr
  $oauth->fetch("http://api.tumblr.com/v2/blog/yourtumblr.tumblr.com/post", array('type'=>'text', 'body'=>'This is a test post'), OAUTH_HTTP_METHOD_POST);
 
  //Print out Tumblr's response
  $json = json_decode($oauth->getLastResponse());
  print_r($json);
} catch(OAuthException $E) {
  print_r($E);
}
?>

As you can see this is a very simple example, that would work provided we knew the user’s tumblr url. Fortunately, Tumblr provides a userinfo method (http://api.tumblr.com/v2/user/info) that will enable you to get this info and do whatever your imagination desires 🙂

All Tumblr API methods can be found here: http://www.tumblr.com/docs/en/api/v2

14 thoughts on “OAuth extension, PHP and the Tumblr API

  1. Luis

    This is a great code, thanks for sharing, I can’t make it work I don’t understand the callback url what do I need in that callback url?

    1. vigrond Post author

      This piece of script acts as the callback too. After the user is directed to Tumblr and clicks ‘Approve application’ to give your app permissions, it will redirect back to your callback url with GET variables.

      As you can see, this script has an if else structure and performs logic based on if there is a GET variable or not.

      So your callback url is the php script itself, for this example.

  2. freelance supermarket

    Hey, I just launched my new blog to help fellow freelancers out with tax and accounting, thought it would be helpful to your freelance readers – freelancersupermarket.com I purposely haven’t made a link – unlike all the spammers! 🙂 all the best

  3. Ugghi

    Thx for sharing this great code. I want to post photo with this code. I am able to upload one picture but I can’t create a photoset with multiple images using API.

    Documentation says: Paramater: Array (URL-encoded binary contents)

    One or more image files (submit multiple times to create a slide show)

    Do you know how to do it? thx

  4. Ugghi

    This one (https://gist.github.com/1649885) able to upload multiple images. Compare with you code, I think

    {$oauth->fetch(“http://api.tumblr.com/v2/blog/yourtumblr.tumblr.com/post”, array(‘type’=>’text’, ‘body’=>’This is a test post’), OAUTH_HTTP_METHOD_POST);}

    should be changed

    {$oauth->fetch(“http://api.tumblr.com/v2/blog/yourtumblr.tumblr.com/post”, array(‘type’=>’text’, ‘body’=>’This is a test post’), OAUTH_HTTP_METHOD_POST, array(‘Content-Type: application/x-www-form-urlencoded’);}

    But it doesn’t work for me 🙁

  5. Ugghi

    This one (https://gist.github.com/1649885) able to upload multiple images. Compare with you code, I think

    {$oauth->fetch(“http://api.tumblr.com/v2/blog/yourtumblr.tumblr.com/post”, array(‘type’=>’text’, ‘body’=>’This is a test post’), OAUTH_HTTP_METHOD_POST);}

    should be changed

    {$oauth->fetch(“http://api.tumblr.com/v2/blog/yourtumblr.tumblr.com/post”, array(‘type’=>’text’, ‘body’=>’This is a test post’), OAUTH_HTTP_METHOD_POST, array(“Host” => “http://api.tumblr.com/”, “Content-type” => “application/x-www-form-urlencoded”, “Expect” => “”);}

    But it doesn’t work for me

  6. Vaibhav Arora

    I need to make a cronjob script using tumblr API, can I save the oauth token and request variables in database and run the script on cronjob ???

  7. Baba

    Thanks for the code, however I am having trouble getting it to work. After allowing access, it redirects to my tumblr’s blog url and not the callback. Nothing gets posted. Any help would be greatly appreciated.

  8. tumblr test

    $oauth->fetch(“http://api.tumblr.com/v2/blog/yourtumblr.tumblr.com/post”, array(‘type’=>’text’, ‘body’=>’This is a test post’,’tags’=>array(‘0′,’1’)), OAUTH_HTTP_METHOD_POST);

    this is wrong~~~why

  9. tumblr test

    add tags is a array string that’s wrong.if tags one array is right.but two or more that’s wrong~~~why

  10. Pingback: Posting to tumblr in PHP | question code

  11. zcode system review

    It is perfect time to make some plans for the future and it is time to be happy.
    I’ve read this post and if I could I wish to suggest you few interesting things or tips. Perhaps you can write next articles referring to this article. I wish to read more things about it!

  12. homepage

    fantastic points altogether, you simply won a new reader.
    What may you recommend in regards to your post that you made a few days ago?
    Any certain?

  13. Dating

    I like the helpful information you provide in your articles.
    I will bookmark your blog and check again here regularly.
    I am quite sure I will learn plenty of new stuff right here!
    Best of luck for the next!

Comments are closed.