微信首次关注推送消息

当我们关注一公共账号的时候就会收到公共账号推送的消息

官网文档是这样写的


<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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值