共计 1564 个字符,预计需要花费 4 分钟才能阅读完成。
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;
}
正文完