【问题标题】:Twitter API https request using curl failed with error使用 curl 的 Twitter API https 请求失败并出现错误
【发布时间】:2017-03-20 03:19:06
【问题描述】:

我正在尝试从 twitter 用户时间轴中检索推文,并使用请求 URL 指定他们的 screen_namecount

我想,我已经提供了必填值并生成了所有在 twitter https://dev.twitter.com/oauth/overview/authorizing-requests 页面上准确提到的必填字段

以下是我的脚本:

  $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"';

还有我的 curl 请求脚本:

$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);

当我执行我的 php 脚本时,它显示以下错误而不是推文:

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

请告诉我为什么它不起作用?

【问题讨论】:

    标签: php api curl twitter


    【解决方案1】:

    我遇到了同样的错误,但解决了将 true 传递到 hash_hmac 函数的问题。请按以下方式更新您的 hash_hmac 函数,然后重试:

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

    【讨论】:

      猜你喜欢
      • 2014-04-07
      • 1970-01-01
      • 2015-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-19
      • 2021-04-23
      相关资源
      最近更新 更多