WeChat official account interface development - reply message
As a WeChat official account, interaction with users is very important. For example, according to the message sent by users and the user information (text, pictures, videos, pictures, etc.) that are passively answered by push events, I have tested several interfaces to realize these functions.
1. Verify the developer and get the user message
<?php /** * wechat php test */ //define your token define("TOKEN", "wechat"); $wechatObj = new wechatCallbackapiTest(); $wechatObj->valid(); $wechatObj->responseMsg(); class wechatCallbackapiTest { public function valid() { $echoStr = $_GET["echostr"]; //valid signature , option if($this->checkSignature()){ echo $echoStr; exit; } } public function responseMsg() { //get post data, May be due to the different environments $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //extract post data if (!empty($postStr)){ $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $time = time(); $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> </xml>"; if(!empty( $keyword )) { $msgType = "text"; $contentStr = "Welcome to wechat world!"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; }else{ echo "Input something..."; } }else { echo ""; 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 ){ // header('content-type:text'); return true; }else{ return false; } } } ?>
Here are two ways to explain:
-
checkSignature(): verify whether the request information comes from wechat server.
The developer fills in the url information in the interface configuration. After the developer submits the information, the wechat server will send a get request to the url. The get request carries four parameters (signature, timestamp, nonce, echost). The checkSignature method encrypts and verifies the request parameters. The process is as follows:
1) Sort the token, timestamp and nonce in dictionary order
2) Concatenate three parameter strings into a string for sha1 encryption
3) The encrypted string obtained by the developer can be compared with the signature, which proves that the request originates from the wechat server and returns the content of the echostr parameter as it is. It becomes a success for the developer, or the access fails. -
responseMsg(): receive the message or event push sent by the user, parse the contained data, and customize the reply message.
The Content (XML string) of post request is obtained by global variable $GLOBALS ["http ﹣ raw ﹣ post ﹣ data"], and then it is converted into object by simplexml ﹣ load ﹣ string. The attribute values such as fromUsername, toUsername, Content, event can be obtained, and the reply can be made by judging the event type and filtering the message Content. The data of the reply message is encapsulated in the XML string of the reply message using sprintf and returned to the wechat server, which parses and displays it to the client.
Note: the validation method only needs to be called when validating the developer. Once the validation is successful, it is no longer needed. Please comment it out!!!
2. First attention reply
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $ev=$postObj->Event;//Get event type $keyword = trim($postObj->Content); $time = time(); $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[%s]]></Content> </xml>"; if($ev=='subscribe'){ // Users pay attention for the first time and automatically reply to the welcome message $msgType="text"; $contentStr="Welcome your attention, only for better service"; $resultStr=sprintf($textTpl,$fromUsername,$toUsername,$time,$contentStr); echo $resultStr; }
3. Event push when clicking menu to pull message
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $ev=$postObj->Event;//Get event type $keyword = trim($postObj->Content); $time = time(); if($ev=='CLICK'){ $evKey=$postObj->EventKey; if($evKey=='send_text'){//The event KEY value corresponds to the KEY value in the user-defined menu interface $msgType="text"; $contentStr="You click. Click Type of menu"; $resultStr=sprintf($textTpl,$fromUsername,$toUsername,$time,$contentStr); echo $resultStr; } }
3. Keyword reply
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $time = time(); $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[%s]]></Content> </xml>"; if (!empty($keyword)) { $pattern = '/.*(random)|(random).*/'; preg_match($pattern,$keyword,$match); if($match){ $msgType = "text"; $contentStr = mt_rand(0,100); $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $contentStr); echo $resultStr; }
I'm using regular matching to see if there's a keyword, and $match is populated with search results. $matches[0] will contain the text to which the full pattern matches, $matches[1] will contain the text to which the first capture subgroup matches, and so on. Empty array if there is no match.
There are other types of message replies, the general process is similar, but there is a little difference in the XML template of the message, which will not be demonstrated here. Hope beginners can get something from it!!!