微信开发模式下关注自动回复官方给出的说明是:
推送XML数据包示例:
<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[FromUser]]></FromUserName> <CreateTime>123456789</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[subscribe]]></Event> </xml>
参数说明:
参数 | 描述 |
---|---|
ToUserName | 开发者微信号 |
FromUserName | 发送方帐号(一个OpenID) |
CreateTime | 消息创建时间 (整型) |
MsgType | 消息类型,event |
Event | 事件类型,subscribe(订阅)、unsubscribe(取消订阅) |
所以我们可以先获取MsgType,判断是否为event消息类型,如果是则获取Event,关于关注与取消关注的Event分别对应subscribe和unsubscribe,所以接下来判断Event类型是否为subscribe;如果是则发送消息:
事例代码:
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);
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$msgType = $postObj->MsgType;
$time = time();
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";
switch($msgType)
{
case "event":
$msgEvent=$postObj->Event;
//订阅自动回复
if($msgEvent=="subscribe")
{
$msgType = "text";
$contentStr = "欢迎你!";
$resultStr = sprintf(
$textTpl,
$fromUsername,
$toUsername,
$time,
$msgType,
$contentStr);
echo $resultStr;
}
break;
case "text":
$keyword = trim($postObj->Content);
if(!empty( $keyword ))
{
$msgType = "text";
$contentStr = "Welcome to wechat world!";
$resultStr = sprintf(
$textTpl,
$fromUsername,
$toUsername,
$time,
$msgType,
$contentStr);
echo $resultStr;
}else{
echo "Input something...";
}
break;
}
}else {
echo "";
exit;
}
}