Java企业微信开发_03_通讯录同步

一、本节要点

1.获取通讯录密钥

获取方式:

登录企业微信—>管理工具—>通讯录同步助手—>开启“API接口同步”  ; 开启后,即可看到通讯录密钥,也可设置通讯录API的权限:读取或者编辑通讯录。

获取通讯录密钥的目的:

通过企业ID(CorpId)和 通讯录密钥可以获取通讯录相关接口的使用凭证(AccessToken)。有了AccessToken,就可以使用通讯录相关接口了。

凭证的获取方式有两种(此处暂时存疑,以待勘误):

通讯录AccessToken:CorpId+通讯录密钥

其他AccessToken:CorpId+应用密钥

Java企业微信开发_03_通讯录同步

2.json序列化

2.1序列化和反序列化的概念

  把对象转换为字节序列的过程称为对象的序列化

  把字节序列恢复为对象的过程称为对象的反序列化

2.2对象的序列化的目的

  1) 把对象的字节序列永久地保存到硬盘上,通常存放在一个文件中;
  2) 在网络上传送对象的字节序列。

2.3java序列化方式

(1)java原生序列化

(2)json序列化

而json序列化可使用 ① json-lib

②fastJson

③gson

2.4json序列化与反序列化

这里我们采用gson来实现java对象的序列化,需要引入  gson-2.7.jar 包。

(1)简单的Jason

{
"userid": "zhangsan",
"name": "张三",
"english_name": "jackzhang" }

使用gson.toJson(user)即可将user对象顺序转成json字符串,如下

    Gson gson = new Gson();
String jsonU1 =gson.toJson(user);

(2)带数组的json

将department设为list<Integer>类型即可

{
"userid": "zhangsan",
"name": "张三",
"english_name": "jackzhang"
"department": [1, 2], }

(3)包含子对象的json

以下代码为文本消息的json字符串,将text属性类型设为Text,Text类中包含content属性。然后使用 gson.toJson(user)

{
"msgtype" : "text",
"agentid" : 1,
"text" : {
"content" : "你的快递已到,请携带工卡前往邮件中心领取。\n出发前可查看<a href=\"http://work.weixin.qq.com\">邮件中心视频实况</a>,聪明避开排队。"
}, }

关于Json序列化,读者在 Java企业微信开发_05_消息推送之发送消息 这一节会有更深刻的理解,这一周将会继续总结。

3.企业微信开发思路

企业微信的开发大体可分为以下几步:

(1)封装实体类

参考官方文档给出的请求包、回包(即响应包),封装对应的java实体类。

(2)java对象的序列化

将java对象序列化为json格式的字符串

(3)获取AccessToken,拼接请求接口url

(4)调用接口发送http请求

封装好http请求方法:httpRequest(请求url, 请求方法POST/GET, 请求包);

 /**
* 1.发起https请求并获取结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect(); // 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
} // 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
log.error("Weixin server connection timed out.");
} catch (Exception e) {
log.error("https request error:{}", e);
}
return jsonObject;
}

二、代码实现

相关jar包:

Java企业微信开发_03_通讯录同步

2.1 工具类之微信参数封装类——WeiXinParamesUtil.java

此类封装了微信的相关参数,如企业id、应用凭证、通讯录凭证等。封装起来更易维护,实现一处修改多处改变。

 package com.ray.util;
/**
* 微信参数
* @author shirayner
*
*/
public class WeiXinParamesUtil {
//1.微信参数
//token
public final static String token = "ray";
// encodingAESKey
public final static String encodingAESKey = "z2W9lyOAR1XjY8mopEmiSqib0TlBZzCFiCLp6IdS2Iv";
//企业ID
public final static String corpId = "ww92f5da92bb24696e"; //应用的凭证密钥
public final static String agentSecret = "I73733veH3uCs6H_ijPvIq0skjTaOePsFF4MyCEi3Ag";
//通讯录秘钥
public final static String contactsSecret = "1m_9XP62YrXjSiYtL5ThbexiLVWBThukiK5sH7wm1TM"; //企业应用的id,整型。可在应用的设置页面查看
public final static int agentId = 1000002; }

2.2 工具类之微信辅助类——WeiXinUtil.java

此类封装了http请求、https请求、获取accessToken的方法

 package com.ray.util;

 import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ray.pojo.AccessToken;
import net.sf.json.JSONException;
import net.sf.json.JSONObject; public class WeiXinUtil { private static Logger log = LoggerFactory.getLogger(WeiXinUtil.class);
//微信的请求url
//获取access_token的接口地址(GET) 限200(次/天)
public final static String access_token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpId}&corpsecret={corpsecret}"; /**
* 1.发起https请求并获取结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect(); // 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
} // 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
log.error("Weixin server connection timed out.");
} catch (Exception e) {
log.error("https request error:{}", e);
}
return jsonObject;
} /**
* 2.发起http请求获取返回结果
*
* @param requestUrl 请求地址
* @return
*/
public static String httpRequest(String requestUrl) {
StringBuffer buffer = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); httpUrlConn.setDoOutput(false);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false); httpUrlConn.setRequestMethod("GET");
httpUrlConn.connect(); // 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect(); } catch (Exception e) {
}
return buffer.toString();
} /**
* 3.获取access_token
*
* @param appid 凭证
* @param appsecret 密钥
* @return
*/
public static AccessToken getAccessToken(String appid, String appsecret) {
AccessToken accessToken = null; String requestUrl = access_token_url.replace("{corpId}", appid).replace("{corpsecret}", appsecret);
JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
// 如果请求成功
if (null != jsonObject) {
try {
accessToken = new AccessToken();
accessToken.setToken(jsonObject.getString("access_token"));
accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
} catch (JSONException e) {
accessToken = null;
// 获取token失败
log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
return accessToken;
} }

发送https请求需要一个证书信任管理器,所以此类依赖于MyX509TrustManager.java

 package com.ray.util;  

 import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; /**
* 证书信任管理器(用于https请求)
*
* @author liufeng
* @date 2013-08-08
*/
public class MyX509TrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
} public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
} public X509Certificate[] getAcceptedIssuers() {
return null;
}
}

2.3 实体类之凭证封装类——AccessToken.java

 package com.ray.pojo;  

 /**
* @desc : 微信通用接口凭证
*
* @author: shirayner
* @date : 2017-8-20 下午9:35:11
*/
public class AccessToken {
// 获取到的凭证
private String token;
// 凭证有效时间,单位:秒
private int expiresIn; public String getToken() {
return token;
} public void setToken(String token) {
this.token = token;
} public int getExpiresIn() {
return expiresIn;
} public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
}

2.4 实体类之用户类——User.java

注:这两个实体类只添加了User的部分属性,如有需要,读者可根据官方文档自行添加相关属性。

 package com.ray.pojo;

 public class User {
private String userid;
private String name;
private int department;
private String mobile;
private String email;
private String position;
private String gender; public User(){};
public User(String userid, String name, int department, String mobile,
String email, String position, String gender) {
super();
this.userid = userid;
this.name = name;
this.department = department;
this.mobile = mobile;
this.email = email;
this.position = position;
this.gender = gender;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} public int getDepartment() {
return department;
}
public void setDepartment(int department) {
this.department = department;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "User [userid=" + userid + ", name=" + name + ", department="
+ department + ", mobile=" + mobile + ", email=" + email
+ ", position=" + position + ", gender=" + gender + "]";
} public String toJson(){
String str="{\"userid\": %s,\"name\": %s,\"department\": [1],\"mobile\": %s,\"email\": %s,\"gender\": %s}"; return String.format(str,this.userid,this.name,this.mobile,this.email,this.gender);
} }

2.5 实体类之部门类——Department.java

 package com.ray.pojo;

 public class Department {
private int id ;
private String name;
private int parentid;
private int order; public Department(int id, String name, int parentid) {
super();
this.id = id;
this.name = name;
this.parentid = parentid;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getParentid() {
return parentid;
}
public void setParentid(int parentid) {
this.parentid = parentid;
}
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
} }

2.6 业务类之通讯录用户业务类——Contacts_UserService

 package com.ray.service;

 import java.util.HashMap;
import java.util.List;
import java.util.Map; import net.sf.json.JSONObject; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.google.gson.Gson;
import com.ray.pojo.User;
import com.ray.test.UserTest;
import com.ray.util.WeiXinUtil; public class Contacts_UserService {
private static Logger log = LoggerFactory.getLogger(UserTest.class); private static String createUser_url="https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=ACCESS_TOKEN";
private static String getUser_url="https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&userid=USERID";
private static String updateUser_url="https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=ACCESS_TOKEN";
private static String deleteUser_url="https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token=ACCESS_TOKEN&userid=USERID";
private static String batchdeleteUser_url="https://qyapi.weixin.qq.com/cgi-bin/user/batchdelete?access_token=ACCESS_TOKEN";
private static String getDepartmentUser_url="https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=ACCESS_TOKEN&department_id=DEPARTMENT_ID&fetch_child=FETCH_CHILD";
private static String getDepartmentUserDetails_url="https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=ACCESS_TOKEN&department_id=DEPARTMENT_ID&fetch_child=FETCH_CHILD"; //1.创建成员
public void createUser(String accessToken,User user) { //1.获取json字符串:将user对象转换为json字符串
Gson gson = new Gson();
String jsonU1 =gson.toJson(user); //使用gson.toJson(user)即可将user对象顺序转成json
System.out.println("jsonU1:"+jsonU1); //2.获取请求的url
createUser_url=createUser_url.replace("ACCESS_TOKEN", accessToken); //3.调用接口,发送请求,创建成员
JSONObject jsonObject = WeiXinUtil.httpRequest(createUser_url, "POST", jsonU1);
System.out.println("jsonObject:"+jsonObject.toString()); //4.错误消息处理
if (null != jsonObject) {
if (0 != jsonObject.getInt("errcode")) {
log.error("创建成员失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
} //2.获取成员
public void getUser(String accessToken,String userId) { //1.获取请求的url
getUser_url=getUser_url.replace("ACCESS_TOKEN", accessToken)
.replace("USERID", userId); //2.调用接口,发送请求,获取成员
JSONObject jsonObject = WeiXinUtil.httpRequest(getUser_url, "GET", null);
System.out.println("jsonObject:"+jsonObject.toString()); //3.错误消息处理
if (null != jsonObject) {
if (0 != jsonObject.getInt("errcode")) {
log.error("获取成员失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
} //3.更新成员
public void updateUser(String accessToken,User user) { //1.获取json字符串:将user对象转换为json字符串
Gson gson = new Gson();
String jsonU1 =gson.toJson(user); //使用gson.toJson(user)即可将user对象顺序转成json
System.out.println("jsonU1:"+jsonU1); //2.获取请求的url
updateUser_url=updateUser_url.replace("ACCESS_TOKEN", accessToken); //3.调用接口,发送请求,创建成员
JSONObject jsonObject = WeiXinUtil.httpRequest(updateUser_url, "POST", jsonU1);
System.out.println("jsonObject:"+jsonObject.toString()); //4.错误消息处理
if (null != jsonObject) {
if (0 != jsonObject.getInt("errcode")) {
log.error("更新成员失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
} //4.删除成员
public void deleteUser(String accessToken,String userId) { //1.获取请求的url
deleteUser_url=deleteUser_url.replace("ACCESS_TOKEN", accessToken)
.replace("USERID", userId); //2.调用接口,发送请求,删除成员
JSONObject jsonObject = WeiXinUtil.httpRequest(deleteUser_url, "GET", null);
System.out.println("jsonObject:"+jsonObject.toString()); //3.错误消息处理
if (null != jsonObject) {
if (0 != jsonObject.getInt("errcode")) {
log.error("删除成员失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
} //5.批量删除成员
public void batchdeleteUser(String accessToken,List<String> userIdList){
//1.获取json字符串:将user对象转换为json字符串
Map<String, Object> content = new HashMap<String, Object>();
content.put("useridlist", userIdList); Gson gson=new Gson();
String useridlist=gson.toJson(content);
System.out.println(useridlist); //2.获取请求的url
batchdeleteUser_url=batchdeleteUser_url.replace("ACCESS_TOKEN", accessToken); //3.调用接口,发送请求,创建成员
JSONObject jsonObject = WeiXinUtil.httpRequest(batchdeleteUser_url, "POST", useridlist);
System.out.println("jsonObject:"+jsonObject.toString()); //4.错误消息处理
if (null != jsonObject) {
if (0 != jsonObject.getInt("errcode")) {
log.error("批量删除成员失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
} //6.获取部门成员
public void getDepartmentUser(String accessToken,String departmentId,String fetchChild) { //1.获取请求的url
getDepartmentUser_url=getDepartmentUser_url.replace("ACCESS_TOKEN", accessToken)
.replace("DEPARTMENT_ID", departmentId)
.replace("FETCH_CHILD", fetchChild); //2.调用接口,发送请求,获取部门成员
JSONObject jsonObject = WeiXinUtil.httpRequest(getDepartmentUser_url, "GET", null);
System.out.println("jsonObject:"+jsonObject.toString()); //3.错误消息处理
if (null != jsonObject) {
if (0 != jsonObject.getInt("errcode")) {
log.error("获取部门成员失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
} //7.获取部门成员详情
public void getDepartmentUserDetails(String accessToken,String departmentId,String fetchChild) {
//1.获取请求的url
getDepartmentUserDetails_url=getDepartmentUserDetails_url.replace("ACCESS_TOKEN", accessToken)
.replace("DEPARTMENT_ID", departmentId)
.replace("FETCH_CHILD", fetchChild); //2.调用接口,发送请求,获取部门成员
JSONObject jsonObject = WeiXinUtil.httpRequest(getDepartmentUserDetails_url, "GET", null);
System.out.println("jsonObject:"+jsonObject.toString()); //3.错误消息处理
if (null != jsonObject) {
if (0 != jsonObject.getInt("errcode")) {
log.error("获取部门成员详情失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
} }

2.7 业务类之通讯录部门业务类

 package com.ray.service;

 import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.ray.pojo.Department;
import com.ray.test.DepartmentTest;
import com.ray.util.WeiXinUtil; public class Contacts_DepartmentService {
private static Logger log = LoggerFactory.getLogger(DepartmentTest.class); private static String createDepartment_url="https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=ACCESS_TOKEN";
private static String updateDepartment_url="https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=ACCESS_TOKEN";
private static String deleteDepartment_url="https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token=ACCESS_TOKEN&id=ID";
private static String getDepartmentList_url="https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=ACCESS_TOKEN&id=ID"; //1.创建部门
public void createDepartment(String accessToken,Department department) { //1.获取json字符串:将Department对象转换为json字符串
Gson gson = new Gson();
String jsonDepartment =gson.toJson(department); //使用gson.toJson(jsonDepartment)即可将jsonDepartment对象顺序转成json
System.out.println("jsonDepartment:"+jsonDepartment);
//2.拼接请求的url
createDepartment_url=createDepartment_url.replace("ACCESS_TOKEN", accessToken); //3.调用接口,发送请求,创建部门
JSONObject jsonObject = WeiXinUtil.httpRequest(createDepartment_url, "POST", jsonDepartment);
System.out.println("jsonObject:"+jsonObject.toString());
if (null != jsonObject) {
if (0 != jsonObject.getInt("errcode")) { log.error("创建部门失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
} //2.更新部门
public void updateDepartment(String accessToken,Department department) { //1.获取json字符串:将Department对象转换为json字符串
Gson gson = new Gson();
String jsonDepartment =gson.toJson(department); //使用gson.toJson(jsonDepartment)即可将jsonDepartment对象顺序转成json
System.out.println("jsonDepartment:"+jsonDepartment);
//2.拼接请求的url
updateDepartment_url=updateDepartment_url.replace("ACCESS_TOKEN", accessToken); //3.调用接口,发送请求,更新部门
JSONObject jsonObject = WeiXinUtil.httpRequest(updateDepartment_url, "POST", jsonDepartment);
System.out.println("jsonObject:"+jsonObject.toString());
if (null != jsonObject) {
if (0 != jsonObject.getInt("errcode")) { log.error("更新部门失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
} //3.删除部门
public void deleteDepartment(String accessToken,String departmentId) { //1.获取请求的url
deleteDepartment_url=deleteDepartment_url.replace("ACCESS_TOKEN", accessToken)
.replace("ID", departmentId); //2.调用接口,发送请求,删除部门
JSONObject jsonObject = WeiXinUtil.httpRequest(deleteDepartment_url, "GET", null);
System.out.println("jsonObject:"+jsonObject.toString()); //3.错误消息处理
if (null != jsonObject) {
if (0 != jsonObject.getInt("errcode")) {
log.error("删除部门失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
} //4.获取部门列表
public void getDepartmentList(String accessToken,String departmentId) { //1.获取请求的url
getDepartmentList_url=getDepartmentList_url.replace("ACCESS_TOKEN", accessToken)
.replace("ID", departmentId); //2.调用接口,发送请求,获取成员
JSONObject jsonObject = WeiXinUtil.httpRequest(getDepartmentList_url, "GET", null);
System.out.println("jsonObject:"+jsonObject.toString()); //3.错误消息处理
if (null != jsonObject) {
if (0 != jsonObject.getInt("errcode")) {
log.error("获取部门列表 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
} }

2.8 测试类之用户测试类-UserTest.java

 package com.ray.test;

 import java.util.Arrays;
import java.util.List; import org.junit.Test; import com.ray.pojo.User;
import com.ray.service.Contacts_UserService;
import com.ray.util.WeiXinParamesUtil;
import com.ray.util.WeiXinUtil; /**
* 成员管理
* @author shirayner
*
*要注意的地方:
*1.开启通讯录同步之后,才能进行通讯录的相关操作
*2.对通讯录操作的凭证access_token,由企业id-cropId和通讯录秘钥secret(而不是应用秘钥)获取。
*3.创建成员需要开启通讯录的编辑权限。(管理工具-通讯录同步)
*4.java对象转json: 用gson.toJson(user)即可将user对象顺序转成json
*/ public class UserTest { //1.创建成员
@Test
public void testCreateUser() {
//1.创建user对象
//User user = new User("3", "ray", 1,"13886086292","3057046319@qq.com","技术顾问","1");
User user = new User("4", "jack", 1,"13986086293","4057046319@qq.com","咨询顾问","1");
//User user = new User("5", "tom", 1,"14986086294","5057046319@qq.com","产品经理","1"); //2.获取access_token:根据企业id和通讯录密钥获取access_token,并拼接请求url
String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpId, WeiXinParamesUtil.contactsSecret).getToken();
System.out.println("accessToken:"+accessToken); //3.创建成员
Contacts_UserService cus=new Contacts_UserService();
cus.createUser(accessToken,user); } //2.获取成员
@Test
public void testGetUser() {
//1.获取userId
//String userId="ShiRui";
String userId="4"; //2.获取access_token:根据企业id和通讯录密钥获取access_token,并拼接请求url
String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpId, WeiXinParamesUtil.contactsSecret).getToken();
System.out.println("accessToken:"+accessToken); //3.获取成员
Contacts_UserService cus=new Contacts_UserService();
cus.getUser(userId, accessToken);
} //3.更新成员
@Test
public void testUpdateUser() { //1.更改user对象信息
//User user = new User("3", "ray", 1,"13886086292","3057046319@qq.com","技术顾问","1");
//User user = new User("4", "jack", 1,"13986086293","4057046319@qq.com","咨询顾问","1");
User user = new User("3", "ray", 1,"13889086292","3057946319@qq.com","咨询顾问","1"); //2.获取access_token:根据企业id和通讯录密钥获取access_token,并拼接请求url
String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpId, WeiXinParamesUtil.contactsSecret).getToken();
System.out.println("accessToken:"+accessToken); //3.创建成员
Contacts_UserService cus=new Contacts_UserService();
cus.updateUser( accessToken,user); } //4.删除成员
@Test
public void testDeleteUser() {
//1.获取userId
//String userId="ShiRui";
String userId="4"; //2.获取access_token:根据企业id和通讯录密钥获取access_token,并拼接请求url
String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpId, WeiXinParamesUtil.contactsSecret).getToken();
System.out.println("accessToken:"+accessToken); //3.创建成员
Contacts_UserService cus=new Contacts_UserService();
cus.deleteUser(userId, accessToken);
} //5.批量删除成员
@Test
public void testbatchdeleteUser() {
//1.获取userIdList
String userId1="3";
String userId2="4";
List<String> userIdList = Arrays.asList(userId1, userId2); //此时将userIdList转json,则结果为:["3","4"],会报错:{"errcode":40063,"errmsg":"some parameters are empty"} //2.获取access_token:根据企业id和通讯录密钥获取access_token,并拼接请求url
String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpId, WeiXinParamesUtil.contactsSecret).getToken();
System.out.println("accessToken:"+accessToken); //3.批量删除成员
Contacts_UserService cus=new Contacts_UserService();
cus.batchdeleteUser(accessToken,userIdList);
} //6.获取部门成员
@Test
public void testGetDepartmentUser() {
//1.获取部门ID以及是否获取子部门成员
String departmentId="1";
String fetchChild="0"; //2.获取accessToken:根据企业id和通讯录密钥获取access_token,并拼接请求url
String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpId, WeiXinParamesUtil.contactsSecret).getToken();
System.out.println("accessToken:"+accessToken); //3.获取部门成员
Contacts_UserService cus=new Contacts_UserService();
cus.getDepartmentUser(accessToken, departmentId, fetchChild);
} //7.获取部门成员详情
@Test
public void testGetDepartmentUserDetails() {
//1.获取部门ID以及是否获取子部门成员
String departmentId="1";
String fetchChild="0"; //2.获取accessToken:根据企业id和通讯录密钥获取access_token,并拼接请求url
String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpId, WeiXinParamesUtil.contactsSecret).getToken();
System.out.println("accessToken:"+accessToken); //3.获取部门成员
Contacts_UserService cus=new Contacts_UserService();
cus.getDepartmentUserDetails(accessToken, departmentId, fetchChild);
}
}

2.9 测试类之部门测试类-DepartmentTest.java

 package com.ray.test;

 import org.junit.Test;
import com.ray.pojo.Department;
import com.ray.service.Contacts_DepartmentService;
import com.ray.util.WeiXinParamesUtil;
import com.ray.util.WeiXinUtil; /**
* 部门管理
* @author shirayner
*
*
*/ public class DepartmentTest { //1.创建部门
@Test
public void testCreateDepartment() {
//1.创建Department对象,并将对象转换成json字符串
Department department = new Department(3, "HEC武汉分公司", 2);
//Department department = new Department(2, "HEC技术中心", 1); //2.获取access_token:根据企业id和通讯录密钥获取access_token,并拼接请求url
String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpId, WeiXinParamesUtil.contactsSecret).getToken();
System.out.println("accessToken:"+accessToken); //3.创建部门
Contacts_DepartmentService cds= new Contacts_DepartmentService();
cds.createDepartment(accessToken, department);
} //2.更新部门
@Test
public void testUpdateDepartment() {
//1.创建Department对象,并将对象转换成json字符串
Department department = new Department(2, "HEC技术服务中心", 1); //2.获取access_token:根据企业id和通讯录密钥获取access_token,并拼接请求url
String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpId, WeiXinParamesUtil.contactsSecret).getToken();
System.out.println("accessToken:"+accessToken); //3.更新部门
Contacts_DepartmentService cds= new Contacts_DepartmentService();
cds.updateDepartment(accessToken, department);
} //3.删除部门
@Test
public void testDeleteDepartment() {
//1.获取userId
String departmentId="3"; //2.获取access_token:根据企业id和通讯录密钥获取access_token,并拼接请求url
String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpId, WeiXinParamesUtil.contactsSecret).getToken();
System.out.println("accessToken:"+accessToken); //3.删除部门
Contacts_DepartmentService cds= new Contacts_DepartmentService();
cds.deleteDepartment(accessToken, departmentId);
} /**
* 4.获取部门列表
* 参数 必须 说明
* access_token 是 调用接口凭证
* id 否 部门id。获取指定部门及其下的子部门。 如果不填,默认获取全量组织架构
*/
@Test
public void testGetDepartmentList() {
//1.获取departmentId
String departmentId="1"; //2.获取access_token:根据企业id和通讯录密钥获取access_token,并拼接请求url
String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpId, WeiXinParamesUtil.contactsSecret).getToken();
System.out.println("accessToken:"+accessToken); //3.调用接口,发送请求,删除部门
Contacts_DepartmentService cds= new Contacts_DepartmentService();
cds.getDepartmentList(accessToken, departmentId);
} }

三、参考资料

1.微信企业号官方开发文档:https://work.weixin.qq.com/api/doc#10016

上一篇:Java企业微信开发_09_身份验证之移动端网页授权(有完整项目源码)


下一篇:Java企业微信开发_07_素材管理之上传本地临时素材文件