Home  >  Article  >  Backend Development  >  How to use PHP to develop the automatic reply rule management function of public accounts

How to use PHP to develop the automatic reply rule management function of public accounts

WBOY
WBOYOriginal
2023-09-19 11:01:59918browse

How to use PHP to develop the automatic reply rule management function of public accounts

How to use PHP to develop the automatic reply rule management function of public accounts

With the popularity of WeChat public accounts, many companies and individuals have begun to understand and use WeChat public accounts . The WeChat official account provides a rich functional interface, among which the automatic reply rule management function is a very important function. This article will introduce how to use PHP to develop the automatic reply rule management function of public accounts and provide specific code examples.

First of all, we need to understand some basic concepts of the automatic reply rule management function of WeChat public accounts. On the backend management page of the WeChat official account, we can set custom menus and keyword automatic reply rules.

Custom menu means that when a user clicks on the menu after following the official account, the official account will respond accordingly according to the settings of the menu. Custom menus can be divided into first-level menus and second-level menus. Each menu item can be set to trigger an event after being clicked, which can be a reply message, a jump link, or an interface call, etc.

Keyword automatic reply rules mean that when a user sends a message containing a certain keyword, the official account will reply according to the set reply rules. Keywords can be text, pictures, links, etc. Reply rules can be replying to fixed messages, replying to random messages, or calling interfaces, etc.

Next, we will start to introduce in detail how to use PHP to develop the automatic reply rule management function of public accounts.

First, we need to prepare a PHP development environment, including a web server (such as Apache or Nginx), PHP parser and MySQL database. In this environment, we can use PHP to develop web applications, handle requests from the WeChat server, and respond accordingly.

Next, we need to obtain the AppID and AppSecret of the WeChat official account. We can apply for a developer account on the WeChat public platform and create a public account. In the settings of the official account, we can find the AppID and AppSecret.

Next, we need to configure the server address and Token in the developer tools of the WeChat public platform. The server address is the address of the web server we built ourselves, and the Token is a string used to verify the identity between the WeChat server and our own server. After the configuration is completed, click Confirm and save the Token, which we will need when writing code.

Next, we can start writing PHP code. First, create a file named wechat.php and write the following code in the file:

<?php

define("TOKEN", "YOUR_TOKEN");

$wechatObj = new wechatCallbackAPI();
$wechatObj->valid();

class wechatCallbackAPI
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];

        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
                
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
}

In the above code, we first define a constant TOKEN to store our data in the WeChat developer tools Configured Token. Next, we created a class named wechatCallbackAPI and defined two methods, valid() and checkSignature() in the class.

valid() method is used to verify the identity between the WeChat server and our own server, and return the verification result. In the method, we first obtain the echostr parameter passed by the WeChat server and save it in the $echoStr variable. Then, call the checkSignature() method for authentication. If the verification passes, $echoStr is output to the client and the execution of the program is terminated.

The checkSignature() method is used to verify whether the parameters passed by the WeChat server are valid. First, we obtain the signature, timestamp and nonce parameters passed by the WeChat server and save them into the corresponding variables. Then, sort the TOKEN, timestamp and nonce in lexicographic order and use the SHA1 algorithm for encryption. Finally, the encrypted string is compared with the signature passed by the WeChat server. If they are equal, the verification passes, otherwise the verification fails.

Next, we can write the code for automatic replies. For the sake of simplicity, here we only implement the keyword automatic reply function. In the wechat.php file, add the following code:

<?php

// 省略上面的代码

class wechatCallbackAPI
{
    // 省略上面的代码
    
    public function responseMsg()
    {
        // 获取微信服务器POST过来的XML数据
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $content = trim($postObj->Content);
            $time = time();

            if ($content == "你好"){
                $textTpl = "<xml>
";
                $textTpl .= "<ToUserName><![CDATA[%s]]></ToUserName>
";
                $textTpl .= "<FromUserName><![CDATA[%s]]></FromUserName>
";
                $textTpl .= "<CreateTime>%s</CreateTime>
";
                $textTpl .= "<MsgType><![CDATA[text]]></MsgType>
";
                $textTpl .= "<Content><![CDATA[%s]]></Content>
";
                $textTpl .= "</xml>";

                $msgType = "text";
                $replyContent = "你好!欢迎关注我的公众号!";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $replyContent);
                echo $resultStr;
            } else {
                echo "success";
            }
        }else {
            echo "success";
            exit;
        }
    }
}

$wechatObj = new wechatCallbackAPI();
$wechatObj->valid();
$wechatObj->responseMsg();

In the above code, we added a method named responseMsg() in the wechatCallbackAPI class (used to process user messages). In the method, we first obtain the XML data POST from the WeChat server and save it to the $postStr variable. Then, the XML data is converted into a SimpleXMLElement object through the simplexml_load_string() function and saved into a variable with the corresponding node value.

Here, we use the keyword automatic reply function as an example. If the content of the message sent by the user is "Hello", the official account will reply "Hello! Welcome to follow my official account!", otherwise no reply will be made.

Finally, we created a $wechatObj object at the end of the wechat.php file, and called the valid() and responseMsg() methods in sequence to complete the authentication between the WeChat server and our own server, and Handle user messages.

So far, we have completed the code writing of using PHP to develop the automatic reply rule management function of public accounts. Next, we can deploy the wechat.php file to our web server and configure the server address and Token in the WeChat public platform to test whether our code is valid.

To sum up, this article introduces how to use PHP to develop the automatic reply rule management function of public accounts and provides specific code examples. I hope to be helpful.

The above is the detailed content of How to use PHP to develop the automatic reply rule management function of public accounts. 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