Controller代码:
public function index(){
//获取微信发送确认的参数。
$signature = $_GET['signature'];
$timestamp = $_GET['timestamp'];
$nonce = $_GET['nonce'];
$echostr = $_GET['echostr'];
$token = 'weixin';
$array = array($token,$timestamp,$nonce);
sort($array);
$str = sha1( implode($array) );
if( $str==$signature && $echostr ){
echo $echostr;
exit;
}else{
$this->getMsg();
}
}
public function getMsg(){
//1,获取到微信推送过来post数据(xml格式)
$postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
//2,处理消息类型,并设置回复类型和内容
$postObj = simplexml_load_string($postArr);
//用户关注事件
if( strtolower($postObj->MsgType)=='event' && strtolower($postObj->Event)=='subscribe' ){
$Content = '北邮即兴剧团,感谢您的关注!智能回复系统期待与您对话。';
responseText($postObj,$Content);
}
//普通消息回复
//用户发送文本消息
if( strtolower($postObj->MsgType)=='text' && strtolower($postObj->Content)=='历史消息' ){
$array = array(
array(
'title'=>'hao123',
'description'=>"hao123 is very cool",
'picUrl'=>'https://www.baidu.com/img/bdlogo.png',
'url'=>'http://www.hao123.com',
),
//多图文直接添加即可!
);
responseNews($postObj,$array);
}
if( strtolower($postObj->MsgType)=='text' && strtolower($postObj->Content)!='历史消息' )
{
$Content = '您输入的是:'.$postObj->Content;
responseText($postObj,$Content);
}
//用户发送位置信息
if( strtolower($postObj->MsgType)=='location' ){
$Content = '您现在所处的位置为:'.$postObj->Label.'.经度为:'.$postObj->Location_Y.'.纬度为:'.$postObj->Location_X;
responseText($postObj,$Content);
}
公共函数库代码:
function responseText($postObj,$Content){
$FromUserName = $postObj->ToUserName;
$ToUserName = $postObj->FromUserName;
$MsgType = 'text';
$CreateTime = time();
$template = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$info = sprintf($template,$ToUserName,$FromUserName,$CreateTime,$MsgType,$Content);
echo $info;
}
//回复图文消息
function responseNews($postObj,$array){
$ToUserName = $postObj->FromUserName;
$FromUserName = $postObj->ToUserName;
$CreateTime = time();
$MsgType = 'news';
$template = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<ArticleCount>".count($array)."</ArticleCount>
<Articles>";
foreach($array as $key=>$value){
$template .="<item>
<Title><![CDATA[".$value['title']."]]></Title>
<Description><![CDATA[".$value['description']."]]></Description>
<PicUrl><![CDATA[".$value['picUrl']."]]></PicUrl>
<Url><![CDATA[".$value['url']."]]></Url>
</item>";
}
$template .="</Articles>
</xml> ";
$info = sprintf( $template, $ToUserName, $FromUserName, $CreateTime, $MsgType );
echo $info;
}