tags:

views:

52

answers:

0

Hi guys,

I'm trying to implement the Tumblr API into an app. I've hacked together their OAuth implementation but I'm having an issue with their write API.

When I send a post body with no spaces in, it posts correctly. But if there is a space, I receieve an 'Invalid Oauth parameters'.

Below is a rough example - I hope someone can help!

    $res = $this->oauth_request(
        '/api/write',
        array(
            'oauth_token' => $this->token,
    'type' => 'regular',
    'title' => '',
    'body' => 'Something with spaces',
    'generator' => 'Test API'
        ),
        $this->tokenSecret
    );

And then the actual $this->oauth_request function:

function oauth_request($endpoint, $params, $token_secret = false) {
        // Set up base OAuth query
        $query = array_merge(
                array(
                        'oauth_consumer_key'     => $this->consumer_key,
                        'oauth_nonce'            => sha1(microtime(true) . $this->consumer_secret . rand(0,999999)),
                        'oauth_signature_method' => 'HMAC-SHA1',
                        'oauth_timestamp'        => time(),
                        'oauth_version'          => '1.0'
                ),
                $params // Additional parameters
        );

        ksort($query); // OAuth query parameters must be sorted beforing signing

        // Generate OAuth signature and add to query
        $query['oauth_signature'] = base64_encode(
                $this->hmac_sha1(
                        'POST&' . rawurlencode('http://www.tumblr.com' . $endpoint) .
                        '&' . rawurlencode(http_build_query($query)),
                        $this->consumer_secret . '&'. ($token_secret ? $token_secret : '')
                )
        );

        // Generate OAuth "Authorization Header" to attach to our OAuth request
        $auth_header = '';
        foreach ($query as $key => $val) {
                $auth_header .= $key . '="' . rawurlencode($val) . '", ';
        }
        $auth_header = rtrim($auth_header, ', ');

        // Hit it!
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'http://www.tumblr.com' . $endpoint);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($query));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Authorization: OAuth ' . $auth_header,
                'Expect:'
        ));
        $res = curl_exec($ch);
        curl_close($ch);

        return $res;
}