获取用户消息并保存

当普通微信用户向公众账号发消息时,微信服务器将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 如果没有 则新建 里边会保存 消息内容以及详细信息

注意: 如果不回复任何信息 公众号会提示公众号暂时无法提供服务,请稍后重试
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容