From d29984aaeb02e053cac15fc4d1e3cfd53b879ff9 Mon Sep 17 00:00:00 2001 From: ELF <360197197@qq.com> Date: Mon, 30 Sep 2019 22:51:56 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Home/Controller/HomeController.class.php | 52 ++++++++++++------- 1 file changed, 34 insertions(+), 18 deletions(-) diff --git a/Application/Home/Controller/HomeController.class.php b/Application/Home/Controller/HomeController.class.php index 8e4344851..8b3c61d2a 100644 --- a/Application/Home/Controller/HomeController.class.php +++ b/Application/Home/Controller/HomeController.class.php @@ -55,26 +55,42 @@ class HomeController extends Controller $secret = 'd3219c70a45c5e1954be4608b288d38b'; $tokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret; - $result = file_get_contents($tokenUrl); - $result = json_decode($result, true); - if (!$result || isset($result['errcode'])) { - $this->ajaxReturn([ - 'status' => false, - 'msg' => '获取失败', - ]); + $content = file_get_contents(RUNTIME_PATH . 'Data/wechat_ticket'); + $ticketData = null; + if ($content) { + $ticketData = json_decode($content, true); } - $accessToken = $result['access_token']; - - $ticketUrl = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . $accessToken . '&type=jsapi'; - $result = file_get_contents($ticketUrl); - $result = json_decode($result, true); - if (!$result || $result['errcode'] != 0) { - $this->ajaxReturn([ - 'status' => false, - 'msg' => '获取失败', - ]); + + $isExpired = false; + if ($ticketData) { + $isExpired = time() > $ticketData['expired_at'] ? true : false; + } + + $ticket = ''; + if (!$ticketData || $isExpired) { + $ticket = $ticketData['ticket']; + $result = file_get_contents($tokenUrl); + $result = json_decode($result, true); + if (!$result || isset($result['errcode'])) { + $this->ajaxReturn([ + 'status' => false, + 'msg' => '获取失败', + ]); + } + $accessToken = $result['access_token']; + + $ticketUrl = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . $accessToken . '&type=jsapi'; + $result = file_get_contents($ticketUrl); + $result = json_decode($result, true); + if (!$result || $result['errcode'] != 0) { + $this->ajaxReturn([ + 'status' => false, + 'msg' => '获取失败', + ]); + } + $ticket = $result['ticket']; + file_put_contents(RUNTIME_PATH . 'Data/wechat_ticket', json_encode(['ticket' => $ticket, 'expired_at' => time() + 3600])); } - $ticket = $result['ticket']; $randStr = 'aaabbbxeclsx'; $time = time();