Failed to validate oauth signature and token


#1

Hi,
I am trying to get the request token from twitter but it is displaying “Failed to validate oauth signature and token”.Here is my code

<?php 

function hmac_sha1( $key, $data ) {
    $blocksize = 64;
    $hashfunc = 'sha1';
    if ( strlen( $key ) >$blocksize ) {
        $key = pack( 'H*', $hashfunc( $key ) );
    }

    $key = str_pad( $key, $blocksize, chr(0x00) );
    $ipad = str_repeat( chr( 0x36 ), $blocksize );
    $opad = str_repeat( chr( 0x5c ), $blocksize );
    $hash = pack( 'H*', $hashfunc( ( $key^$opad ).pack( 'H*',$hashfunc( ($key^$ipad).$data ) ) ) );

    return base64_encode($hash);
}

$consumerkey = "gcjncGuCVfVxZuuTK9VVg";
$consumersecret = "XXXXX";


$mt = microtime();
$rand = mt_rand();
	
$sign = "POST&".urlencode('https://api.twitter.com/oauth/request_token').'&';

$url = 'https://api.twitter.com/oauth/request_token';

$fields = array(
			'oauth_callback' => 'http://localhost:3005/the_dance/process_callback?service_provider_id=11',
            'oauth_consumer_key'=> $consumerkey,
            'oauth_nonce'=>md5($mt . $rand),
			'oauth_signature_method' => 'HMAC-SHA1',
            'oauth_timestamp'=>time(),
            'oauth_version'=>"1.0",
        );


$head = "OAuth ";

foreach($fields as $key=>$value) { 
	$head .= $key.'="'.urlencode($value).'",'; 
	
	if ($key == 'oauth_callback') {
    $value = urlencode($value);
	}
	
	$sign .= urlencode($key) . '%3D' . urlencode($value) . '%26';
}

rtrim($fields_string,'&');

$sign = substr($sign, 0, strlen($sign) - 3);

$signing_key = $consumersecret . '&';

$oauth_signature = hmac_sha1($signing_key, $sign);

$fields['oauth_signature'] = urlencode($oauth_signature);

$head .= 'oauth_signature="'.urlencode($oauth_signature).'"';


$ch = curl_init();

curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,GET);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: ' . $head));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$result = curl_exec($ch);

curl_close($ch);

?>

Can anybody tell me what’s wrong in this ?
Waiting for your reply


#2

There are so many OAuth (and Twitter) libraries for PHP, there’s no real reason you should be implementing hmac_sha1 or the signing process by hand. I would suggest using the excellent tmhOAuth library in order to interact with the API: https://github.com/themattharris/tmhOAuth


#3