Table of Contents
回复内容:
我经常这么干的
Home Backend Development PHP Tutorial 微信公众平台 - php开发微信公众号,用户发送消息后,公众号没响应,怎么调试呢?

微信公众平台 - php开发微信公众号,用户发送消息后,公众号没响应,怎么调试呢?

Jun 06, 2016 pm 08:18 PM
php Micro-channel public platform debug

我是用thinkphp开发的,这是消息推送地址的代码:

<code><?php namespace Home\Controller;
use Think\Controller;

class WeixinController extends Controller {
    var $data = array ();
    var $wxcpt, $sReqTimeStamp, $sReqNonce, $sEncryptMsg;

    public function index() {
        // 删除微信传递的token干扰
        unset ( $_REQUEST ['token'] );
        $appid = '**********';
        $token = "baofan1994";
        $encodingaeskey = "*********************************";
        $content = wp_file_get_contents ( 'php://input' );
        ! empty ( $content ) || die ( '这是微信请求的接口地址,直接在浏览器里无效' );

        if ($_GET ['encrypt_type'] == 'aes') {
            vendor ( 'WXBiz.wxBizMsgCrypt' );

            $this->sReqTimeStamp = I ( 'get.timestamp' );
            $this->sReqNonce = I ( 'get.nonce' );
            $this->sEncryptMsg = I ( 'get.msg_signature' );

            $this->wxcpt = new \WXBizMsgCrypt ( $token, $encodingaeskey, $appid);

            $sMsg = ""; // 解析之后的明文
            $errCode = $this->wxcpt->DecryptMsg ( $this->sEncryptMsg, $this->sReqTimeStamp, $this->sReqNonce, $content, $sMsg );
            if ($errCode != 0) {

                exit ();
            } else {
                // 解密成功,sMsg即为xml格式的明文
                $content = $sMsg;
            }
        }

        $data = new \SimpleXMLElement ( $content );
        // $data || die ( '参数获取失败' );
        foreach ( $data as $key => $value ) {
            $this->data [$key] = safe ( strval ( $value ) );
        }

        $this->replyText("好好学习");
    }

    /* 回复文本消息 */
    public function replyText($content) {
        $msg ['Content'] = $content;
        $this->_replyData ( $msg, 'text' );
    }

    /* 发送回复消息到微信平台 */
    private function _replyData($msg, $msgType) {
        $msg ['ToUserName'] = $this->data ['FromUserName'];
        $msg ['FromUserName'] = $this->data ['ToUserName'];
        $msg ['CreateTime'] = NOW_TIME;
        $msg ['MsgType'] = $msgType;

        if ($_REQUEST ['doNotInit']) {
            dump ( $msg );
            exit ();
        }

        $xml = new \SimpleXMLElement ( '<xml></xml>' );
        $this->_data2xml ( $xml, $msg );
        $str = $xml->asXML ();

        if ($_GET ['encrypt_type'] == 'aes') {
            $sEncryptMsg = ""; // xml格式的密文
            $errCode = $this->wxcpt->EncryptMsg ( $str, $this->sReqTimeStamp, $this->sReqNonce, $sEncryptMsg );
            if ($errCode == 0) {
                $str = $sEncryptMsg;
            } else {

            }
        }

        echo ($str);
    }
    /* 组装xml数据 */
    public function _data2xml($xml, $data, $item = 'item') {
        foreach ( $data as $key => $value ) {
            is_numeric ( $key ) && ($key = $item);
            if (is_array ( $value ) || is_object ( $value )) {
                $child = $xml->addChild ( $key );
                $this->_data2xml ( $child, $value, $item );
            } else {
                if (is_numeric ( $value )) {
                    $child = $xml->addChild ( $key, $value );
                } else {
                    $child = $xml->addChild ( $key );
                    $node = dom_import_simplexml ( $child );
                    $node->appendChild ( $node->ownerDocument->createCDATASection ( $value ) );
                }
            }
        }
    }
}</code>
Copy after login
Copy after login

