QQ微博API至今未发布,昨几天在给EMLOG写QQ微博插件插件的时候搞定QQ微博,今天封装一个php发QQ微博的类,相当于一个简单的QQ微博API功能。大致原理简单的说来就是用CURL库模拟登陆发表微博。废话不多说,直接上菜:
<?php
/*
用法:
$qq = new qq();
$qq->publish('xieyanwei','password','Hi, I\'m a PHPer.');
*/
class qq
{
function publish($username, $password, $content='')
{
$qq = trim($username);
$pwd = $this->md5_3(trim($password));
$cookie_jar = $this->login($qq, $pwd);
$url = 'http://t.qq.com/publish.php' ;
$fields = array(
'content'=>urlencode($content),
'pic'=>urlencode(''),
'countType'=>urlencode(''),
'viewModel'=>urlencode('1')
);
$fields_string = '';
foreach($fields as $key=>$value)
{
$fields_string .= $key.'='.$value.'&' ;
}
rtrim($fields_string ,'&') ;
$fields_string = substr($fields_string, 0,-5);
$referURL = 'http://t.qq.com/'.$qq;
$curl = curl_init($url) ;
curl_setopt($curl, CURLOPT_POST,count($fields)) ;
curl_setopt($curl, CURLOPT_POSTFIELDS,$fields_string) ;
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie_jar);
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie_jar);
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie_jar);
curl_setopt($curl, CURLOPT_REFERER, $referURL);
curl_exec($curl) ;
curl_close($curl) ;
unlink($cookie_jar);
}
private function login($username, $password)
{
$qq = trim($username);
$pwd = trim($password);
$verifyURL = 'http://ptlogin2.qq.com/check?uin=@'.$qq.'&appid=46000101';
$loginURL = 'http://ptlogin2.qq.com/login?';
$curl = curl_init($verifyURL);
$cookie_jar = tempnam('.', 'cookie');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie_jar);
$verifyCode = curl_exec($curl);
curl_close($curl);
$verifyCode = strtoupper(substr($verifyCode, 18, 4));
$loginURL .= 'u=@'.$qq.'&p='.md5($pwd.$verifyCode).'&verifycode='.$verifyCode.'&aid=46000101&u1=http%3A%2F%2Ft.qq.com&h=1&from_ui=1&fp=loginerroralert';
$curl = curl_init($loginURL);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie_jar);
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie_jar);
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie_jar);
curl_exec($curl);
curl_close($curl);
return $cookie_jar;
}
private function md5_3($str)
{
return strtoupper(md5(md5(md5($str,true),true)));
}
}
?>