接收用户消息是公众号开发的基础环节,通过对用户消息的正确识别才完成对应消息及事件的回复功能。
建议使用 php 7 及以上版本,如果您使用的版本小于 php 5.6 系统将使用 $GLOBALS["HTTP_RAW_POST_DATA"] 接收公众号转发的用户消息数据。
如果您的版本 为 5.6 并遇到 php 服务器报错 : always_populate_raw_post_data
请修改 php.ini :
always_populate_raw_post_data = -1
getMsg() 函数用于接收用户消息,并将消息数据保存至 graceWeChat 对象。
<?php class indexController extends grace{ public $graceWeChat; public function __construct(){ parent::__construct(); $this->graceWeChat = new \phpGrace\tools\graceWeChat(); } public function index(){ // 接收消息 $this->graceWeChat->getMsg(); } }
<?php // 接收到消息后消息保存在 graceWeChat 对象的属性内 : // $this 代表 graceWeChat 对象 $this->openId = $this->msg->FromUserName; // 用户 openid $this->ourOpenId = $this->msg->ToUserName; // 我方公众号 openid $this->msgType = $this->msg->MsgType; // 消息类型 $this->msgContent = $this->msg->Content; // 消息内容 $this->event = $this->msg->Event; // 事件 $this->EventKey = $this->msg->EventKey; // 事件对应的值
将 graceWeChat 对象的 deBug 属性设置为 true 可以记录消息到 ./log.html。
linux 服务器请保证框架分组目录的写入权限 : chmod -R 777 /web根目录/分组目录
<?php class indexController extends grace{ public $graceWeChat; public function __construct(){ parent::__construct(); $this->graceWeChat = new \phpGrace\tools\graceWeChat(); } public function index(){ // 接收消息 $this->graceWeChat->deBug = true; $this->graceWeChat->getMsg(); } }
访问 http://域名/分组名称/log.html 即可查看到用户消息数据( 请在项目正式发布时关闭调试,保证更高的运行效率 )。