美文网首页
微信开发之获取access_token

微信开发之获取access_token

作者: 喊我小王吧 | 来源:发表于2019-04-03 17:11 被阅读0次

    获取access_token

    access_token 作为微信接口全局访问的唯一调用凭据 ,公众号调用各个接口时候都需要使用access_token 。

    access_token的存储至少要保留512个字符空间。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。

    注意:

    access_token 尽量获取一次,然后各个地方调用即可,切勿多次请求接口获取,防止造成冲突。

    文档原文如下:

    在这里插入图片描述

    获取方式

    接口调用请求说明

    https请求方式: GET
    https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
    

    参数说明

    参数 是否必须 说明
    grant_type 获取access_token填写client_credential
    appid 第三方用户唯一凭证
    secret 第三方用户唯一凭证密钥,即appsecret

    返回说明

    正常情况下,微信会返回下述JSON数据包给公众号:

    {"access_token":"ACCESS_TOKEN","expires_in":7200}
    

    参数说明

    参数 说明
    access_token 获取到的凭证
    expires_in 凭证有效时间,单位:秒

    错误时微信会返回错误码等信息,JSON数据包示例如下(该示例为AppID无效错误):

    {"errcode":40013,"errmsg":"invalid appid"}
    

    返回码说明

    返回码 说明
    -1 系统繁忙,此时请开发者稍候再试
    0 请求成功
    40001 AppSecret错误或者AppSecret不属于这个公众号,请开发者确认AppSecret的正确性
    40002 请确保grant_type字段值为client_credential
    40164 调用接口的IP地址不在白名单中,请在接口IP白名单中进行设置。(小程序及小游戏调用不要求IP地址在白名单内。)

    代码实现

    实体类

    public class AccessToken {
    
        private String expires_in; //成功有效时间
        private String access_token;  // 普通Token
        private String errcode; //失败ID
        private String errmsg; //失败消息
        private long expiresIn; //过期时间 , 默认2小时
    
        public long getExpiresIn() {
            return expiresIn;
        }
    
        public void setExpiresIn(long expiresIn) {
            this.expiresIn = expiresIn;
        }
    
        public String getExpires_in() {
            return expires_in;
        }
    
        public void setExpires_in(String expires_in) {
            this.expires_in = expires_in;
        }
    
        public String getAccess_token() {
            return access_token;
        }
    
        public void setAccess_token(String access_token) {
            this.access_token = access_token;
        }
    
        public String getErrcode() {
            return errcode;
        }
    
        public void setErrcode(String errcode) {
            this.errcode = errcode;
        }
    
        public String getErrmsg() {
            return errmsg;
        }
    
        public void setErrmsg(String errmsg) {
            this.errmsg = errmsg;
        }
    
        /**
         *
         * @param expires_in 从微信服务器获取到的过期时间
         * @param access_token 从微信服务器获取到的过期时间access-token
         */
        public AccessToken(String expires_in, String access_token) {
            this.access_token = access_token;
            //当前系统时间+上过期时间
            expiresIn = System.currentTimeMillis() + Integer.parseInt(expires_in) * 1000;
        }
    
        //判断token是否过期
        public boolean isExpired() {
            return System.currentTimeMillis() > expiresIn;
        }
    }
    

    HttpUtil工具

        /**
         * @param url 发送get请求方法
         * @return
         */
        public static String sendHttpByGet(String url){
            try {
                URL urlGet = new URL(url);
                URLConnection urlConnection = urlGet.openConnection();
                InputStream is = urlConnection.getInputStream();
                String inputStreamData = getInputStreamData(is);
                return inputStreamData;
            } catch (Exception e) {
                logger.info("发送get请求方法异常! " + e);
                e.printStackTrace();
            }
            return null;
        }
    
    

    请求获取

    public class AccessTokenTool {
    
        static Logger logger = LoggerFactory.getLogger(AccessTokenTool.class);
        //自己的appid 和 appsecret
        private static final String APPID = "wxb24662xxxx";
        private static final String APPSECRET = "1864f91ecdd3xxxxxxxxxxx";
        //用于存储token
        private static AccessToken at;
    
        /**
         * @return
         * @throws Exception
         */
        private static com.example.bwjf.demo.pojo.AccessToken getAccessToken(){
            String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
            accessTokenUrl = accessTokenUrl.replace("APPID",APPID).replace("APPSECRET",APPSECRET);
            logger.info(" 微信全局token的url " + accessTokenUrl );
    
            String message = HttpUtil.sendHttpByGet(accessTokenUrl);
    
                /**
                 *  获取access_token
                 *  成功返回的json : {"access_token":"ACCESS_TOKEN","expires_in":7200}
                 *  失败放的json  : {"errcode":40013,"errmsg":"invalid appid"}
                 *
                 */
                JSONObject jsonObject = JSONObject.parseObject(message);
                String accessToken = jsonObject.getString("access_token");
                String expires_in = jsonObject.getString("expires_in");
                String errcode = jsonObject.getString("errcode");
    
                logger.info("accessToken = " + accessToken);
                logger.info("expires_in = "+ expires_in);
    
                if(!jsonObject.containsKey(errcode)){
                    //创建token,并且存起来
                    at = new AccessToken(expires_in,accessToken);
                    return at;
                }
    
            return null;
        }
    
    
        /**
         * 对外提供获取 AccessTokenTool
         * @return
         */
        public static String getToken(){
            if(at==null || at.isExpired() == false){
                //logger.info("过期");
                try {
                    getAccessToken();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return at.getAccess_token();
        }
        
    }
    
    

    注:

    认证后公众号,可能出现的问题调用Api无权限或者为空 (开发者测试账号除外 )

    请在微信公众平台,安全中心设置ip白名单即可!

    相关文章

      网友评论

          本文标题:微信开发之获取access_token

          本文链接:https://www.haomeiwen.com/subject/fzwzbqtx.html