java的微信公众号开发二(获取access_token)

一、开发文档如下

文档原文地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183

摘取部分:

access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。

目前Access_token的有效期通过返回的expire_in来传达,目前是7200秒之内的值。

Access_token的有效时间可能会在未来有调整,所以中控服务器不仅需要内部定时主动刷新,还需要提供被动刷新access_token的接口,这样便于业务服务器在API调用获知access_token已超时的情况下,可以触发access_token的刷新流程。

请求方式:

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

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

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

错误时微信会返回错误码等信息,JSON数据包示例如下:

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

二、获取access_token的方法

//注册时获取access_token
public static Map<String,String> getAccessToken(String APPID,String APPSECRET) {
    //1.拼接api要求的获取access_token 的httpsurl链接
    String urlString = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ APPID + "&secret=" + APPSECRET;
    URL reqURL=null;
    HttpsURLConnection httpsConn=null;
    InputStreamReader isr=null;
    try {
        //2.创建一个url对象
        reqURL = new URL(urlString);
        try {
            //3.获取一个链接
            httpsConn= (HttpsURLConnection) reqURL.openConnection();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 4.取得该连接的输入流,用来读取响应内容
        try {
            isr = new InputStreamReader(httpsConn.getInputStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 4.1读取服务器的响应内容并显示
        // 4.2 InputStreamReader的int read(char []cbuf);//将读取到的字符存到数组中。返回读取的字符数。
        char[] chars = new char[1024];
        String reslut = "";
        int len;
        try {
            //拼接字符串
            while ((len = isr.read(chars)) != -1) {
            reslut += new String(chars, 0, len);
            }
            isr.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //5.将获取的json中的值。
        //5.1
        Map<String,String> map=new HashMap<String,String>();
        JSONObject jsonObject = JSONObject.parseObject(reslut);
        // 获取access_token,expires_in的值
        String access_token = jsonObject.getString("access_token"); 
        String expires_in = jsonObject.getString("expires_in");
        if (access_token!= null) {
            map.put("access_token",access_token);
            map.put("expires_in",expires_in);
            return map;
        } else {
            return null;
        }
    } catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    return null;
}

三、存取access_token

可以使用数据库来存取access_token,所以存的时候我们要把当前的时间存进去,以便于判断时间差

晒一下数据库结构:appid、secret、access_token、expires_in、creattime几列,(expires_in,creattime两个使用的是long类型

四、验证是否失效的方法

//判断token时效性的方法
	public static boolean checktime(WechatUserinfo weichatUserinfo) {
		//有效时间,化成毫秒数
		long expires_in =(weichatUserinfo.getExpires_in())*1000;
		//创建时存入的毫秒数
		long creattime = weichatUserinfo.getCreattime();
		//现在的时间
		long nowTime = System.currentTimeMillis();
		//差值
		long remianTime = nowTime - creattime;
		if(remianTime<expires_in) {
			//没有失效,直接取用即可
			return true;
		}else {
			/*//失效了,重新获取并储存
			weichatUserinfo=getAccessToken(weichatUserinfo);*/
			return false;
		}
	}

本文未对错误返回码进行解析与分析,大家可按照自己的想法进行添补,具体错误返回码,详见开发文档。

本文写的方法若未查到有可能会返回空值,在使用此方法时,可对返回的结果进行一次判断后,做对应处理。






猜你喜欢

转载自blog.csdn.net/weixin_40877388/article/details/80306315