这里是图中 B Service Provider Grants Request Token。
得到url,类似下面的字符串:
https://twitter.com/oauth/request_token?oauth_callback=http%3A%2F%2Flocalhost%2Fitwitter%2F&oauth_consumer_key=fwwaw3m5sQq4L3M6aXV1jg
&oauth_nonce=817d10a677547378dbef3547c5545fdb&oauth_signature=Hv48dvKEbWAn4tG4JSEs0UbM1so%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1295839203&oauth_version=1.0a
这里使用了curl,函数如下。
function http( $url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FRESH_CONNECT,true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
然后,用 echo http($url); 就可以得到类似如下的值:
oauth_token=sNwJ4Km398PwLdOOjxBcER7KQ2U8P9uPocLblUaAY &oauth_token_secret=SMVXvhsBWX9qbwbZNsukn5qc2Ex3vLUV405sQyrrU&oauth_callback_confirmed=true
这里把这个值转换为Array(数组),放到一个变量里。
$oauth_responses = http($url);
$oauth_responses = split('&', $oauth_responses);
$parsed_parameters = array();
foreach ($oauth_responses as $oauth_response) {
$split = split('=', $oauth_response, 2);
$parameter = $split[0];
$value = $split[1];
if (isset($parsed_parameters[$parameter])) {
if (is_scalar($parsed_parameters[$parameter])) {
$parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
}
$parsed_parameters[$parameter][] = $value;
} else {
$parsed_parameters[$parameter] = $value;
}
}
这是 $parsed_parameters 的值类似如下:
Array ( [oauth_token] => sNwJ4Km398PwLdOOjxBcER7KQ2U8P9uPocLblUaAY [oauth_token_secret] => SMVXvhsBWX9qbwbZNsukn5qc2Ex3vLUV405sQyrrU [oauth_callback_confirmed] => true )
然后,取出oauth_token的值,作为参数,请求图中C Consumer Directs User to Service Provider,代码如下。
$oauth_token = $parsed_parameters['oauth_token'];
$url2 = "http://api.twitter.com/oauth/authorize?oauth_token=" . $oauth_token;