主题:生成signature
获取access_token并缓存
效果图:
生成signature并验证通过后
获取的access_token
access_token缓存文件
模型(model/Wechat.php)实例
namespace app\index\model;
use think\Model;
use think\facade\Cache;
class Wechat extends Model
{
// 微信推送事件
public function check() {
// 将微信服务器的请求数据分别存为变量
$signature = input('get.signature');
$timestamp = input('get.timestamp');
$nonce = input('get.nonce');
$echostr = input('get.echostr');
// 在框架配置文件中设置微信的token,并读取
$token = config('app.wechattoken');
// 将获取的数据存到一个数组中
$tmpArr = array($timestamp, $nonce, $token);
// 排序数据数组
sort($tmpArr, SORT_STRING);
// 判断加密后的字符串与微信请求中的signature是否一致
if(sha1(implode($tmpArr)) != $signature) {
exit('signature error');
}
exit($echostr);
}
// 获取access_token
public function access_token($iscache = true) {
// 如果某个参数使用较多,放到一个变量中,方便更改
$cache_key = 'access_token';
// 默认不用删除缓存
if(!$iscache) {
Cache::rm($cache_key);
}
// 获取缓存中的access_token值
$access_token = Cache::get($cache_key);
if($access_token && $iscache) {
return $access_token;
}
// 将appid和appsecret(微信公众号中获取)的值保存至config/app.php中,并调取
$appid = config('app.appid');
$appsecret = config('app.appsecret');
// 拼接url
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
// 获取access_token的值,返回一个json数据
$res = http_Get($url);
// 将json数据转换成数组
$res = json_decode($res, true);
// 如果没有拿到access_token的值,返回false
if(!isset($res['access_token'])) {
return false;
}
// 拿到数据后进行缓存,使用facade中的Cache
Cache::set($cache_key, $res[$cache_key], $res['expires_in']-300);
return $res[$cache_key];
}
}
运行实例 »
点击 "运行实例" 按钮查看在线实例
控制器(controller/Wechat.php)实例
namespace app\index\controller;
use think\Controller;
class Wechat extends Controller
{
// 微信推送事件
public function __construct() {
parent::__construct();
$this->model = model('Wechat');
}
public function index() {
$valid = $this->model->check();
// 判断模型中返回值
if(!$valid) {
exit('signature error');
}
exit(input('get.echostr'));
}
// 获取access_token
public function get_access_token() {
$access_token = $this->model->access_token();
return $access_token;
}
}
运行实例 »
点击 "运行实例" 按钮查看在线实例