3.3 接收事件推送消息
在基础接口中,事件消息只有关注和取消关注事件。用户关注和取消关注公众账号的时候将分别触发这两个消息。
3.3.1 关注/取消关注
用户关注微信公众账号时的界面如图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所示。
3.3.2 案例
本节将关注/取消关注事件消息通过代码实现,以便读者理解。代码如下所示:
<?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;
}
}
?>```
时间: 2025-01-28 13:00:44