我已经通过创建签名实现了一切。我创建了一个函数来收集所需的参数(为了清楚起见,我在此处添加了一些注释):
function collect_parameters(){
global $credentials; // This is an Object with my App's credentials and stuff
$oAuth = get_user_oauth(); // This returns an object with the the personal user OAuth tokens retrieved from the earlier docs.
$encoded_collection = array();
$collection = array(
'status' => rawurlencode( $_GET['tweet'] ),
'include_entities' => 'true',
'oauth_consumer_key' => $credentials->key,
'oauth_nonce' => $credentials->nonce, // md5( str_shuffle( uniqid() . mt_rand(0,9999999999) ) )
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => $credentials->time, // current timestamp
'oauth_token' => $oAuth->oauth_token,
'oauth_version' => '1.0',
);
// Percent encode every key and value that will be signed.
foreach( $collection as $key => $value ){
$encoded_collection[rawurlencode($key)] = rawurlencode($value);
}
// Sort the list of parameters alphabetically by encoded key.
ksort( $encoded_collection );
return http_build_query( $encoded_collection );
}
我使用这个函数来构建签名基字符串
function create_signature_base_string( $parameter_string, $url = 'https://api.twitter.com/1.1/statuses/update.json', $method = 'POST' ){
return strtoupper( $method ) .'&'. rawurlencode( $url ) .'&'. rawurlencode( $parameter_string );
}
我用这个函数来计算签名
function calculate_signature( $signature_base_string, $signing_key ){
return base64_encode( hash_hmac('sha1', $signature_base_string, $signing_key, true) );
}
现在构建 OAuth 标头。这是一个函数,它使用上面的辅助函数(加上其他一些返回所需信息的函数):
function get_oauth_headers(){
global $credentials;
$oAuth = get_user_oauth();
$parameters = collect_parameters();
$signature_base_string = create_signature_base_string( $parameters );
$signing_key = get_signing_key();
$signature = calculate_signature( $signature_base_string, $signing_key );
);
冉冉说