虽然我们知道了微信服务器发送给我们的各种消息格式, 但是有时我们需要知道微信服务器发送给我们的各种消息的内容.
那么我们能想到的最简单的方法就是在回复的消息中输出我们接收到的消息的每个字段的内容. 现在我们对`Wechat-php`框架做简单的修改.
我们查看`Wechat.php`中的`savePostData`函数, 这个函数中我们可以看到,从解密和读取xml数据后, 接收到的数据被作为一个`array`储存在`$this->request`字段中.
我们要做的就是把`$this->request`字段遍历出来并拼接成一个字符串, 提供给需要的地方使用就可以了.
- private function savePostData() {
- $xml = '';
- if ($this->encrypted) {
- $errCode = $this->msgCryptor->decryptMsg($_GET['msg_signature'], $_GET['timestamp'], $_GET['nonce'], $GLOBALS['HTTP_RAW_POST_DATA'], $xml);
- if ($errCode != 0) exit($errCode);
- } else {
- $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
- }
- $xml = (array) simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
- // 微信服务器发送过来的数据被存在$this->request中
- // 之前的代码查看是否需要对POST数据进行解密操作
- $this->request = array_change_key_case($xml, CASE_LOWER);
- // 将数组键名转换为小写,提高健壮性,减少因大小写不同而出现的问题
- }
复制代码
我们新写一个函数,实现把`$this->request`转换为字符串的功能:
现在我们在`index.php`中处理所以消息类型和事件类型的回调函数, 所有的处理都是一样的,返回微信服务器发送过来的内容.
- protected function onSubscribe() {
- $this->responseText($this->getRequestTxt());
- }
- protected function onUnsubscribe() {
- $this->responseText($this->getRequestTxt());
- }
- protected function onText() {
- $this->responseText($this->getRequestTxt());
- }
- protected function onImage() {
- $this->responseText($this->getRequestTxt());
- }
- protected function onLocation() {
- $this->responseText($this->getRequestTxt());
- }
- protected function onLink() {
- $this->responseText($this->getRequestTxt());
- }
- protected function onClick() {
- $this->responseText($this->getRequestTxt());
- }
- protected function onEventLocation() {
- $this->responseText($this->getRequestTxt());
- }
- protected function onVoice() {
- $this->responseText($this->getRequestTxt());
- }
- protected function onScan() {
- $this->responseText($this->getRequestTxt());
- }
- protected function onUnknown() {
- $this->responseText($this->getRequestTxt());
- }
复制代码
修改完成后上传到我们的公众号服务器,然后在微信中向公众号发送消息, 就可以看见每种消息的回显了.
附件中有全部工程代码.
|