其实我是想知道怎么去调试,代码肯定是有问题的。。。

回复内容:

我是用thinkphp开发的,这是消息推送地址的代码:

<code><?php namespace Home\Controller;
use Think\Controller;

class WeixinController extends Controller {
    var $data = array ();
    var $wxcpt, $sReqTimeStamp, $sReqNonce, $sEncryptMsg;

    public function index() {
        // 删除微信传递的token干扰
        unset ( $_REQUEST ['token'] );
        $appid = '**********';
        $token = "baofan1994";
        $encodingaeskey = "*********************************";
        $content = wp_file_get_contents ( 'php://input' );
        ! empty ( $content ) || die ( '这是微信请求的接口地址,直接在浏览器里无效' );

        if ($_GET ['encrypt_type'] == 'aes') {
            vendor ( 'WXBiz.wxBizMsgCrypt' );

            $this->sReqTimeStamp = I ( 'get.timestamp' );
            $this->sReqNonce = I ( 'get.nonce' );
            $this->sEncryptMsg = I ( 'get.msg_signature' );

            $this->wxcpt = new \WXBizMsgCrypt ( $token, $encodingaeskey, $appid);

            $sMsg = ""; // 解析之后的明文
            $errCode = $this->wxcpt->DecryptMsg ( $this->sEncryptMsg, $this->sReqTimeStamp, $this->sReqNonce, $content, $sMsg );
            if ($errCode != 0) {

                exit ();
            } else {
                // 解密成功,sMsg即为xml格式的明文
                $content = $sMsg;
            }
        }

        $data = new \SimpleXMLElement ( $content );
        // $data || die ( '参数获取失败' );
        foreach ( $data as $key => $value ) {
            $this->data [$key] = safe ( strval ( $value ) );
        }

        $this->replyText("好好学习");
    }

    /* 回复文本消息 */
    public function replyText($content) {
        $msg ['Content'] = $content;
        $this->_replyData ( $msg, 'text' );
    }

    /* 发送回复消息到微信平台 */
    private function _replyData($msg, $msgType) {
        $msg ['ToUserName'] = $this->data ['FromUserName'];
        $msg ['FromUserName'] = $this->data ['ToUserName'];
        $msg ['CreateTime'] = NOW_TIME;
        $msg ['MsgType'] = $msgType;

        if ($_REQUEST ['doNotInit']) {
            dump ( $msg );
            exit ();
        }

        $xml = new \SimpleXMLElement ( '<xml></xml>' );
        $this->_data2xml ( $xml, $msg );
        $str = $xml->asXML ();

        if ($_GET ['encrypt_type'] == 'aes') {
            $sEncryptMsg = ""; // xml格式的密文
            $errCode = $this->wxcpt->EncryptMsg ( $str, $this->sReqTimeStamp, $this->sReqNonce, $sEncryptMsg );
            if ($errCode == 0) {
                $str = $sEncryptMsg;
            } else {

            }
        }

        echo ($str);
    }
    /* 组装xml数据 */
    public function _data2xml($xml, $data, $item = 'item') {
        foreach ( $data as $key => $value ) {
            is_numeric ( $key ) && ($key = $item);
            if (is_array ( $value ) || is_object ( $value )) {
                $child = $xml->addChild ( $key );
                $this->_data2xml ( $child, $value, $item );
            } else {
                if (is_numeric ( $value )) {
                    $child = $xml->addChild ( $key, $value );
                } else {
                    $child = $xml->addChild ( $key );
                    $node = dom_import_simplexml ( $child );
                    $node->appendChild ( $node->ownerDocument->createCDATASection ( $value ) );
                }
            }
        }
    }
}</code>
Copy after login
Copy after login

其实我是想知道怎么去调试,代码肯定是有问题的。。。

可以通过写文件或者数据库的方式调试,我一般是写文件!比如代码的入口开始写文件,记录用户openid以及发送内容,然后以此类推,最极端的情况是每行代码后面都跟上调试信息,当然,这没必要哈!只需要在你感兴趣的有疑问的地方加就好了!如果前一个调试信息有了,后一个调试信息没出来,肯定是中间的代码有问题!另外记得检查下代码有没有语法错误之类的,在编辑器里打开看看

