当我们关注一公共账号的时候就会收到公共账号推送的消息
官网文档是这样写的
<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[FromUser]]></FromUserName> <CreateTime>123456789</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[subscribe]]></Event> </xml>注意这个是我们接受到得xml格式的数据,不是发送的,我们是从这里获取到用户关注的事件的,具体解释官方如下
参数 | 描述 |
---|---|
ToUserName | 开发者微信号 |
FromUserName | 发送方帐号(一个OpenID) |
CreateTime | 消息创建时间 (整型) |
MsgType | 消息类型,event |
Event | 事件类型,subscribe(订阅)、unsubscribe(取消订阅) |
<?php
/**
* wechat php test
*/
include_once('tianqi.php');
include_once('robot.php');
//define your token
define("TOKEN", "wood");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->responseMsg();
class wechatCallbackapiTest
{
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;
$keyword = trim($postObj->Content);
$time = time();
//捕获事件
$type=$postObj->MsgType;//获取消息类型
$event = $postObj->Event;//获取事件类型
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
if(!empty( $keyword ))
{
$robot = new robot($keyword);
$cont = $robot->get_content();
$msgType = "text";
$contentStr = $cont;
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}else{
echo "Input something...";
}
if($type=='event'){
if($event=="subscribe"){//首次关注
$msgType = "text";
$contentStr = "欢迎您关注木头的微信空间,更多功能正在开发中!";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}
}
}else {
echo "";
exit;
}
}
}
?>
经测试关注的时候可以正常接受公共账号推送来的消息
关注微信账号:z510168343