68-微信公众号开发涉及到的token和access_token

1. 基础支持的access_token

官方文档:

https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html

实现:

CommonConstant.java:

String WXGZH_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
String WXGZH_SNS_OAUTH2_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
public JsonResponse getToken(String appid,String secret){
    String token = (String)wxgzhCommonCache.getBaseToken(appid);
    if(StringUtils.isEmpty(token)){
        String url = String.format(CommonConstant.WXGZH_TOKEN_URL,appid,secret);
        String result = okHttpUtil.get(url);
        if(result==null){
            logger.info("result is null");
            return result(-1,"获取token失败",null);
        }
        JSONObject resultObj = JSON.parseObject(result);
        if(resultObj==null){
            logger.info("result is null");
            return result(-1,"获取token失败",null);
        }
        String errcode = resultObj.getString("errcode");
        if(StringUtils.isNotEmpty(errcode)){
            logger.info("获取token,返回错误,result={}",result);
            return result(-2,"获取token,返回错误",resultObj);
        }
        token = resultObj.getString("access_token");
        int expires_in = resultObj.getInteger("expires_in");
        expires_in = expires_in-300;//预留5分钟
        wxgzhCommonCache.putBaseToken(appid,token,expires_in);
    }
    return result(0,"",token);
}

2. 网页授权需要获取的用户access_token

官方文档:
https://developers.weixin.qq....
代码实现:

public JsonResponse getAccessToken(String code){
    String url = String.format(CommonConstant.WXGZH_SNS_OAUTH2_ACCESS_TOKEN_URL,appId,appSecret,code);
    String result = okHttpUtil.get(url);
    JsonResponse js = checkResult(result,"获取access_token");
    if(js.getCode().intValue()!=0){
        return js;
    }
    return js;
}

你可能感兴趣的:(java)