微信关注公众号与输入内容自动回复开发实例代码

时间:2017-05-08 10:31:07 类型:PHP
字号:    

关注微信或者向微信公众号发送信息, 都可以自动回复内容,开发模式下怎么写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参数了
     		$this->responseMsg();   //关注公众号/输入hello都将会自动回复
		}else{ 
 			$this -> _check_signature();//验证消息的确来自微信服务器
                        //验证代码: http://www.ncyteng.com/news/show/169
		} 
	}

	public function responseMsg(){
	 //get post data, May be due to the different environments
  		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //接收微信发来的XML数据
  		//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); //消息内容
        $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 将会回复的内容
   				$contentStr = 'hello world!!!';
   				$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype,$contentStr);
   		 		echo $resultStr;
   		 		exit();            
   		}
   		else{
    		$contentStr = '现在只回复输入 hello, 其它的俺还暂时还不理人哟';
    		$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr);
    		echo $resultStr;
    		exit();
  			 }
 
 		 }
 		 
 		}

微信关注自动回复代码下载