原文:http://vtuce.cn/p/13.html 本文示例代码在thinkphp下运行,纯php请自行更改。 开发者首次接入,直接返回echostr即可完成校验: return input('get.echostr');
成为开发者之后,微信每次转发用户消息到我的服务器,就不会再带上echostr了。 但是,仍旧需要验证消息来自微信服务器。为什么?因为有坏人可能仿造微信来调用你的接口,所以,该接口首先验证,然后做业务逻辑。严重注意:排序使用sort($arr,SORT_STRING);网上的教程这里是坑。 public function main()
{
//获得参数 signature nonce token timestamp echostr
$nonce = input('post.nonce');
$timestamp = input('post.timestamp');
$token = '你在公众号填写的token';
$signature = input('post.signature');
//将$nonce, $timestamp, $token这3个字符串按字典序排序后拼接成字符串(放入数组只是为了排序)
$arr = [$nonce, $timestamp, $token];
sort($arr,SORT_STRING);
$str = implode($arr);
//sha1加密后与signature比对,相同则来自微信,否则是坏人发来的
$sha1str = sha1($str);
if ($sha1str != $signature) {
$ip = Request::instance()->ip();
logWrite($ip);
return '';
}
// TODO 业务逻辑
}
其中,logWrite() 是我自己写的函数,把坏人的IP记录在日志中.
|