批改状态:合格
老师批语:
微信开发服务器配置和access_token
ngrok.exe http 80
启动内网穿透,外网可以访问内网服务器。access_token 访问次数有限,需要用到cache.服务器配置时,首次接入成功
返回exit($echostr)
application\index\controller\Weixin.php
<?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');
}
public function index()
{
$valid=$this->model->valid();
if(!$valid){
exit('sigature error');
}
exit(input('get.echostr'));
}
public function get_access_token($iscache=true){
$cache_key='access_token';
if(!$iscache){
Cache::rm($cache_key);
}
$data=Cache::get($cache_key);
if($data && $iscache){
return $data;
}
$appid=config('app.APPID');
$appsecret=config('app.APPSECRET');
$url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
$res=http_Get($url);
// dump($res);
$res=json_decode($res,true);
// dump($res);
if(!isset($res[$cache_key])){
return false;
}
Cache::set($cache_key,$res['access_token'],($res['expires_in']-600));
return $res[$cache_key];
}
}点击 "运行实例" 按钮查看在线实例
application\index\model\Weixin.php
<?php
namespace app\index\model;
use think\Model;
use think\Db;
use think\facace\Cache;
class Weixin extends model
{
public function valid()
{
$signature=input('get.signature');
// $signature='c5052967c11f8d7e59c3b4011407b94c697b1ceb';
// var_dump($signature);
$timestamp=input('get.timestamp');
// $timestamp='1527896867';
$nonce=input('get.nonce');
// $nonce='3010175004';
$echostr=input('get.echostr');
// $echostr='9044276551450221539';
$token=config('app.token');
file_put_contents('d://data.txt','signature='.$signature.' timestmp='.$timestamp.' nonce='.$nonce.' echostr='.$echostr);
$tmpArr=array($timestamp,$nonce,$token);
sort($tmpArr,SORT_STRING);
// dump($tmpArr);
$tmpStr=implode($tmpArr);
// echo $tmpStr;
// $tmpStr=sha1($tmpStr);
//
if(sha1($tmpStr) != $signature){
// exit('error');
return false;
}
// 首次接入成功需要输出$echostr
// exit($echostr);
return true;
}
}点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号