PHP实现微博的同步发送
导读:在设计博客类站点时,有时会需要在发布文章时同步发布在微博上。本文阐述了实现该功能的基本方式。
调用接口
权限认证
接入页面
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_URLrequest()->redirect($code_url);
回调地址页面(WB_CALLBACK_URL):
===callback.php====================
$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;}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。