search
HomeBackend DevelopmentPHP TutorialPHP WeChat development text automatic reply

PHP WeChat development text automatic reply

Apr 19, 2018 am 09:44 AM
phpreplyautomatic

The content of this article is about automatic text reply in PHP WeChat development. It has certain reference value. Now I share it with you. Friends in need can refer to it

Today I would like to share with you the development of the WeChat automatic reply function. This time you need to prepare your own server (which can be accessed from the Internet), and carry out it on the public account

Server authentication and enable server configuration.


When users send messages to the official account, WeChat will send these messages to the development team in xml format url corresponding to the developer's server;

The developer receives xmlAfter the message is sent, it can be parsed, and then the corresponding content is sent back to the user according to the content of the message. The reply message must also end with ## Sent in #xml format

.

<xml> <ToUserName>< ![CDATA[toUser] ]></ToUserName> <FromUserName>< ![CDATA[fromUser] ]></FromUserName> <CreateTime>12345678</CreateTime> <MsgType>< ![CDATA[text] ]></MsgType> <Content>< ![CDATA[你好] ]></Content> </xml>

Parameter Is it required Description
ToUserName is the receiver account (received OpenID)
FromUserName is the developer WeChat ID
CreateTime is the message creation time (integer)
MsgType is text
Content is the message content of (line break: line breaks can be made in content, WeChat The client supports newline display)

One thing to note here is that the waiting time for WeChat to send a request to the developer server is 5 seconds. If the developer If the server 5 cannot reply within seconds,

WeChat will resend the request

(up to three times). After three times, Still cannot reply within 5 seconds or the content of the reply cannot be parsed by WeChat, and it will display "This official account cannot be

" Serve". If

cannot guarantee a reply within 5 seconds, you can reply with an empty string and WeChat will not do any processing on this message.

Because the types of messages sent by WeChat to the developer server are relatively diverse, including ordinary messages, follow events, unfollow events, button click events, etc. Therefore, when designing the automatic reply function, the flexibility, scalability and maintainability of the program must be fully considered.

Here I used the "chain of responsibility design pattern" to define a processing interface and let each message handler implement this interface; when receiving a request, send the request

The request is passed to the first handler class. Each request class contains a reference to the next handler class; if the request can be processed in this class, it will return to processing directly

The result, otherwise flows to the next handler class until the request is processed. The characteristic of this mode is that it decomposes the steps of processing requests and can make complex judgments

条件进行分解,同时每一个处理程序都只有一个单一的职责,对其进行修改不会影响到其他处理程序类。另外,将每一个请求类

xml文件的格式配置好,应用程序启动的时候,使用反射+IOC注入的方式实例化每一个处理程序类。

  首先创建一个页面,replyText.html


 我们创建两个数据表,

rule表 :用来存储回复数据,id自增长 , mp_id是当前正在使用的公众号,keyword是用户输入的关键字,type在此为text,reply_id与reply_text表建立连接,status为当前状态(是否正在使用)。



reply_text表 : reply_id作为主键,content为回复内容。

(在此注意一点,在页面输入对应值后,要把数据统一添加到两个数据表中,add()方法成功返回主键值,可利用这点进行两表关联添加)



public function replyText(){
        if(IS_GET){
            $this->display(&#39;replytext&#39;);
        }else{
            $mp = $this->mp;
            $mp_id = $mp[&#39;id&#39;];
            $data = I(&#39;post.&#39;);

            $textret = M(&#39;reply_text&#39;)->add($data);

            if($textret){
                $data[&#39;reply_id&#39;] = $textret;
                $data[&#39;mp_id&#39;] = $mp_id;
                $data[&#39;type&#39;] = &#39;text&#39;;
                if ($mp[&#39;is_use&#39;] == 1){
                    $data[&#39;status&#39;] = 1;
                }else{
                    $data[&#39;status&#39;] = 0;
                }
                $ret = M(&#39;rule&#39;)->add($data);
                if ($ret) {
                    $this->ajaxReturn(array(&#39;msg&#39;=>&#39;添加成功!&#39;));
                }else{
                    $this->ajaxReturn(array(&#39;msg&#39;=>$ret));
                }
            }
        }
    }


之前介绍过,我用的laneWeChat包,可以直接调用里边的方法,在wechatrequest.lib.php里的text方法中加入以下代码进行文本回复:

//获取哪个公众号发过来的请求
        $mp_id = $_GET[&#39;id&#39;];

        $content = $request[&#39;content&#39;];
        $where[&#39;mp_id&#39;] = $mp_id;
        $where[&#39;keyword&#39;] = $content;
        $data = M(&#39;rule&#39;)->where($where)->find();
        if ($data) {
            //发送消息中有这个关键字
            $reply_id = $data[&#39;reply_id&#39;];
            $type = $data[&#39;type&#39;];

            if ($type == "text") {
                $reply = M(&#39;reply_text&#39;)->find($reply_id);
                $reply_text = $reply[&#39;content&#39;];
                return ResponsePassive::text($request[&#39;fromusername&#39;], $request[&#39;tousername&#39;], $reply_text);
            }
            
        }else{
            return &#39;success&#39;;
        }

代码要一一写的话就有些多了,在此,只给小伙伴们分享以上代码,如果还有其他问题,欢迎留言提问哦~

请大家多多关注,我会时刻更新的!

相关推荐:

PHP微信开发之翻译功能

PHP WeChat development to obtain city weather

         

The above is the detailed content of PHP WeChat development text automatic reply. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 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: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 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.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software