本节书摘来自华章出版社《微信公众平台开发最佳实践》一 书中的第3章,第3.3节,作者:方倍工作室,更多章节内容可以访问云栖社区“华章计算机”公众号查看。
在基础接口中,事件消息只有关注和取消关注事件。用户关注和取消关注公众账号的时候将分别触发这两个消息。
用户关注微信公众账号时的界面如图3-14所示,单击“关注”按钮,微信公众账号将收到关注事件。用户关注微信公众账号时的XML数据格式如下所示:
<xml> <ToUserName><![CDATA[gh_b629c48b653e]]></ToUserName> <FromUserName><![CDATA[ollB4jv7LA3tydjviJp5V9qTU_kA]]></FromUserName> <CreateTime>1372307736</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[subscribe]]></Event> <EventKey><![CDATA[]]></EventKey> </xml>``` 用户取消关注微信公众账号时的界面如图3-15所示,单击“取消关注”按钮,微信公众账号将收到取消关注事件。 <div style="text-align: center"><img src="https://yqfile.alicdn.com/9a71735fa3b60d01d6f7736973559e094d9f4312.png" width="" height=""> </div> 用户取消关注微信公众账号时的XML数据格式如下所示: <ToUserName><![CDATA[gh_b629c48b653e]]></ToUserName> <FromUserName><![CDATA[ollB4jqgdO_cRnVXk_wRnSywgtQ8]]></FromUserName> <CreateTime>1372309890</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[unsubscribe]]></Event> <EventKey><![CDATA[]]></EventKey>`关注及取消关注事件消息的参数及描述如表3-13所示。
本节将关注/取消关注事件消息通过代码实现,以便读者理解。代码如下所示:
<?php // // 关注/取消关注事件消息 // 微信公众账号关注与取消关注事件消息 // define("TOKEN", "weixin"); $wechatObj = new wechatCallbackapiTest(); if (!isset($_GET['echostr'])) { $wechatObj->responseMsg(); }else{ $wechatObj->valid(); } class wechatCallbackapiTest { public function valid() { $echoStr = $_GET["echostr"]; if($this->checkSignature()){ echo $echoStr; exit; } } private function checkSignature() { $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr); $tmpStr = implode($tmpArr); $tmpStr = sha1($tmpStr); if($tmpStr == $signature){ return true; }else{ return false; } } public function responseMsg() { $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; if (!empty($postStr)){ $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $RX_TYPE = trim($postObj->MsgType); switch ($RX_TYPE) { case "event": $result = $this->receiveEvent($postObj); break; } echo $result; }else { echo ""; exit; } } private function receiveEvent($object) { $content = ""; switch ($object->Event) { case "subscribe": //关注事件 $content = "欢迎关注方倍工作室"; break; case "unsubscribe": //取消关注事件 $content = ""; break; } $result = $this->transmitText($object, $content); return $result; } private function transmitText($object, $content) { $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[%s]]></Content> </xml>"; $result = sprintf($textTpl, $object->FromUserName, $object-> ToUserName, time(), $content); return $result; } } ?>``` 相关资源:微信公众平台开发【接收消息】接收普通消息源代码