Home Backend Development PHP Tutorial PHP WeChat development text automatic reply

PHP WeChat development text automatic reply

Apr 19, 2018 am 09:44 AM
php reply automatic

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

.

1

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

Copy after login
ParameterIs it requiredDescription
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()方法成功返回主键值,可利用这点进行两表关联添加)



1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

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));

                }

            }

        }

    }

Copy after login


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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

//获取哪个公众号发过来的请求

        $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;;

        }

Copy after login

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

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

相关推荐:

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 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

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,

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

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

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.

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.

See all articles