`

php开发微信公众账号开发包开发教程五之请求响应处理

    博客分类:
  • php
阅读更多
第三篇文章已经讲解了如何封装请求信息,现在将介绍如何使用请求消息。
首先我们针对接收到的每种消息定义自己的请求消息处理器,先定义基类处理器:
/**
 * 消息处理基类
 * @author Administrator
 *
 */
 abstract class AbstractMessageProcessor {
 	public $requestMessage ;//消息请求对象 AbstractBaseRequestMessage的子类
 	public $time ;//响应请求时间
	/**
	 * 
	 * @param $requestMessage 类型为:AbstractBaseRequestMessage
	 */
	public function __construct($requestMessage){
		$this->requestMessage = $requestMessage;
        $this->time = time();
	}
	/**
	 * 处理消息
	 * @param $message
	 */
	abstract  public function processMessage();

}

然后大家可根据自己需求自行实现自己的请求消息处理器,我的实现如下,比较简单的业务功能:
/**
 * 文本消息处理器
 * @author Administrator
 *
 */
class TextMessageProcessor extends AbstractMessageProcessor {
	/**
	 * @param unknown_type $message
	 */
	public function processMessage() {
					if(!empty( $this->requestMessage->keyword ))
	                {	
                        if(strpos($this->requestMessage->keyword, "天气") !== false){
                            $ctity = str_replace("天气","",$this->requestMessage->keyword);
                            if(!empty($ctity)){
                            
                             	$message = getWeather($ctity);
		               			 MessageUtil::sendTextMessage($this->requestMessage->fromUsername, $this->requestMessage->toUsername,  $message);
                            
                            
                            }else {
                           		 $message = "请回复格式:\n 天气+地点,例如:天气成都 ";
               		  			MessageUtil::sendTextMessage($this->requestMessage->fromUsername, $this->requestMessage->toUsername,  $message);
                            }
                                
                        
                        }else if(strpos($this->requestMessage->keyword, "翻译") !== false){
                        
                         	$ctity = str_replace("翻译","",$this->requestMessage->keyword);
                            if(!empty($ctity)){
                            
                             	$message = tanslate($ctity);
		               			 MessageUtil::sendTextMessage($this->requestMessage->fromUsername, $this->requestMessage->toUsername, $message);
                            
                            
                            }else {
                           		 $message = "请回复格式:\n 翻译+要翻译的词 ";
               		  			 MessageUtil::sendTextMessage($this->requestMessage->fromUsername, $this->requestMessage->toUsername,  $message);
                            }
                        
                        }else if("1" == $this->requestMessage->keyword){
                        		 $message = "主菜单:\n 翻译:翻译+要翻译的词\n天气预报:天气+地点  \n 笑话:2 \n搞笑图片 3\n 主菜单:1";
               		  			 MessageUtil::sendTextMessage($this->requestMessage->fromUsername, $this->requestMessage->toUsername,  $message);
                        	
                        } else if("2" == $this->requestMessage->keyword){
                        		$message =getjoke();
               		  			 MessageUtil::sendTextMessage($this->requestMessage->fromUsername, $this->requestMessage->toUsername,  $message);
                        }else if("3" == $this->requestMessage->keyword){
                        	   sendJokeImage($this->requestMessage->fromUsername, $this->requestMessage->toUsername);
                        }else if("4" == $this->requestMessage->keyword){
                        		$mediaId = "n7HVI2spZKcafRBTErrgm-ptqdY_F5MzSueTLJch1TpeM8l07hITsoZlM5BuPfg7";//是记录在微信服务器中的id 不能是本地服务器的图片资源{$this->requestMessage->basePath}/res/images/erweima.jpg" ;
                        	    MessageUtil::sendImageMessage($this->requestMessage->fromUsername, $this->requestMessage->toUsername,  "n7HVI2spZKcafRBTErrgm-ptqdY_F5MzSueTLJch1TpeM8l07hITsoZlM5BuPfg7");
                        }else if("5" == $this->requestMessage->keyword){
                        		$title = "愿得一人心(剧场版)-李行亮,雨宗林";
                        		$description = ",愿得一人心(剧场版)在线试听,MP3免费下载,愿得一人心(剧场版)歌词下载_百度音乐-听到极致";
                        		$musicUrl="{$this->requestMessage->basePath}/res/music/父亲.mp3";
                        		$hQMusicUrl=$musicUrl;
                        		$thumbMediaId = "";
                        	    MessageUtil::sendMusicMessage($this->requestMessage->fromUsername,$this->requestMessage->toUsername,$title,$description,$musicUrl,$hQMusicUrl,null);
                        }else if("6" == $this->requestMessage->keyword){
               		  			 MessageUtil::sendTextMessage($this->requestMessage->fromUsername, $this->requestMessage->toUsername,  $this->requestMessage->fromUsername);
                        }else{
                         		$message = talk($this->requestMessage->keyword);
               		  			 MessageUtil::sendTextMessage($this->requestMessage->fromUsername, $this->requestMessage->toUsername, $message);
                        }
	                	
		           
	                }else{
		                 MessageUtil::sendTextMessage($this->requestMessage->fromUsername, $this->requestMessage->toUsername, "input some thing...");
	                }
	}

}
/**
 * Event类型消息处理器
 * @author Administrator
 *
 */
class EventMessageProcessor extends AbstractMessageProcessor {
	/**
	 * 
	 */
	public function processMessage() {
	 				
               		  if($this->requestMessage->customEvent == "subscribe"){
		               	  	$picUlr = "{$this->requestMessage->$requestMessage->basePath}/res/images/erweima.jpg" ;
					    	$url = "{$this->requestMessage->$requestMessage->basePath}/res/images/erweima.jpg" ;
					    	$description = "你好,欢迎关注程序员.\n主菜单:\n翻译:翻译+要翻译的词\n天气预报:天气+地点 \n笑话:2\n搞笑图片: 3\n主菜单:1";
					    	$title = "欢迎关注程序员";
                 			MessageUtil::sendOneTextImageMessage($this->requestMessage->fromUsername, $this->requestMessage->toUsername,$title,$description, $picUlr,$url);
               		  }else if($this->requestMessage->customEvent == "CLICK") {
               		  	switch ($this->requestMessage->eventKey){
               		  		case "key_dpdz" : {
								$message="<a href ='http://api.map.baidu.com/geocoder?address=成都五块石客运站&output=html&src=hanfei|shuiguo'>我的位置</a>";
               		  			MessageUtil::sendTextMessage($this->requestMessage->fromUsername, $this->requestMessage->toUsername,  $message);
								break ;
               		  		}
               		  		case  "key_rxsg" : {
               		  			$picUlr = "http://mmbiz.qpic.cn/mmbiz/lp77EI7LTyp9C6bGT7zxlASgSGibIbTpRFwuruZFgnvDQlPIv7rAZ7ibAV6vCl6dgc1dgIMiaic3icbFcctvccMh0ibA/0" ;
						    	$url = "http://mp.weixin.qq.com/s?__biz=MzA4NjM5NDQyOQ==&mid=201608824&idx=1&sn=c96cab1d0fb61a174c617a02099651b9#rd" ;
						    	$description = "蓝莓营养价值 ①花青素:\n是一种非常重要的植物水溶性色素,属于纯天然的抗衰老营补充剂,是目前人类发现的最有效的抗氧化生物活性剂。②总酸和有机酸:具有广泛的生物学活性,特别在抗肿瘤等方面作用突出。";
						    	$title = "热销水果信息";
               	  				MessageUtil::sendOneTextImageMessage($this->requestMessage->fromUsername, $this->requestMessage->toUsername, $title,$description, $picUlr,$url);
               		  			break ;
               		  		}
               		  	}
               		  	
               		  }
	}

	
}
/**
 * 图片类型消息处理器
 * @author Administrator
 *
 */
class ImageMessageProcessor extends AbstractMessageProcessor{
	/**
	 * 
	 */
	public function processMessage() {
		$message = "你发送的是图片";
        MessageUtil::sendTextMessage($this->requestMessage->fromUsername, $this->requestMessage->toUsername, $message);
	}

	
}
/**
 * 声音类型消息处理器
 * @author Administrator
 *
 */
class VoiceMessageProcessor extends AbstractMessageProcessor{
	/**
	 * 
	 */
	public function processMessage() {
		$message = "你发送的是声音";
       MessageUtil::sendTextMessage($this->requestMessage->fromUsername, $this->requestMessage->toUsername, $message);
	}

	
}
/**
 * 视频类型消息
 * @author Administrator
 *
 */
class VideoMessageProcessor extends AbstractMessageProcessor{
	/**
	 * 
	 */
	public function processMessage() {
		$message = "你发送的视频";
        MessageUtil::sendTextMessage($this->requestMessage->fromUsername, $this->requestMessage->toUsername, $message);
	}

	
}
/**
 * 地理位置消息类型
 * @author Administrator
 *
 */
class LocationMessageProcessor extends AbstractMessageProcessor{
	/**
	 * 
	 */
	public function processMessage() {
		$message = "你发送的地理位置";
        MessageUtil::sendTextMessage($this->requestMessage->fromUsername, $this->requestMessage->toUsername,  $message);
	}

	
}
/**
 * 连接类型消息
 * @author Administrator
 *
 */
class LinkMessageProcessor extends AbstractMessageProcessor{
	/**
	 * 
	 */
	public function processMessage() {
		$message = "你发送的是连接";
        MessageUtil::sendTextMessage($this->requestMessage->fromUsername, $this->requestMessage->toUsername, $message);
	}

	
}

然后创建消息处理器的工厂类:
/**
 * 消息处理器工厂类
 * @author Administrator
 *
 */
class MessageProcessFactory {
	/**
	 * 创建处理器工厂方法
	 * @param 得到请求解析的xml对象 $postObj
	 */
	static function createMessageProcess($postObj) {
		$messageType = $postObj->MsgType;
		switch ($messageType){
			case "event":{
				return  new EventMessageProcessor(new EventRequestMessage($postObj));
			}
			case "text" :{
				return  new TextMessageProcessor(new TextRequsetMessage($postObj));
			}
			case "image":{
				return  new ImageMessageProcessor(new ImageRequestMessage($postObj));
			}
			case "voice" :{
				return  new VoiceMessageProcessor(new VoiceMessageProcessor($postObj));
			}
			case "video":{
				return  new VideoMessageProcessor(new VideRequestMessage($postObj));
			}
			case "location" :{
				return  new LocationMessageProcessor(new LocationRequestMessage($post));
			}
			case "link":{
				return  new LinkMessageProcessor(new LinkMessageProcessor($postObj));
			}
			default:{
				return  new TextMessageProcessor(new TextRequsetMessage($postObj));
			}
		}
	}
}

到此请求和响应消息基本封装完毕,如需可仔细扩充。最后看看如何处接收请求,只需在最开始的index.php中的responseMsg方法中加入如下代码,
  public function responseMsg()
    {
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
      	//extract post data
		if (!empty($postStr)){
                
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $messageProcessor = MessageProcessFactory::createMessageProcess($postObj);
                if($messageProcessor!=null){
                	$messageProcessor->processMessage();
                }
			

        }else {
        	echo "";
        	exit;
        }
    }

完整的index.php代码:
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->responseMsg();


class wechatCallbackapiTest
{
	public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }

    public function responseMsg()
    {
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
      	//extract post data
		if (!empty($postStr)){
                
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $messageProcessor = MessageProcessFactory::createMessageProcess($postObj);
                if($messageProcessor!=null){
                	$messageProcessor->processMessage();
                }
			

        }else {
        	echo "";
        	exit;
        }
    }

到此一个简单php微信公众号工具包开发完成,等有时间将写更详细的教程,最后附一张图片,源码下载地址http://download.csdn.net/detail/ybhanxiao/7223847
  • 大小: 181 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics