防止access_token失效 法二(存表)

新建表token,过了有效期的话更新一次数据即可

  `id` int(10) NOT NULL AUTO_INCREMENT,

  `token` varchar(100) DEFAULT NULL,

  `addtime` varchar(255) DEFAULT NULL,

public function getToken(Request $request)
{
    $data = DB::table('token')->first();
    if ($data && (time() - $data->addtime) > 7200) {
        $c = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_GET, \DingTalkConstant::$FORMAT_JSON);
        $req = new \OapiGettokenRequest();
        $corpid = $this->corpid;
        $corpSecret = $this->corpSecret;
        $req->setCorpid($corpid);
        $req->setCorpsecret($corpSecret);
        $resp = $c->execute($req, '', "https://oapi.dingtalk.com/gettoken");
        $token = $resp->access_token;
        $res = DB::table('token')->where('id',$data->id)->update(['token' => $token, 'addtime' => time()]);
    }elseif(!$data){
        $c = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_GET, \DingTalkConstant::$FORMAT_JSON);
        $req = new \OapiGettokenRequest();
        $corpid =  $this->corpid ;
        $corpSecret = $this->corpSecret;
        $req->setCorpid($corpid);
        $req->setCorpsecret($corpSecret);
        $resp = $c->execute($req, '', "https://oapi.dingtalk.com/gettoken");
        $token = $resp->access_token;
        $res = DB::table('token')->insert(['token' => $token, 'addtime' => time()]);
    }else{
        $token = $data->token;
    }
    return $token;
}

猜你喜欢

转载自blog.csdn.net/stand_forever/article/details/84662604
今日推荐