Correction status:Uncorrected
Teacher's comments:
<?php namespace app\index\controller; use think\Controller; use think\facade\Cache; class Weixin extends Controller{ //构造器 public function __construct(){ parent::__construct(); $this->model = model('Weixin'); //model模型中的Weixin类 } // 微信推送事件 public function index(){ // 校验数据来源 $valid = $this->model->valid(); //用$valid变量来接收model目录中的valid()方法返回的数据 if(!$valid){ exit('signature error'); //不通过,返回错误信息 } exit(input('get.echostr')); //通过,返回随机字符串 } }
<?php namespace app\index\model; use think\Model; use think\facade\Cache; use think\Db; class Weixin extends Model{ // 签名校验 public function valid(){ $signature = input('get.signature'); $timestamp = input('get.timestamp'); $nonce = input('get.nonce'); $token = config('app.weixintoken'); //从app.php配置文件中拿到数据 $tmpArr = array($timestamp,$nonce,$token); //用$tmpArr变量来接收数组中的数据 sort($tmpArr, SORT_STRING); $str = implode($tmpArr); //将$tmpArr数组中的数据拼接来一个字符串 if(sha1($str) != $signature){ //判断时将$str进行sha1加密,$str不等于$signature时执行false,否则返回true return false; //不通过返回false } return true; //通过返回true } //获取access_token public function access_token($iscache = true){ $key = 'access_token'; if(!$iscache){ Cache::rm($key); } $data = Cache::get($key); //将拿到的数据存储到$data变量中 if($data && $iscache){ //如果 $data 并且 $iscache有值 将返回当前值 return $data; } $appid = config('app.appid'); //在app.php配置文件中设置值 $appsecret = config('app.appsecret'); //在app.php配置文件中设置值 //URL中必须配置公众号里的appid 和 appsecret $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret; $res = http_get($url); $res = json_decode($res,true); if(!isset($res['access_token'])){ //检测$res中没有值则返回false,如果有值拿到下面语句中缓存 return false; } Cache::set($key,$res['access_token'],($res['expires_in']-500)); //缓存accseet_token, return $res['access_token']; } }
//微信token 'weixintoken' => 'p医院医院*', //开发者ID:APPID 'appid' => 'w医院医院医院医院医院c', //开发者密码 'appsecret' => 'e8医院医院*6医院医院医院医院*c医院5医院医院医院97医院*',
function http_Post($url,$data){ $curl = curl_init(); curl_setopt($curl,CURLOPT_URL,trim($url)); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); //启用时会发送一个常规的POST请求,为1或者为true if(!empty($data)){ $data = is_array($data)?json_encode($data):$data; curl_setopt($curl,CURLOPT_POST,1); curl_setopt($curl,CURLOPT_POSTFIELDS,$data);//需要要传送的内容 } curl_setopt($curl,CURLOPT_RETURNTRANSFER,1); $return_str = curl_exec($curl); curl_close($curl); return $return_str; } function http_Get($url){ $curl = curl_init(); curl_setopt($curl,CURLOPT_URL,trim($url)); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl,CURLOPT_HEADER,0); curl_setopt($curl,CURLOPT_CUSTOMREQUEST,'GET');//需要要传送的内容 curl_setopt($curl,CURLOPT_RETURNTRANSFER,1); $return_str = curl_exec($curl); curl_close($curl); return $return_str; }