我想从twitter上获取所有公开信息。在Twitter中创建应用程序并收集使用者密钥(API Key)
,消费者密钥(API Secret)
,访问级别,访问令牌,访问令牌密钥,访问级别并编写程序。在运行时它显示错误
{"message":"Could not authenticate you","code":32}
。
为twitterapi创建一个类,其中所有键都是私有的,然后设置为post。然后创建一个函数setGetfield()
public function setGetfield($string)
{
if (!is_null($this->getPostfields()))
{
throw new Exception('You can only choose get OR post fields.');
}
$search = array('#', ',', '+', ':');
$replace = array('%23', '%2C', '%2B', '%3A');
$string = str_replace($search, $replace, $string);
$this->getfield = $string;
return $this;
}
创建一个函数getGetfields(),用于从twitter收集所有字段。
public function getGetfields()
{
return $this->getfield;
}
构建oauth写buildOuath功能
public function buildOauth($url, $requestMethod)
{
if (!in_array(strtolower($requestMethod), array('post', 'get')))
{
throw new Exception('Request method must be either POST or GET');
}
$consumer_key = $this->consumer_key;
$consumer_secret = $this->consumer_secret;
$oauth_access_token = $this->oauth_access_token;
$oauth_access_token_secret = $this->oauth_access_token_secret;
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
$getfield = $this->getGetfield();
if (!is_null($getfield))
{
$getfields = str_replace('?', '', explode('&', $getfield));
foreach ($getfields as $g)
{
$split = explode('=', $g);
$oauth[$split[0]] = $split[1];
}
}
$base_info = $this->buildBaseString($url, $requestMethod, $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
$this->url = $url;
$this->oauth = $oauth;
return $this;
}
生成授权标题
private function buildAuthorizationHeaders($oauth)
{
$return = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key => $value)
{
$values[] = "$key=\"" . rawurlencode($value) . "\"";
}
$return .= implode(', ', $values);
return $return;
}
如何解决这个难题