当前位置: 首页 > 编程文章 >

微信公众号PHP文本消息自动回复实现指南

微信公众号PHP文本消息自动回复实现指南

作者:周景时间:2025-11-19 15:52:19浏览:559

本文介绍基于PHP的微信公众号文本消息自动回复功能实现。核心逻辑在于修改wx_sample.php文件,调用responseMsg方法替代valid验证。针对用户发送的文本及关注事件(MsgType为event且Event为subscribe),需自定义提取$msgType和$event变量以区分处理,从而实现关键词匹配与欢迎语回复。

本文目录展开

微信公众号PHP文本消息自动回复实现指南

本实例分享了利用PHP语言实现微信公众号文本消息自动回复的具体代码方案,供开发者参考使用,详细内容如下所示。

首先获取PHP示例源码,可通过以下链接下载:地址一为http://xiazai.jb51.net/202608/yuanma/phpwx(jb51.net).rar;地址二为官方文档页面https://mp.weixin.qq.com/wiki/home/index.html,路径为开始开发下的接入指南中提供PHP示例代码下载。

接下来查看wx_sample.php文件的初始代码结构。


<?php
/**
 * wechat php test
 */

//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->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 = "<xml>
  <ToUserName><![CDATA[%s]]></ToUserName>
  <FromUserName><![CDATA[%s]]></FromUserName>
  <CreateTime>%s</CreateTime>
  <MsgType><![CDATA[%s]]></MsgType>
  <Content><![CDATA[%s]]></Content>
  <FuncFlag>0</FuncFlag>
  </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()
 {
 // 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;
 }
 }
}

?>

在wx_sample.php文件中,需注释掉原有的$wechatObj->valid();语句,并在其下方添加一行代码$wechatObj->responseMsg();以启用消息响应功能。


<?php
/**
 * wechat php test
 */

//define your token
define("TOKEN", "weixin");
$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)){
 /* 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 = "<xml>
  <ToUserName><![CDATA[%s]]></ToUserName>
  <FromUserName><![CDATA[%s]]></FromUserName>
  <CreateTime>%s</CreateTime>
  <MsgType><![CDATA[%s]]></MsgType>
  <Content><![CDATA[%s]]></Content>
  <FuncFlag>0</FuncFlag>
  </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()
 {
 // 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;
 }
 }
}

?>

4.关键词自动回复和关注回复 $keyword保存着用户微信端发来的文本信息。 官方开发者文档:https://mp.weixin.qq.com/wiki/home/index.html(消息管理-》接收消息-接收事件推送-》1.关注/取消关注事件)

关注事件与普通文本消息存在两点差异:一是MsgType字段值为event,二是额外包含Event字段值为subscribe。由于官方提供的初始wx_sample.php未提取该参数,因此需要手动处理。在程序中需新增两个变量$msgType和$event来分别捕获这些信息。


<?php
/**
 * wechat php test
 */

//define your token
define("TOKEN", "weixin");
$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)){
 /* 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 = "<xml>
  <ToUserName><![CDATA[%s]]></ToUserName>
  <FromUserName><![CDATA[%s]]></FromUserName>
  <CreateTime>%s</CreateTime>
  <MsgType><![CDATA[%s]]></MsgType>
  <Content><![CDATA[%s]]></Content>
  <FuncFlag>0</FuncFlag>
  </xml>"; 
  
 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;
 }
 }
}


?>

上述即为本文的全部内容,希望对各位的学习有所帮助,同时也欢迎大家继续支持本站。

上一篇
PHP版支付宝服务窗API接口开发示例

本文提供基于PHP语言的支付宝服务窗API接口开发实例。针对官方Demo阅读性不足的问题,整理了一套简化代码供参考。使用前需申请相应权限,核心功能包含参数拼接及RSA签名验证机制,旨在辅助开发者快速接入服务窗业务。

下一篇
PHP实现的MongoDB操作类

本文介绍了一个使用 PHP 语言编写的 MongoDB 数据库操作类。该代码文件旨在简化 PHP 与 MongoDB 之间的交互过程,提供标准化的接口以执行常见的数据库操作任务。

相关文章

更多
PHP微信公众号开发核心代码与数据库配置详解

本文分享了PHP微信公众号开发中的关键实现细节,涵盖从数据库二级菜单建立到核心消息响应逻辑的代码解析。重点展示了如何通过coon.php进行数据库连接,以及在index.php中利用responseMsg方法接收并处理用户发送的XML数据,包括提取用户ID、消息类型等关键字段,最终返回相应的文本回复,为开发者提供可直接参考的工程实践方案。

2026.03.29 753
PHP微信开发之文本自动回复

本文介绍如何在微信公众平台开启开发者模式并配置URL、Token及EncodingAESKey,随后提供基于PHP的微信接口对接脚本。通过验证签名机制确保通信安全,并演示如何根据用户输入关键词返回特定文本或在新用户关注时发送欢迎语。

2025.01.23 593
PHP通过网页授权获取微信OpenID方法总结

在微信支付或自动登录场景中,获取用户OpenID是核心步骤。本文重点介绍通过认证服务号进行网页授权获取OpenID的方法。通过封装PHP类并调用getOpenid接口,结合Cookie缓存机制,可有效避免重复授权请求,提升用户体验。

2026.01.19 292
9个PHP实用功能代码片段推荐

本文整理了9段PHP实用代码片段,涵盖从邮件阅读追踪到网页内容解析的多种场景。包括通过生成1像素图片记录IP和时间的邮件已读检测、利用get_meta_tags提取关键字、使用DOMDocument抓取页面所有链接、自动将文本中的URL转换为超链接、创建节省HTTP请求的数据URL、远程下载保存图片、清理Word HTML标签、检测客户端默认语言以及获取Facebook粉丝数等功能,为日常开发提供便捷工具。

2026.02.12 974
PHP代码混淆与加密扩展的区别及适用场景

PHP 代码混淆与加密的核心区别在于: 混淆( Obfuscation ) 通过重命名变量、控制流扁平化等手段增加逆向阅读难度,但 不改变程序逻辑 ,运行时由 Zend 引擎正常解析; 加密( Encryption ) 通常指将源码编译为字节码并附加解密层,需依赖特定扩展或自定义 Loader 才能运行。若目标是防止源

2025.08.02 942
不安装服务器环境怎么快速测试PHP代码

使用 php -l 检查语法,用 php -S localhost:8000 启动内置服务器运行代码。

2026.07.16 908

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。