Search code examples
phpoauthtumblr

Unable to generate Tumblr API Request Token in PHP


First, a note: My host does not have the PECL OAUTH or HTTP extensions installed.

The purpose of this: I'm hoping to create an interface to easily follow and unfollow a given list of Tumblr names.

Problem: Can't get past the authentication step.

Code:

$request_url = 'http://www.tumblr.com/oauth/request_token';
$consumer_key = COSUMER_KEY;
$consumer_secret = CONSUMER_SECRET;
$oauth_key = urlencode_rfc3986($consumer_secret) . '&';
$time = time();
$nonce = md5(microtime() . mt_rand());
$callback_url = 'http://krisallengallery.com/easyfollowr/index.php';
$params = array('oauth_consumer_key' => $consumer_key,
                'oauth_signature_method' => 'HMAC-SHA1',
                'oauth_timestamp' => $time,
                'oauth_nonce' => $nonce,
                'oauth_version' => '1.0a',
                'oauth_callback' => $callback_url);             
uksort($params, 'strcmp');

$oauth_header = 'Authorization: OAuth ';

$raw_signature = 'GET&' . urlencode_rfc3986($request_url) . '&';
$raw_suffix = array();
foreach($params as $key => $param)
{
    $raw_suffix[] = $key . '=' . $param;
}
$raw_signature .= urlencode_rfc3986(implode('&', $raw_suffix));
$oauth_signature = urlencode_rfc3986(base64_encode(hash_hmac('sha1', $raw_signature, $oauth_key, true)));

$params['oauth_signature'] = $oauth_signature;
uksort($params, 'strcmp');

$raw_head = array();
foreach($params as $key => $param)
{
    $raw_head[] = $key . '="' . $param . '"';
}
$oauth_header .= implode(',', $raw_head);

$session = curl_init($request_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($session, CURLOPT_HEADER, true);
curl_setopt($session, CURLOPT_HTTPHEADER, array($oauth_header));
$response = curl_exec($session);
curl_close($session);
echo $response;

function urlencode_rfc3986($input)
{
    return str_replace('+', ' ', str_replace('%7E', '~', rawurlencode($input)));
}

Any ideas of where I'm going wrong?

ETA: Made some modifications. It's still not working, but the error I'm getting now is oauth_signature does not match expected value


Solution

  • I'm not entirely sure what I was doing wrong, but fortunately, I found fangel's OAuth script on GitHub that implements everything I need to generate tokens. It looks like I was on the the right track, though.

    ETA: Furthermore, there is jacobbudin's TumblrOAuth library on GitHub, which uses fangel's script and some forked then updated code, that handles all the Tumblr authentication for a user for your application.

    I'm sure I'll be back with more questions when I start trying to build my Followr script.