开发环境:
框架:thinkphp 5.1
前端:layui 2.5.8
控制器代码:MessageController.php
1.入口文件
public function read()
{
if (isset($_GET['echostr'])) {
$this->valid();
}else{
$this->responseMsg();
}
}
2.微信签名认证
/**
执行服务器认证
**/
public function valid()
{
$echoStr = $_GET["echostr"];
//valid signature , option
if($this->checkSignature() && $echoStr){
echo $echoStr;exit;
}
}
3.认证方法
/**
* 微信服务器认证
* @return bool
*/
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 );
//检验signature
if( $tmpStr == $signature){
return true;
}else{
return false;
}
}
4.认证成功的效果