微信开发中的消息验证与消息回复
处理逻辑
判断微信服务器传来的数据是否含有名为echostr的GET参数 有则进行服务器消息验证(valid) 没有则微信推送过来的是一条消息,需要我们处理。
消息类型分为
1)事件类型:用户关注/取消关注事件、扫描二维码事件……
2)被动回复类型:用户发送过来一条文字、图片、语音……
然后根据需求回复相应的文字、图片、图文….
代码示例
MsgType)=='event'){
if(strtolower($postObj->Event)=='subscribe'){//用户关注事件
$content="欢迎关注XXXX";
responseText($postObj, $content);
}
}else if(strtolower($postObj->MsgType)=='text'){
switch(trim($postObj->Content)){
/*被动回复文本信息*/
case 'test':
$content="this is test!";
responseText($postObj, $content);
break;
case 'time':
$content="现在是北京时间:".date("Y-m-d H:i:s",time());
responseText($postObj, $content);
break;
case 'website':
$content="乘风破浪";
responseText($postObj, $content);
break;
/*被动回复图文信息*/
case 'news':
$arr=array(
array(
'title'=>'我的csdn博客',
'description'=>'欢迎访问我的csdn博客',
'picUrl'=>'http://avatar.csdn.net/9/5/4/1_somehow1002.jpg',
'url'=>'http://blog.csdn.net/somehow1002',
),
array(
'title'=>'开源中国',
'description'=>'。。。。。',
'picUrl'=>'https://www.oschina.net/img/ie/logo_osc.png','',
'url'=>'https://www.oschina.net/',
),
);
responseNews($postObj, $arr);
break;
default:
$content="sorry, I don't understand!";
$res->responseText($postObj, $content);
break;
}
}
}
function responseText($postObj,$content){
/* @文字消息回复格式
*
*
*
*
* 12345678
*
*
*
*
* */
$fromUserName=$postObj->ToUserName;
$toUserName=$postObj->FromUserName;
$time=time();
$msgType='text';
$template="
%s
";
echo sprintf($template,$toUserName,$fromUserName,$time,$msgType,$content);
}
function responseNews($postObj,$arr){
/* @图文消息回复格式
* #一个item一则图文消息
*
*
*
*
* 12345678
*
* 2
*
* -
*
*
*
*
*
* -
*
*
*
*
*
*
*
*
* */
$fromUserName=$postObj->ToUserName;
$toUserName=$postObj->FromUserName;
$time=time();
$msgType='text';
$template="
%s
".count($arr)."
";
foreach($arr as $v){
$template.="
-
";
}
$template.="
";
echo sprintf($template,$toUserName,$fromUserName,time());
}