当前位置: 代码迷 >> 综合 >> 微信服务号 权限 access_token 失效问题
  详细解决方案

微信服务号 权限 access_token 失效问题

热度:2   发布时间:2023-12-17 04:20:37.0
    /*** 获取access_token  并放入cache缓存*/function  set_access_token($cacheobj){static $n=0;$access_token =null;Cache::rm('access_token');if (empty($access_token) ||$access_token ==false) {$access_token = $this->get_access_token();// 切换到file操作$access_token = json_decode($access_token,true);if(is_array($access_token)){$access_token['add_time'] = time();}$access_token = json_encode($access_token);// 提前20秒获取一次$cacheobj->set('access_token', $access_token, 7000);}$data =json_decode($access_token,true);if($n>=10){return '';}if(!isset($data['access_token']) || $data['access_token']==''){$n++;return $this->set_access_token($cacheobj);}//存入数据库中Db::name('config')->where(['id'=>53,'name'=>'access_token'])->update(['value'=>$data['access_token']]);return $data['access_token'];}// 获取tokenfunction get_access_token(){static $n=0;$configdata = Config::get('weixin_api');$url= $configdata['get_access_url'];$appid = $configdata['appid'];$secret = $configdata['secret'];$url = str_replace('APPID', $appid, $url);$url = str_replace('SECRET', $secret, $url);$client = new Client(['timeout' => 8.0,]);$request = new GuRequest('get', $url);$response = $client->send($request, ['timeout' => 30, 'verify' => false, 'headers' => ['Accept' => 'application/json',]]);$body = $response->getBody();$remainingBytes = $body->getContents();$n++;if($n>=4){return '';}//判断是否正确if(stripos($remainingBytes,'access_token') !== false){return $remainingBytes;}else{return  $this->get_access_token();}}
<?phpnamespace think;
use \Workerman\Worker;
use \Workerman\Lib\Timer;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
define('APP_PATH', __DIR__ . '/application/');
require __DIR__ . '/thinkphp/base.php';
$task = new Worker();
// 开启多少个进程运行定时任务,注意业务是否在多进程有并发问题
$task->count = 1;
$task->onWorkerStart = function($task)
{// 每7200秒执行一次$time_interval = 6000;Timer::add($time_interval, function(){$urltoken = 'http://zyapi.xiaoluge.top/generateaccess_token';$client = new Client();$response = $client->get($urltoken);$response->getStatusCode(); // 200});
};// 运行worker
Worker::runAll();