微信公众号开发文档里又个php的例子,先把那个例子跑起来。然后对照那个例子一点一点地调试你的代码,先保证你和微信对接没问题。
然后,我是自己做了个客户端模拟微信用户给后台发消息,测试自己的逻辑对不对。

<code>

    
        <meta charset="utf-8">
        <title>信信通</title>
    
    
        <div>
            <input id="mpid" type="text" size="50" value="一个代码公众号的ID">
            <input id="src" type="text" size="5" value="wx">
        </div>
        <div class="message">
            <div>关注事件</div>
            <textarea id="subscribe" cols="80" rows="3"><xml><tousername></tousername><fromusername></fromusername><createtime>1348831865</createtime><msgtype></msgtype><event></event></xml></textarea>
            <div>
                <button class="send">send</button>
            </div>
        </div>
        <div class="message">
            <div>文本消息</div>
            <textarea id="text" cols="80" rows="3"></textarea>
            <div>
                <button class="send">send</button>
            </div>
        </div>
        <div class="message">
            <div>菜单消息</div>
            <textarea id="event" cols="80" rows="4"></textarea>
            <div>
                <button class="send">send</button>
            </div>
        </div>
        <div class="message">
            <div>位置事件</div>
            <textarea id="location" cols="80" rows="5"><xml><tousername></tousername><fromusername></fromusername> <createtime>1351776365</createtime> <msgtype></msgtype> <location_x>23.134521</location_x> <location_y>113.358803</location_y> <scale>20</scale> <label></label> <msgid>9876543210123456</msgid></xml></textarea>
            <div>
                <button class="send">send</button>
            </div>
        </div>
        <div class="message">
            <div>二维码关注</div>
            <textarea id="qrscene" cols="80" rows="4">
            </textarea>
            <div>
                <button class="send">send</button>
            </div>
        </div>
        <div class="message">
            <div>场景二维码</div>
            <textarea id="qrscene2" cols="80" rows="4"></textarea>
            <div>
                <button class="send">send</button>
            </div>
        </div>
        <div class="message">
            <div>完成微信群发</div>
            <textarea id="MASSSENDJOBFINISH" cols="80" rows="6"></textarea>
            <div>
                <button class="send">send</button>
            </div>
        </div>
        <div>
            <div>执行结果</div>
            <textarea id="response" cols="100" rows="6" readonly></textarea>
        </div>
    

