小程序如何获取access_token

小程序如何获取access_token

首先:获取access_token需要小程序的appid和AppSecret,这个可以通过“小程序公众平台——开发——开发设置”查到

如下,在需要access_token的地方,请求get_access_token()接口,该接口查询数据库是否有未过期的access_token,有的话就返回,没有的话请求 getAccessToken()这个接口获取新的access_token,并返回。

public static function getAccessToken($routineAppId = '',$routineAppSecret = ''){
    $routineAppId = SystemConfig::getValue('routine_appId');
    $routineAppSecret = SystemConfig::getValue('routine_appsecret');
    $url  ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$routineAppId."&secret=".$routineAppSecret;
    return json_decode(self::curlGet($url),true);
}


public static function get_access_token(){
    $accessToken = db('routine_access_token')->where('id',1)->find();
    if($accessToken['stop_time'] > time()) return $accessToken['access_token'];
    else{
        $accessToken = self::getAccessToken();
        if(isset($accessToken['access_token'])){
            $data['access_token'] = $accessToken['access_token'];
            $data['stop_time'] = bcadd($accessToken['expires_in'],time(),0);
            db('routine_access_token')->where('id',1)->update($data);
        }
        return $accessToken['access_token'];
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43687896/article/details/86238048