功能比较简单,当用户在公众号下留言,将留言的关键词带到数据库查询并返回查询结果。
反正是以比较简单的代码做的,代码运行环境随便可以运行PHP就行。
反正是以比较简单的代码做的,代码运行环境随便可以运行PHP就行。
<!DOCTYPE html>
<html>
<body>
<head>
<meta charset="utf-8">
</head>
<?php
require_once "defs.php";
function index()
{
$timestamp = $_GET['timestamp'];
$nonce = $_GET['nonce'];
$token = 'hongming'; //公众号里面配置的token
$signature = $_GET['signature'];
$echostr = $_GET['echostr']; //每一次都要验证, 只有第一次验证才会有 echostr
$array = array( $timestamp, $nonce, $token);
sort( $array );
//2.将排序后的三个参数拼接之后用sha1加密
$tempstr = implode('', $array);
$tempstr = sha1( $tempstr );
//3.将加密后的字符串与signature进行对比,判断该请求是否来自微信
if( $tempstr == $signature && $echostr){ //启动服务器配置 会进入到这里
echo $_GET['echostr'];
exit();
}else{
reponseMsg(); //这里是 启用成功后, 接受事件用的
}
}
function reponseMsg(){
$postStr = file_get_contents("php://input");
//根据事件,进行自己的逻辑代码吧 请开始你的表演
if (!empty($postStr)){
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$msgtype = $postObj->MsgType;
$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") //文本判断
{
$msgType = "text";
$contentStr = sousuo($keyword);
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}
if($msgtype=='event'){ // 关注判断
$msgType = "text";
$contentStr = "感谢您的关注!";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}
else // 其他类型消息判断
{
$msgType = "text";
$contentStr = "回复关键词可以查询影视资源哦!";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}
}
}
index();
?>
</body
</html>
其他的可以去看看官方的开发文档。
![PHP对接微信公众号实现简单自动回复[PHP教程]-度崩网-几度崩溃 PHP对接微信公众号实现简单自动回复[PHP教程]-度崩网-几度崩溃](https://img.vlogforum.com/imgs/2019/12/1f547735d650d8.png)




