美文网首页
获取用户消息并保存

获取用户消息并保存

作者: 海藻web开发 | 来源:发表于2017-06-19 16:52 被阅读0次

当普通微信用户向公众账号发消息时,微信服务器将POST消息的XML数据包到开发者填写的URL上。我们需要对接收的XML进行解析获取关键数据: 发送者的openId 消息类型、消息内容等。
····

 <?php
/**
  * wechat php test
  */

//define your token
define("TOKEN", "wxtext2017");

class weChat{
    public $postObj;      //接收到的xml对象
    public $openId;       //客户的openId
    public $ourOpenId;    //我方公众号的openId
    public $msgType;      //客户消息的类型
    //构造函数用于接收消息
    public function __construct(){
        if(!empty($GLOBALS["HTTP_RAW_POST_DATA"])){
            $postStr=$GLOBALS["HTTP_RAW_POST_DATA"];
                //将xml转换成对象
                libxml_disable_entity_loader(true);
                $this->postObj      = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $this->openId       = $this->postObj->FromUserName;
                $this->ourOpenId    = $this->postObj->ToUserName;
                $this->msgType      = $this->postObj->MsgType;
        }
    }
}
$wechatObj = new weChat();
//接收消息的一个测试
$data = "客户的消息类型为: {$wechatObj->msgType}, 
客户的openId: {$wechatObj->openId}, 
我方公众号的openId: {$wechatObj->ourOpenId}, 
客户的消息内容:{$wechatObj->postObj->Content}
";
file_put_contents('log.txt', $data);
?>

用户向公众号发送消息后 这段代码将自动保存到文件中log.tex 如果没有 则新建 里边会保存 消息内容以及详细信息

注意: 如果不回复任何信息 公众号会提示公众号暂时无法提供服务,请稍后重试

相关文章

网友评论

      本文标题:获取用户消息并保存

      本文链接:https://www.haomeiwen.com/subject/jztnqxtx.html