U8国际·(集团)有限公司官网

导航切换

联系电话:
021-66889888     1399998888

U8国际·(集团)有限公司官网

U8国际·(集团)有限公司官网
当前位置: 主页 > 教学科研 > 教研动态

微信公众号开发:php实现文本消息自动回复的代码和方法

作者: 小编 来源: 本站   日期:2026-01-19 01:54

曾有许多初学者,对于微信公众号开发感到特别头疼,特别是在要实现自动回复功能的时候。尽管在网上存在着好多旧教程,然而技术进行更新速度是很快的,直接应用老代码的话,或许是没办法运行的。

开发环境的基本配置

在开展微信公众号开发以前,要准备妥当服务器以及域名。你所拥有的服务器得支持PHP这种语言,而且还已然配置好了SSL证书,以此保证能够借助HTTPS协议去进行访问。这可是微信平台强制规定的安全举措。

你要于微信公众平台的后台那儿,寻得开发设置页面,精准填好服务器配置信息。这其中涵盖服务器地址URL,还有令牌Token以及消息加解密的密钥。填好往后提交验证,微信服务器会朝着你填的地址发送一个GET请求来予以校验。

接收用户消息的原理

当用户朝着你的公众号递送消息的时候,微信这个服务器会把这通消息整理成XML样式,借由一个POST请求传送到你所设定的服务器地址之处;你的代码得能够接纳并处置这个POST请求。

核心在于,对这个 XML 数据包展开解析,此为处理的关键所在。你得凭借它从中把关键字段给提取出来,像是发送者的 OpenID 呀,消息创建的时间呢,消息的类型还有消息确实切内容。这可是实现任何回复功能的根基所在。

文本消息的解析与提取

valid();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)){ /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,  the best way is to check the validity of xml by yourself */ libxml_disable_entity_loader(true);  $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $time = time(); $textTpl = "      %s      0  ";  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() { // you must define TOKEN by yourself if (!defined("TOKEN")) { throw new Exception('TOKEN is not defined!'); }  $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"];  $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); // use SORT_STRING rule sort($tmpArr, SORT_STRING); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr );  if( $tmpStr == $signature ){ return true; }else{ return false; } }}?>

有各种不同多样的类型属于消息范畴,其中文本消息处于最为常见的那一类情形。所接收到的XML数据当中,用来标识消息类型的是MsgType这个字段实例,与之相对应具有着text这种值标识的是文本消息例证。你首先务必着手对这个字段展开一些判断操作行为。

确认属于文本消息之后,再于XML里提取用户所发送的具体文字内容,此内容一般存储在Content字段当中。把内容提取出来并存储到变量,这是后续开展关键词匹配以及智能回复的前提条件。

实现关键词自动回复逻辑

在得到用户所发送的文本以后,便可着手去设计回复逻辑。有一种简单且有效的办法是进行关键词匹配。你能够事先去定义一个数组,把关键词以及对应的回复内容关联起来。

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)){ /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,  the best way is to check the validity of xml by yourself */ libxml_disable_entity_loader(true);  $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $time = time(); $textTpl = "      %s      0  ";  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() { // you must define TOKEN by yourself if (!defined("TOKEN")) { throw new Exception('TOKEN is not defined!'); }  $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"];  $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); // use SORT_STRING rule sort($tmpArr, SORT_STRING); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr );  if( $tmpStr == $signature ){ return true; }else{ return false; } }}?>

过后,对这个关键词数组展开遍历,借助函数判定用户输入之中是否涵盖某个关键词。一旦达成匹配,随即调用回复消息的函数,把预设的回复内容回返给用户。此过程全然由代码自行达成。

处理用户关注事件

存在一种特别的“事件消息”,并非文本消息。新用户关注公众号之际,微信服务器会发出一个事件推送。此消息的MsgType字段值为event

你得进一步去判别事件的类型,留意事件所对应的那个Event字段的值是subscribe。在捕获到了这个事件之后,你能够马上朝着该用户发送出那么一条欢迎语,这可是提升用户体验的一个挺好的机会。

组装与返回回复消息

需要按照微信所要求的XML格式,把消息组装好然后返回,不管是回复文本,还是响应关注事件。回复消息的XML当中,要涵盖接收方与发送方的OpenID,还有消息创建时间,以及消息类型和内容。

于组装完毕之后,运用echo或者print之类的函数把完整的XML字符串予以输出,当微信服务器接收到此响应之时,便会将其转变为一条公众号消息,于用户的微信聊天界面里进行显示。

当你着手对公众号增添自动回复功能之际,碰到的最为棘手的难题,究竟是配置服务器环境呢,还是领会微信的通讯协议以及数据格式呢?欢迎于评论区去分享你遭遇问题的经历,要是觉着本文具备助益,同样请点赞予以支持。

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)){ /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,  the best way is to check the validity of xml by yourself */ libxml_disable_entity_loader(true);  $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $time = time(); $msgType = $postObj->MsgType;//消息类型 $event = $postObj->Event;//时间类型,subscribe(订阅)、unsubscribe(取消订阅) $textTpl = "      %s      0  ";    switch($msgType){  case "event":  if($event=="subscribe"){  $contentStr = "Hi,欢迎关注海仙日用百货!"."\n"."回复数字'1',了解店铺地址."."\n"."回复数字'2',了解商品种类.";  }   break;  case "text":  switch($keyword){  case "1":  $contentStr = "店铺地址:"."\n"."杭州市江干艮山西路233号新东升市场地下室第一排.";   break;  case "2":  $contentStr = "商品种类:"."\n"."杯子、碗、棉签、水桶、垃圾桶、洗碗巾(刷)、拖把、扫把、"   ."衣架、粘钩、牙签、垃圾袋、保鲜袋(膜)、剪刀、水果刀、饭盒等.";  break;  default:  $contentStr = "对不起,你的内容我会稍后回复";  }  break; } $msgType = "text"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; }else { echo ""; exit; } }  private function checkSignature() { // you must define TOKEN by yourself if (!defined("TOKEN")) { throw new Exception('TOKEN is not defined!'); }  $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"];  $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); // use SORT_STRING rule sort($tmpArr, SORT_STRING); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr );  if( $tmpStr == $signature ){ return true; }else{ return false; } }}?>