首先需要配置好 公众号中 ->服务器配置,配置的服务器URL就是接收回调的地址,附赠配置链接
《服务器配置》验证token教程
//接收到用户发送的消息
public function index() //与配置TOKEN方法一致
{
$timestamp =$_GET['timestamp'];
$nonce = $_GET['nonce'];
$token = TOKEN; //验证时配置的TOKEN
$signature = $_GET['signature'];
$array = array($token,$timestamp,$nonce);
sort($array, SORT_STRING);
$tmpstr = sha1(implode($array));
if($tmpstr == $signature){
if (!isset($get['echostr'])) {
$data = file_get_contents("php://input"); //接收XML数据
//可以使用file_put_contents 函数写入本地文件内获取xml接收的数据
$arr = $this->xmltoarr($data); //转数组
$this->text($arr['Content'],['$UserInfo['FromUserName']']); //数据处理 调用发送查看发送内容及对应返回数
return $XML;
} else{ //并没有走这里 欢迎大佬指教
ob_clean();
file_put_contents(EXTEND_PATH.'about.txt',222,FILE_APPEND);
echo $_GET['echostr'];
exit;
}
}
}
/*
* 将xml 转 数组
*/
public function xmltoarr($xml){//xml字符串转数组
$arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $arr;
}
/*
* 文本消息
* $cont string 用户发送的文本内容
* $senduser 发送者
* */
private function text($cont,$senduser){
$cont = '你好'; //比如这里$cont 内容时“你好”
$XML = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$sendMsg = sprintf($XML,$senduser,'自己的原始ID即可',time(),'要返回的内容');
echo $sendMsg;
}
返回XML就可以返回给用户了。随时欢迎大佬赐教