導讀:在設計博客類站點時,有時會需要在發布文章時同步發布在微博上。本文闡述了實現該功能的基本方式。
include_once( 'sina_config.php' ); include_once( 'saetv2.ex.class.php' ); //獲取到授權的url $o = new SaeTOAuthV2( WB_AKEY , WB_SKEY ); $code_url = $o->getAuthorizeURL( WB_CALLBACK_URL ); //post或get方式調用該url,取得授權;授權完成後,新浪會調用我們這邊傳過去的回調地址:WB_CALLBACK_URL request()->redirect($code_url);
$o = new SaeTOAuthV2( WB_AKEY , WB_SKEY ); if (isset($_REQUEST['code'])) { $keys = array(); $keys['code'] = $_REQUEST['code']; $keys['redirect_uri'] = WB_CALLBACK_URL; try { $token = $o->getAccessToken( 'code', $keys ) ; } catch (OAuthException $e) { echo "weibo.com get access token err."; LOG_ERR("weibo.com get access token err."); return ; } } if ($token) { //取到授權後的api調用密鑰,可用存起來,在有效期內多次調用api接口就不用再授權了 $_SESSION['token'] = $token; $c = new SaeTClientV2( WB_AKEY , WB_SKEY , $_SESSION['token']['access_token'] ); $ret = $c->update( $weiboStr ); //發送微博 if ( isset($ret['error_code']) && $ret['error_code'] > 0 ) { $str = "Weibo.com Send failed. err info:" . $ret['error_code'] . '/' . $ret['error']; LOG_ERR($str); } else { LOG_INFO("Weibo.com Send Success."); } }
//獲取當前微博內容(140字) public function getWeibo() { $titleLen = mb_strlen($this->title, 'UTF-8'); //140字除去鏈接的20個字和省略符;剩115字左右,需要說明的是鏈接:無論文章的鏈接多長,在微博裡都會被替換成短鏈接,按短鏈接的長度來計算字數; $summaryLen = 115 - $titleLen ; $pubPaper = cutstr_html($this->summary); if(mb_strlen($pubPaper, 'UTF-8') >= $summaryLen) $pubPaper = mb_substr($pubPaper,0,$summaryLen,'UTF-8'); $pubPaper = sprintf('【%s】%s...%s', $this->title , $pubPaper , aurl('post/show', array('id' => $this->id))); return $pubPaper; } //完全的去除html標記 function cutstr_html($string) { $string = strip_tags($string); $string = preg_replace ('/n/is', '', $string); $string = preg_replace ('/ | /is', '', $string); $string = preg_replace ('/ /is', '', $string); return $string; }