简体   繁体   中英

Twitter API https request using curl failed with error

I am trying to retrieve tweets from twitter user timeline specifying their screen_name and count with request URL.

I think, I have provided required values and generated all the required field exactly mentioned on twitter https://dev.twitter.com/oauth/overview/authorizing-requests page

Following are the my scripts:

  $param_string = 'oauth_consumer_key='.$consumer_key.
        '&oauth_nonce='.$nonce.
        '&oauth_signature_method=HMAC-SHA1'.
        '&oauth_timestamp='.$timestamp.
        '&oauth_token='.$token.
        '&oauth_version='.$version.
        '&screen_name='.rawurlencode($screen_name).
        '&count='.$count;

$base_string = 'POST&'.rawurlencode($url).'&'.rawurlencode($param_string);
$signing_key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $signing_key)));

$auth = 'OAuth oauth_consumer_key="'.rawurlencode($consumer_key).'",'.
    'oauth_nonce="'.rawurlencode($nonce).'",'.
    'oauth_signature="'.rawurlencode($signature).'",'.
    'oauth_signature_method="HMAC-SHA1",'.
    'oauth_timestamp="'.rawurlencode($timestamp).'",'.
    'oauth_token="'.rawurlencode($token).'",'.
    'oauth_version="1.0"';

And my curl request scripts :

$ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, True);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_CAINFO, __DIR__."/ca-bundle.crt");
    curl_setopt($ch,CURLOPT_CAPATH,__DIR__.'/ca-bundle.crt');
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: $auth"));
    $output = curl_exec($ch);

  if(curl_error($ch))
  {
   echo 'HTTP error:' . curl_error($ch);
  }else{
  echo "<pre>";
  var_dump($output);
  }
  curl_close($ch);

While I execute my php scripts it's showing following error instead of tweets:

string(64) "{"errors":[{"code":32,"message":"Could not authenticate you."}]}"

Please let me know why it's not working?

I have experienced same error but resolved that passing true into hash_hmac function. Could please update you hash_hmac function as following then try again:

$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $signing_key,true)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM