官方文档地址:获取access_token - 接口文档 - 企业微信开发者中心
根据文档要求获取corpid、agentid和corpsecret
建立wechat.properties文件
#企业id
corpid = corpid
#企业通讯录密钥
corpsecret = corpsecret
#获取access_token
access_token_url = https://qyapi.weixin.qq.com/cgi-bin/gettoken
#企业微信access_token缓存redis
access_token_reids_key = wechat_access_token
#应用ID
a_agentid = a_agentid
#应用密钥
a_corpsecret = a_corpsecret
#应用access_token缓存redis
a_access_token_reids_key = a_access_token_reids_key
建立WechatUtil工具类
public class WechatUtil {
/**
* redis缓存有效时间,秒
*/
public static final int access_token_time = 7100;
/**
* 企业id
*/
public static final String corpid;
/**
* 企业通讯录密钥
*/
public static final String corpsecret;
/**
* 获取access_token
*/
public static final String access_token_url;
/**
* 企业微信access_token缓存redis
*/
public static final String access_token_reids_key;
// 应用
public static final String a_agentid;
public static final String a_corpsecret;
public static final String a_access_token_reids_key;
static {
try {
InputStream is = WechatUtil.class.getResourceAsStream("/wechat.properties");
Properties pro = new Properties();
pro.load(is);
corpid = pro.getProperty("corpid");
corpsecret = pro.getProperty("corpsecret");
access_token_url = pro.getProperty("access_token_url");
access_token_reids_key = pro.getProperty("access_token_reids_key");
a_agentid= pro.getProperty("a_agentid");
a_corpsecret= pro.getProperty("a_corpsecret");
a_access_token_reids_key= pro.getProperty("a_access_token_reids_key");
} catch (IOException e) {
throw new RuntimeException("加载wechat.properties配置文件失败." + e.getMessage(), e);
}
}
/**
* Description: 获取token(新增应用,应修订此方法)
* @param appName 传null或者空,默认查询通讯录token
* @return
* @throws Exception
*/
public static String getToken(String appName) throws Exception {
try {
String tokenReidsKey = access_token_reids_key;
String key = corpid;
String secret = corpsecret;
if (StringUtils.isEmpty(appName)) {
// 用默认
} else if (appName.equals("a")) {
// 应用
tokenReidsKey = a_access_token_reids_key;
secret = a_corpsecret;
}
String token = RedisUtil.getValue(tokenReidsKey);
if (!StringUtils.isEmpty(token)) {
return token;
}
// 获取token
String result = HttpsUtil.getHttp(access_token_url, "corpid=" + key + "&corpsecret=" + secret);
Map<String, Object> resultMap = orderSimpleResult(result);
token = resultMap.get("access_token") + "";
if (StringUtils.isEmpty(token)) {
throw new Exception (-1, result);
}
RedisUtil.setValue(tokenReidsKey, token, access_token_time);
return token;
} catch (Exception e) {
throw new Exception (e);
}
}
}
自此即完成获取企微access_token的步骤