關(guān)注微信或者向微信公眾號(hào)發(fā)送信息, 都可以自動(dòng)回復(fù)內(nèi)容,開發(fā)模式下怎么寫php代碼呢?
這里以CI框架控制器里示例下, 當(dāng)然如果你是其它框架, 或者是原生PHP, 那么直接里面的代碼拷貝出來, 做相應(yīng)的替換就可以了
class Wx extends CI_Controller { private $wx_token = "zhuangzi"; private $AppID = "wx6833ed680a3432af"; private $AppSecret = "3faeb8577cc8f2728732a1e5e0291107"; public function index() { if(!isset($_GET["echostr"])) { //驗(yàn)證過了, 就沒有echostr參數(shù)了 $this->responseMsg(); //關(guān)注公眾號(hào)/輸入hello都將會(huì)自動(dòng)回復(fù) }else{ $this -> _check_signature();//驗(yàn)證消息的確來自微信服務(wù)器 //驗(yàn)證代碼: http://tjegd.cn/news/show/169 } } public function responseMsg(){ //get post data, May be due to the different environments $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //接收微信發(fā)來的XML數(shù)據(jù) //extract post data if(!empty($postStr)){ //解析post來的XML為一個(gè)對(duì)象$postObj $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; //請(qǐng)求消息的用戶 $toUsername = $postObj->ToUserName; //"我"的公眾號(hào)id $keyword = trim($postObj->Content); //消息內(nèi)容 $time = time(); //時(shí)間戳 $msgtype = 'text'; //消息類型:文本 $event = $postObj->Event; $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> </xml>"; if($event == "subscribe"){ $contentStr = '歡迎光臨莊子公眾號(hào)'; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr); echo $resultStr; exit(); } if($keyword == 'hello'){ //輸入 hello 將會(huì)回復(fù)的內(nèi)容 $contentStr = 'hello world!!!'; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype,$contentStr); echo $resultStr; exit(); } else{ $contentStr = '現(xiàn)在只回復(fù)輸入 hello, 其它的俺還暫時(shí)還不理人喲'; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr); echo $resultStr; exit(); } } }