<script type="text/javascript" src="../static/js/jquery.min.js"></script>
<script type="text/javascript">
    var textmsg = '<xml>';
    textmsg += '<ToUserName><![CDATA[toUser]]>';
    textmsg += '<FromUserName><![CDATA[mocker]]>';
    textmsg += '<CreateTime>' + Math.round((new Date()).getTime()/1000) + '';
    textmsg += '<MsgType><![CDATA[text]]>';
    textmsg += '<Content><![CDATA[test]]>';
    textmsg += '<MsgId>9876543210123456';
    textmsg += '';
    var eventmsg = '<xml>';
    eventmsg += '<ToUserName><![CDATA[toUser]]>';
    eventmsg += '<FromUserName><![CDATA[mocker]]>';
    eventmsg += '<CreateTime>' + Math.round((new Date()).getTime()/1000) + '';
    eventmsg += '<MsgType><![CDATA[event]]>';
    eventmsg += '<Event><![CDATA[CLICK]]>';
    eventmsg += '<EventKey><![CDATA[/display/ti]]>';
    eventmsg += '';
    eventmsg += '';
    var qrscene = '<xml><ToUserName><![CDATA[toUser]]>';
    qrscene += '<FromUserName><![CDATA[mocker]]>';
    qrscene += '<CreateTime>' + Math.round((new Date()).getTime()/1000) + '';
    qrscene += '<MsgType><![CDATA[event]]>';
    qrscene += '<Event><![CDATA[subscribe]]>';
    qrscene += '<EventKey><![CDATA[qrscene_123]]>';
    qrscene += '<Ticket><![CDATA[TICKET]]>';
    qrscene += '';
    var qrscene2 = '<xml>';
    qrscene2 += '<ToUserName><![CDATA[toUser]]>';
    qrscene2 += '<FromUserName><![CDATA[mocker]]>';
    qrscene2 += '<CreateTime>' + Math.round((new Date()).getTime()/1000) + '';
    qrscene2 += '<MsgType><![CDATA[event]]>';
    qrscene2 += '<Event><![CDATA[scan]]>';
    qrscene2 += '<EventKey><![CDATA[SCENE_VALUE]]>';
    qrscene2 += '<Ticket><![CDATA[TICKET]]>';
    qrscene2 += '';
    var masssendjobfinish = '<xml>';
    masssendjobfinish += '<ToUserName><![CDATA[toUser]]>';
    masssendjobfinish += '<FromUserName><![CDATA[mocker]]>';
    masssendjobfinish += '<CreateTime>' + Math.round((new Date()).getTime()/1000) + '';
    masssendjobfinish += '<MsgType><![CDATA[event]]>';
    masssendjobfinish += '<Event><![CDATA[MASSSENDJOBFINISH]]>';
    masssendjobfinish += '<MsgID><![CDATA[1988]]>';
    masssendjobfinish += '<Status><![CDATA[sendsuccess]]>';
    masssendjobfinish += '<TotalCount>100';
    masssendjobfinish += '<FilterCount>80';
    masssendjobfinish += '<SentCount>75';
    masssendjobfinish += '<ErrorCount>5';
    masssendjobfinish += '';
    
    $(function(){
        $('#text').html(textmsg);
        $('#event').html(eventmsg);
        $('#qrscene').html(qrscene);
        $('#qrscene2').html(qrscene2);
        $('#MASSSENDJOBFINISH').html(masssendjobfinish);
        $('button.send').click(function(){
            $.ajax({
                type: 'POST',
                url: '/rest/mi/api?mpid=' + $('#mpid').val() + '&src=' + $('#src').val(),
                data: $(this).parent().prev().val(),
                success: function(rsp) {
                    $('#response').val(rsp);
                }
            });
        });
    });
</script></code>
Copy after login

我经常这么干的

1、在电脑上建立共享wifi
2、手机通过共享wifi上网,使用微信
3、在电脑上开Wireshark,然后抓你建立的共享wifi中的数据
4、在wireshark中跟踪请求和响应

还有个小事情可以处理下,就是设置你的服务器不启用gzip

最近微信官方提供了两个调试途径

登录你的微信公众号,找到开发者中心。

  • 开启调试日志就能捕捉到微信服务器和你的服务器之间的异常和错误。

  • 找到微信网页调试工具,这是一个结合了微信内置浏览器与chrome浏览器开发者工具的软件,windows和mac都有版本

附上最近基于微信高级接口开发的活动工具
链接

我提供两个方案,楼主自己看看你适不适合自己。
一是,把请求的数据写到log文件,一开始就从接受数据的位置,然后慢慢的往下推,到无法记录数据的时候就问题就在刚刚跳过的那里了,当然,语法错误真方法就无效了,语法错误的时候,你可以把微信授权的操作关掉(无授权请忽略),然后浏览器直接访问链接,看看报错位置。

第二,就是用微信官方给出的微信开发者工具进行调试,工具可以在微信呢开发者文档那里下载,位置大概是:开始开发->开发者调试工具

以上是个人微信呢开发时里面使用的调试方式,因为个人刚刚毕业不久,如果说错了,还请各位大神指正

可以试试用这个工具调试:
软件下载地址 是windows版的

先用将自己的openid打印在日志中,再复制到本地测试,发送消息可以本地测试;或者用qq浏览器有个微信调试工具 选择服务器调试 启动你本地的项目 将生成的外部链接配置在微信公众号里 就可以本地测试

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1238
24
How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles