今天要讲的是代微信公众号接收消息并进行回复,这里要用到的就是咱们之前在微信公众号三方平台开发【帐号注册、平台创建】里写到的“公众号消息与事件接收URL”,在接收的目标方法里,我们首先要获取到微信推送过来post数据(xml格式),然后对其进行解密操作,从而得到消息内容。
这里我们会用到微信公众号三方平台开发【component_verify_ticket篇】里同样的解密方法进行数据的加解密操作,如下: require_once(dirname(__FILE__).'/wxBizMsgCrypt.php');
//encodingAesKey和token均为申请三方平台是所填写的内容
$encodingAesKey = '公众号消息加解密Key';
$token = '公众号消息校验Token';
$appId = '三方平台appid';
$timeStamp = empty ( $_GET ['timestamp'] ) ? "" : trim ($_GET ['timestamp'] );
$nonce = empty ( $_GET ['nonce'] ) ? "" : trim ( $_GET['nonce'] );
$msg_sign = empty ( $_GET ['msg_signature'] ) ? "" : trim( $_GET ['msg_signature'] );
$pc = new \WXBizMsgCrypt ( $token, $encodingAesKey, $appId );
//获取到微信推送过来post数据(xml格式)
$postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
$msg = '';
$errCode= $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $postArr,$msg);
解密后,当$errCode返回值为0时,代表解密成功,下一步我们就需要对消息进行解析处理:
$postObj =simplexml_load_string($msg,'SimpleXMLElement',LIBXML_NOCDATA);
然后,根据不同的消息类型做出相应的回复,当消息类型为“event”且为用户关注事件时,微信公众号给用户自动回复一个文本消息:
if (strtolower($postObj -> MsgType) == 'event'){
//如果是关注subscribe事件
if(strtolower($postObj->Event == 'subscribe')){
$public_name= strval($postObj->ToUserName);
$map['public_name']=$public_name;
$cont =M('Subscribe')->where($map)->find();
//回复用户消息
$content =$cont['content'];
responseText($postObj,$content);
}
}
根据关键字回复图文消息:
if(strtolower($postObj -> MsgType) == 'text' &&trim($postObj->Content)=='图文'){
//这一步可从数据库中查询得到
$arr = array(
array(
'title'=> 'test1',
'description'=> 'test1',
'picUrl'=>'http://mmbiz.qpic.cn/mmbiz/mLiaE7fSUysSbbqzicX2LVsLL1HsXMRV0m6uicfiaSX9Aic43BA5vnpFOBMWAoEuaVDicoOX4HzGT8OT5QK6DRs14VkQ/0',
'url'=>'https://mp.weixin.qq.com/s?__biz=MjM5NzY4MDc0MA==&tempkey=mKI6U0rlJZofvceyQdxTPAYtneMxKyhWy52ytbUZfOJzFEHMDqmYTQLQWrkrSRky&appmsgid=10000002&itemidx=1&sign=99baf31f45e2357af575c63b5b303b6a#wechat_redirect',
),
array(
'title'=> 'test2',
'description'=> 'test2',
'picUrl'=> 'http://mmbiz.qpic.cn/mmbiz_jpg/mLiaE7fSUysTFDEZQTOvXleYwYqFN1JeLwM66Zg7dHjK3aHQxdVtwGTJgzuKJRuZCBHljIvVLkvZ2CADJ6paJYQ/0?wx_fmt=jpeg',
'url'=>'https://mp.weixin.qq.com/s?__biz=MjM5NzY4MDc0MA==&tempkey=mKI6U0rlJZofvceyQdxTPDXw5wcPw4rpHzkwOv4U7kDY1V%2BUUirAB0C9oEEsX5HQB8Uv1Ut2zj3buNkRPh6KNYWVyTaxebMkb8IcD9FjNbpcqY0mdRbCxRnbIjtmNBd37cKXm3Egbo1KWdkSEy5NZg%3D%3D&chksm=315123030626aa15c3e454afbd931ec3458149b13370999b16bc72b876326977e7d68b406a8c#rd',
)
);
responseNews($postObj,$arr);
}
其他关键字回复:
$public_name= strval($postObj->ToUserName);
$keyword = strval(trim($postObj-> Content));
$log['public_name']=$public_name;
$log['keyword'] =array('like','%'.$keyword.'%');
$con =M('Keyword')->where($log)->select();
foreach ($con as $vo=> $k){
$conn=$con[$vo]['content'];
}
if($conn){
$content =$conn;
}else{
$lg['public_name']=$public_name;
$lg['keyword']='';
$con =M('Keyword')->where($lg)->select();
foreach($con as $vo => $k){
$conn=$con[$vo]['content'];
}
$content =$conn;
}
responseText($postObj,$content);
以上用到的responseText()、responseNews()鉴于代码模块化,而且方便复用,所以单独用方法写出,其他不多说了,具体见代码:
1)回复文本消息
function responseText($postObj,$content){
$template ="<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$fromUser = $postObj ->ToUserName;
$toUser = $postObj -> FromUserName;
$time = time();
$msgType = 'text';
$res =sprintf($template,$toUser,$fromUser,$time,$msgType,$content);
$encodingAesKey = '公众号消息加解密Key';
$token ='公众号消息校验Token';
$appId = '三方平台appid';
$pc = new \WXBizMsgCrypt ($token, $encodingAesKey, $appId );
$encryptMsg = '';
$errCode =$pc->encryptMsg($res,$_GET ['timestamp'], $_GET ['nonce'], $encryptMsg);
if($errCode ==0){
$res = $encryptMsg;
}
echo $res;
}
2)回复图文消息
function responseNews($postObj,$arr){
$toUser = $postObj -> FromUserName;
$fromUser = $postObj -> ToUserName;
$template ="<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<ArticleCount>".count($arr)."</ArticleCount>
<Articles>";
foreach($arr as $k=>$v){
$template.="<item>
<Title><![CDATA[".$v['title']."]]></Title>
<Description><![CDATA[".$v['description']."]]></Description>
<PicUrl><![CDATA[".$v['picUrl']."]]></PicUrl>
<Url><![CDATA[".$v['url']."]]></Url>
</item>";
}
$template.="</Articles>
</xml>";
$time = time();
$msgType = 'news';
$res =sprintf($template,$toUser,$fromUser,$time,$msgType);
$encodingAesKey = '公众号消息加解密Key';
$token ='公众号消息校验Token';
$appId = '三方平台appid';
$pc = new \WXBizMsgCrypt ($token, $encodingAesKey, $appId );
$encryptMsg = '';
$errCode =$pc->encryptMsg($res,$_GET ['timestamp'], $_GET ['nonce'], $encryptMsg);
if($errCode ==0){
$res = $encryptMsg;
}
echo $res;
}
需要注意的是,在代微信公众号实现其功能的时候,接收的消息都需要解密,对回复的内容也必须进行加密再进行回复。
接收消息事件完整代码:
public function reponseMsg(){
require_once(dirname(__FILE__).'/wxBizMsgCrypt.php');
//encodingAesKey和token均为申请三方平台是所填写的内容
$encodingAesKey = '公众号消息加解密Key';
$token = '公众号消息校验Token';
$appId = '三方平台appid';
$timeStamp = empty ($_GET ['timestamp'] ) ? "" : trim ( $_GET ['timestamp'] );
$nonce = empty ( $_GET['nonce'] ) ? "" : trim ( $_GET ['nonce'] );
$msg_sign = empty ($_GET ['msg_signature'] ) ? "" : trim ( $_GET ['msg_signature'] );
$pc = new\WXBizMsgCrypt ( $token, $encodingAesKey, $appId );
//获取到微信推送过来post数据(xml格式)
$postArr =$GLOBALS['HTTP_RAW_POST_DATA'];
$msg = '';
$errCode =$pc->decryptMsg($msg_sign, $timeStamp, $nonce, $postArr,$msg);
if($errCode == 0){
//处理消息类型,并设置回复类型和内容
$postObj =simplexml_load_string($msg,'SimpleXMLElement',LIBXML_NOCDATA);
//判断该数据包是否是订阅(用户关注)的事件推送
if(strtolower($postObj -> MsgType) == 'event'){
//如果是关注subscribe事件
if(strtolower($postObj -> MsgType) == 'event'){
//如果是关注subscribe事件
if(strtolower($postObj->Event == 'subscribe')){
$public_name= strval($postObj->ToUserName);
$map['public_name']=$public_name;
$cont= M('Subscribe')->where($map)->find();
//回复用户消息
$content= $cont['content'];
responseText($postObj,$content);
}
}
}
//用户发送某一图文关键字的时候,回复图文消息
if(strtolower($postObj-> MsgType) == 'text' && trim($postObj->Content)=='图文'){
//这一步可从数据库中查询得到
$arr= array(
array(
'title'=> 'test1',
'description'=> 'test1',
'picUrl'=>'http://mmbiz.qpic.cn/mmbiz/mLiaE7fSUysSbbqzicX2LVsLL1HsXMRV0m6uicfiaSX9Aic43BA5vnpFOBMWAoEuaVDicoOX4HzGT8OT5QK6DRs14VkQ/0',
'url'=>'https://mp.weixin.qq.com/s?__biz=MjM5NzY4MDc0MA==&tempkey=mKI6U0rlJZofvceyQdxTPAYtneMxKyhWy52ytbUZfOJzFEHMDqmYTQLQWrkrSRky&appmsgid=10000002&itemidx=1&sign=99baf31f45e2357af575c63b5b303b6a#wechat_redirect',
),
array(
'title'=> 'test2',
'description'=> 'test2',
'picUrl'=> 'http://mmbiz.qpic.cn/mmbiz_jpg/mLiaE7fSUysTFDEZQTOvXleYwYqFN1JeLwM66Zg7dHjK3aHQxdVtwGTJgzuKJRuZCBHljIvVLkvZ2CADJ6paJYQ/0?wx_fmt=jpeg',
'url'=>'https://mp.weixin.qq.com/s?__biz=MjM5NzY4MDc0MA==&tempkey=mKI6U0rlJZofvceyQdxTPDXw5wcPw4rpHzkwOv4U7kDY1V%2BUUirAB0C9oEEsX5HQB8Uv1Ut2zj3buNkRPh6KNYWVyTaxebMkb8IcD9FjNbpcqY0mdRbCxRnbIjtmNBd37cKXm3Egbo1KWdkSEy5NZg%3D%3D&chksm=315123030626aa15c3e454afbd931ec3458149b13370999b16bc72b876326977e7d68b406a8c#rd',
)
);
responseNews($postObj,$arr);
}else{
//当微信用户发送关键字,公众号回复对应内容
$public_name=strval($postObj->ToUserName);
$keyword= strval(trim($postObj -> Content));
$log['public_name']=$public_name;
$log['keyword']= array('like','%'.$keyword.'%');
$con= M('Keyword')->where($log)->select();
foreach($con as $vo => $k){
$conn=$con[$vo]['content'];
}
if($conn){
$content= $conn;
}else{
$lg['public_name']=$public_name;
$lg['keyword']='';
$con= M('Keyword')->where($lg)->select();
foreach($con as $vo => $k){
$conn=$con[$vo]['content'];
}
$content= $conn;
}
responseText($postObj,$content);
}
}
}