關注微信或者向微信公眾號發(fā)送信息, 都可以自動回復內(nèi)容,開發(fā)模式下怎么寫php代碼呢?
這里以CI框架控制器里示例下, 當然如果你是其它框架, 或者是原生PHP, 那么直接里面的代碼拷貝出來, 做相應的替換就可以了
class Wx extends CI_Controller {
private $wx_token = "zhuangzi";
private $AppID = "wx6833ed680a3432af";
private $AppSecret = "3faeb8577cc8f2728732a1e5e0291107";
public function index()
{
if(!isset($_GET["echostr"]))
{ //驗證過了, 就沒有echostr參數(shù)了
$this->responseMsg(); //關注公眾號/輸入hello都將會自動回復
}else{
$this -> _check_signature();//驗證消息的確來自微信服務器
//驗證代碼: http://www.155as.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為一個對象$postObj
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName; //請求消息的用戶
$toUsername = $postObj->ToUserName; //"我"的公眾號id
$keyword = trim($postObj->Content); //消息內(nèi)容
$time = time(); //時間戳
$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 = '歡迎光臨莊子公眾號';
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr);
echo $resultStr;
exit();
}
if($keyword == 'hello'){
//輸入 hello 將會回復的內(nèi)容
$contentStr = 'hello world!!!';
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype,$contentStr);
echo $resultStr;
exit();
}
else{
$contentStr = '現(xiàn)在只回復輸入 hello, 其它的俺還暫時還不理人喲';
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr);
echo $resultStr;
exit();
}
}
}
