1.查询出access_Token的值
public String getAccessToken() {
String access_token= redisTemplate.opsForValue().get("hbPaymentToken")+"";
log.info("---redis get hbPaymentToken--"+access_token);
if(StringUtils.isBlank(access_token)||access_token.equals("null")||access_token.equals("")){
//记住,先去企业微信后台管理端开启api同步权限
//corpid---企业微信corpid
//corpsecret ---企业微信通讯录secret
String access_token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=corpid&corpsecret=corpsecret";
// String access_token_url = wechatOpenProperties.getAccessTokenUrl()+"?corpid=ww17f8d10783494584&corpsecret=i5t-rh8bXeNCgihcYPrG9ZPpWkivzPJ69sv570osk6I";
JSONObject jsonObject = JSONObject.parseObject(HttpClientUtil.doGet(access_token_url));
access_token = jsonObject.getString("access_token");
redisTemplate.opsForValue().set("hbPaymentToken",access_token,7000, TimeUnit.SECONDS);
}
return access_token;
}
//同步通讯录
public String getUser() {
log.info("begin-----执行---更新员工信息-----getUser");
List<HashMap<String, Object>> userList = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> user = null;
// 1查询出access_Token的值
String access_token= getAccessToken() ;
// 获取部门列表信息(不填则是查询出所有的部门列表)
List<String> depts = getDepartmentList(access_token, "");
// 根据部门信息去获取成员的详细信息(查询到的数据)
List<WxUserInfo> users = getDepartmentUserDetails(depts, access_token, "0");
for (WxUserInfo d : users) {
user = new HashMap<String, Object>();
user.put("userId", d.getUserId());
user.put("name", d.getName());
user.put("passWord", "123456");
user.put("mobile", d.getMobile());
user.put("power", 1);
user.put("alias",d.getAlias());
user.put("department", d.getDepartment());
user.put("email", d.getEmail());
user.put("position", d.getPosition());
user.put("gender", d.getGender());
user.put("status", d.getStatus());
user.put("store",d.getStore());
user.put("storeId",d.getStoreId());
userList.add(user);
}
// 将其保存到数据库中
wxUserInfoMapper.insertWxUserInfo(userList);
}
/**
* 获取部门列表
* @param accessToken
* @param departmentId
* @return
*/
public List<String> getDepartmentList(String accessToken, String departmentId) {
List<String> departments = new ArrayList<String>();
// 1.获取请求的url
String getDepartmentList_url = wechatOpenProperties.getDepartmentList_url()+"?access_token="+accessToken+"&id="+departmentId;
// 2.调用接口,发送请求,获取成员
JSONObject jsonObject = JSONObject.parseObject(HttpClientUtil.doGet(getDepartmentList_url));
System.out.println("jsonObject:" + jsonObject.toString());
// 3.错误消息处理
if (null != jsonObject) {
if (0 != jsonObject.getIntValue("errcode")) {
log.error("获取部门列表 errcode:{} errmsg:{}",
jsonObject.getIntValue("errcode"),
jsonObject.get("errmsg"));
} else {// 查询成功
List<Map<String, Object>> mapListJson = (List)jsonObject.getJSONArray("department");
QueryWrapper q = new QueryWrapper();
departmentMapper.delete(q);
departmentMapper.insertDepartment(mapListJson);
if (null != mapListJson) {
Department department = new Department();
for (int i = 0; i < mapListJson.size(); i++) {
Map<String, Object> dept = mapListJson.get(i);
if (null != dept.get("id")) {
departments.add(dept.get("id").toString());
}
}
}
}
}
return departments;
}
/**
* 获取部门成员详情
* @param depts
* @param accessToken
* @param fetchChild//是否遍历子部门的成员,一般不要遍历,除非你就只获取父级部门或者子部门为空,不然会导致数据重复
* @return
*/
public List<WxUserInfo> getDepartmentUserDetails(List<String> depts, String accessToken, String fetchChild) {
List<WxUserInfo> users = new ArrayList<>();
for (String deptId : depts) {
// 1.获取请求的url
String getDepartmentUserDetails_url = wechatOpenProperties.getDepartmentUserDetails_url()+"?access_token="+accessToken+
"&department_id="+deptId+"&fetch_child="+fetchChild;
// 2.调用接口,发送请求,获取部门成员
JSONObject jsonObject =JSONObject.parseObject(HttpClientUtil.doGet(getDepartmentUserDetails_url));
System.out.println("Contact_service----jsonObject:" + jsonObject.toString());
// 3.错误消息处理
if (null != jsonObject) {
if (0 != jsonObject.getIntValue("errcode")) {
log.error("获取部门成员详情失败 errcode:{} errmsg:{}",
jsonObject.getIntValue("errcode"),
jsonObject.get("errmsg"));
}else{//查询成功的话
// JSONArray array=jsonObject.getJSONArray("userlist");
List<Map<String, Object>> mapListJson = (List)jsonObject.getJSONArray("userlist");
if(null!=mapListJson){
for(int i=0;i<mapListJson.size();i++){
Map<String, Object> de=mapListJson.get(i);
//具体字段看自己业务需求
WxUserInfo user=new WxUserInfo();
user.setUserId(String.valueOf(de.get("userid")));
user.setDepartment(String.valueOf(de.get("department")));
user.setName(String.valueOf(de.get("name")));
user.setPosition(String.valueOf(de.get("position")));
user.setMobile(String.valueOf(de.get("mobile")));
user.setGender(String.valueOf(de.get("gender")));
user.setEmail(String.valueOf(de.get("email")));
user.setStatus(String.valueOf(de.get("status")));
user.setAlias(String.valueOf(de.get("alias")));
//自定义字段取值,没有忽略
JSONObject jsonObject1 = (JSONObject)de.get("extattr");
List<JSONObject> attrsListJson = (List)(jsonObject1.getJSONArray("attrs"));
for(int j =0;j<attrsListJson.size();j++ ){
JSONObject jsonObject2 =attrsListJson.get(j);
if(("门店").equals(jsonObject2.getString("name"))){
user.setStore(jsonObject2.getString("value"));
}
if(("门店ID").equals(jsonObject2.getString("name"))){
user.setStoreId(jsonObject2.getString("value"));
}
}
users.add(user);
}
}
}
}
}
return users;
}
public class HttpClientUtil {
public static String doGet(String url) {
CloseableHttpClient httpCilent2 = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000) //设置连接超时时间
.setConnectionRequestTimeout(5000) // 设置请求超时时间
.setSocketTimeout(5000)
.setRedirectsEnabled(true)//默认允许自动重定向
.build();
HttpGet httpGet2 = new HttpGet(url);
httpGet2.setConfig(requestConfig);
httpGet2.setHeader("Content-Type","application/json;charset=UTF-8");;
String srtResult = "";
try {
HttpResponse httpResponse = httpCilent2.execute(httpGet2);
if(httpResponse.getStatusLine().getStatusCode() == 200){
srtResult = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");//获得返回的结果
}else if(httpResponse.getStatusLine().getStatusCode() == 400){
//..........
}else if(httpResponse.getStatusLine().getStatusCode() == 500){
//.............
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
httpCilent2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return srtResult;
}
public static byte[] doGet_entity(String url) {
CloseableHttpClient httpCilent2 = HttpClients.createDefault();
HttpGet httpGet2 = new HttpGet(url);
String srtResult = "";
try {
HttpResponse httpResponse = httpCilent2.execute(httpGet2);
if(httpResponse.getStatusLine().getStatusCode() == 200){
return EntityUtils.toByteArray(httpResponse.getEntity());
}else if(httpResponse.getStatusLine().getStatusCode() == 400){
//..........
}else if(httpResponse.getStatusLine().getStatusCode() == 500){
//.............
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
httpCilent2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static String doPost(String url, Map<String, Object> paramsMap){
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().
setConnectTimeout(180 * 1000).setConnectionRequestTimeout(180 * 1000)
.setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
httpPost.setConfig(requestConfig);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (String key : paramsMap.keySet()) {
nvps.add(new BasicNameValuePair(key, String.valueOf(paramsMap.get(key))));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
String strResult = "";
if (response.getStatusLine().getStatusCode() == 200) {
strResult = EntityUtils.toString(response.getEntity(), "UTF-8");
return strResult;
} else {
return "Error Response: " + response.getStatusLine().toString();
}
} catch (Exception e) {
e.printStackTrace();
return "post failure :caused by-->" + e.getMessage().toString();
}finally {
if(null != httpClient){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static String doPostForJson(String url, String jsonParams){
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().
setConnectTimeout(180 * 1000).setConnectionRequestTimeout(180 * 1000)
.setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
httpPost.setConfig(requestConfig);
httpPost.setHeader("Content-Type","application/json;charset=UTF-8"); //
try {
httpPost.setEntity(new StringEntity(jsonParams,ContentType.create("application/json", "utf-8")));
System.out.println("request parameters" + EntityUtils.toString(httpPost.getEntity()));
HttpResponse response = httpClient.execute(httpPost);
String strResult = "";
if (response.getStatusLine().getStatusCode() == 200) {
strResult = EntityUtils.toString(response.getEntity(), "UTF-8");
return strResult;
} else {
return "Error Response: " + response.getStatusLine().toString();
}
} catch (Exception e) {
e.printStackTrace();
return "post failure :caused by-->" + e.getMessage().toString();
}finally {
if(null != httpClient){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
企业微信通讯录同步-java
最新推荐文章于 2023-08-23 10:00:28 发布