騰訊微博(t.qq.com)已于2014年9月28日停止服務,本文僅作技術歸檔參考,展示OAuth 1.0時代的API調用模式。現代開發請使用騰訊開放平台(QQ登錄、微信開放平台)最新API。
由於當時無官方開放API,開發者通過模擬Web登錄流程獲取Cookie,再解析HTML頁面:
// 1. 獲取驗證碼
$verifyUrl = "https://ptlogin2.qq.com/check?uin=@{$qq}&appid=46000101";
// 解析返回JS獲取驗證碼
// 2. 提交登錄(MD5加密密碼+驗證碼)
$loginUrl = "https://ptlogin2.qq.com/login?u=@{$qq}&p=" . md5($pwd . $verifyCode) . "&verifycode={$verifyCode}&aid=46000101&u1=http%3A%2F%2Ft.qq.com";
// 攜帶Cookie Jar持久化會話
// 3. 訪問個人主頁獲取HTML
$html = curl_get('https://t.qq.com/'.$qq.'/mine', $cookieFile);
// 4. 使用Simple HTML DOM解析器提取微博內容
$dom = str_get_html($html);
$talkList = $dom->find('#talkList');
$lastTalk = $talkList[0];
$userName = $lastTalk->children(0)->children(1)->find('.userName')[0]->plaintext;
$msgCnt = $lastTalk->children(0)->children(1)->find('.msgCnt');
$pubInfo = $lastTalk->children(0)->children(1)->find('.pubInfo');
// 判斷原創/轉發邏輯提取內容
// 1. 申請應用獲取AppID/AppKey
// 2. OAuth 2.0 授權碼模式獲取Access Token
$authUrl = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id={$appId}&redirect_uri={$redirectUri}&scope=get_user_info";
// 用戶授權後回調獲取code
$tokenUrl = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&code={$code}&client_id={$appId}&client_secret={$appKey}&redirect_uri={$redirectUri}";
// 3. 調用OpenAPI
$apiUrl = "https://graph.qq.com/user/get_user_info?access_token={$accessToken}&oauth_consumer_key={$appId}&openid={$openId}";
使用snsapi_userinfo作用域獲取用戶基本信息,snsapi_base靜默授權獲取OpenID。
| 庫 | 特點 | 適用場景 |
|---|---|---|
| symfony/dom-crawler | CSS選擇器、XPath、可獨立使用 | 現代PHP項目首選 |
| paquettg/php-html-parser | jQuery風格API、容錯性強 | 快速原型開發 |
| masterminds/html5-php | HTML5標準解析、修正不規範標記 | 複雜頁面結構 |
| simple-html-dom (原文使用) | 老舊、不維護、內存洩漏風險 | 僅維護舊項目 |