一、本节要点

1.通讯录权限

ISV(应用服务商)默认无管理通讯录的权限,企业应用默认有所有通讯录权限。

2.数据传输格式—JSON

请参见: Java_数据交换_fastJSON_01_用法入门

二、代码实现

1.HTTP请求工具类—HttpHelper

package com.ray.dingtalk.qy.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream; import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; /**
* HTTP请求封装,建议直接使用sdk的API
*/
public class HttpHelper {
private static final Logger log = LogManager.getLogger(HttpHelper.class); /**
* @desc :1.发起GET请求
*
* @param url
* @return JSONObject
* @throws Exception
*/
public static JSONObject doGet(String url) throws Exception { //1.生成一个请求
HttpGet httpGet = new HttpGet(url);
//2.配置请求的属性
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();//
httpGet.setConfig(requestConfig); //3.发起请求,获取响应信息
//3.1 创建httpClient
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
//3.2 发起请求,获取响应信息
response = httpClient.execute(httpGet, new BasicHttpContext()); //如果返回结果的code不等于200,说明出错了
if (response.getStatusLine().getStatusCode() != 200) { log.info("request url failed, http code=" + response.getStatusLine().getStatusCode()
+ ", url=" + url);
return null;
}
//4.解析请求结果
HttpEntity entity = response.getEntity(); //reponse返回的数据在entity中
if (entity != null) {
String resultStr = EntityUtils.toString(entity, "utf-8"); //将数据转化为string格式
log.info("GET请求结果:"+resultStr);
JSONObject result = JSON.parseObject(resultStr); //将String转换为 JSONObject if(result.getInteger("errcode")==null) {
return result;
}else if (0 == result.getInteger("errcode")) {
return result;
}else {
log.info("request url=" + url + ",return value=");
log.info(resultStr);
int errCode = result.getInteger("errcode");
String errMsg = result.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
}
} catch (IOException e) {
log.info("request url=" + url + ", exception, msg=" + e.getMessage());
e.printStackTrace();
} finally {
if (response != null) try {
response.close(); //释放资源 } catch (IOException e) {
e.printStackTrace();
}
} return null;
} /** 2.发起POST请求
* @desc :
*
* @param url 请求url
* @param data 请求参数(json)
* @return
* @throws Exception JSONObject
*/
public static JSONObject doPost(String url, Object data) throws Exception {
//1.生成一个请求
HttpPost httpPost = new HttpPost(url); //2.配置请求属性
//2.1 设置请求超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
httpPost.setConfig(requestConfig);
//2.2 设置数据传输格式-json
httpPost.addHeader("Content-Type", "application/json");
//2.3 设置请求实体,封装了请求参数
StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8");
httpPost.setEntity(requestEntity); //3.发起请求,获取响应信息
//3.1 创建httpClient
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null; try { //3.3 发起请求,获取响应
response = httpClient.execute(httpPost, new BasicHttpContext()); if (response.getStatusLine().getStatusCode() != 200) { log.info("request url failed, http code=" + response.getStatusLine().getStatusCode()
+ ", url=" + url);
return null;
} //获取响应内容
HttpEntity entity = response.getEntity();
if (entity != null) {
String resultStr = EntityUtils.toString(entity, "utf-8");
log.info("POST请求结果:"+resultStr); //解析响应内容
JSONObject result = JSON.parseObject(resultStr); if(result.getInteger("errcode")==null) {
return result;
}else if (0 == result.getInteger("errcode")) {
return result;
}else {
log.info("request url=" + url + ",return value=");
log.info(resultStr);
int errCode = result.getInteger("errcode");
String errMsg = result.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
}
} catch (IOException e) {
log.info("request url=" + url + ", exception, msg=" + e.getMessage());
e.printStackTrace();
} finally {
if (response != null) try {
response.close(); //释放资源 } catch (IOException e) {
e.printStackTrace();
}
} return null;
} /**
* @desc : 3.
*
* @param url
* @param file
* @return
* @throws Exception
* JSONObject
*/
public static JSONObject uploadMedia(String url, File file) throws Exception {
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
httpPost.setConfig(requestConfig); HttpEntity requestEntity = MultipartEntityBuilder.create().addPart("media",
new FileBody(file, ContentType.APPLICATION_OCTET_STREAM, file.getName())).build();
httpPost.setEntity(requestEntity); try {
response = httpClient.execute(httpPost, new BasicHttpContext()); if (response.getStatusLine().getStatusCode() != 200) { log.info("request url failed, http code=" + response.getStatusLine().getStatusCode()
+ ", url=" + url);
return null;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
String resultStr = EntityUtils.toString(entity, "utf-8"); JSONObject result = JSON.parseObject(resultStr);
if (result.getInteger("errcode") == 0) {
// 成功
//result.remove("errcode");
//result.remove("errmsg");
return result;
} else {
log.info("request url=" + url + ",return value=");
log.info(resultStr);
int errCode = result.getInteger("errcode");
String errMsg = result.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
}
} catch (IOException e) {
log.info("request url=" + url + ", exception, msg=" + e.getMessage());
e.printStackTrace();
} finally {
if (response != null) try {
response.close(); //释放资源 } catch (IOException e) {
e.printStackTrace();
}
} return null;
} public static File downloadMedia(String url, String fileDir) throws Exception {
//1.生成一个请求
HttpGet httpGet = new HttpGet(url);
//2.配置请求属性
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
httpGet.setConfig(requestConfig); //3.发起请求,获取响应信息
//3.1 创建httpClient
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null; //4.设置本地保存的文件
File file = new File(fileDir); try {
//5. 发起请求,获取响应信息
response = httpClient.execute(httpGet, new BasicHttpContext());
log.info("HttpStatus.SC_OK:"+HttpStatus.SC_OK);
log.info("response.getStatusLine().getStatusCode():"+response.getStatusLine().getStatusCode()); //请求成功
if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){ //6.取得请求内容
HttpEntity entity = response.getEntity(); if (entity != null) {
//这里可以得到文件的类型 如image/jpg /zip /tiff 等等 但是发现并不是十分有效,有时明明后缀是.rar但是取到的是null,这点特别说明
log.info(entity.getContentType());
//可以判断是否是文件数据流
log.info(entity.isStreaming()); //6.1 输出流
FileOutputStream output = new FileOutputStream(file);
//6.2 输入流:从钉钉服务器返回的文件流,得到网络资源并写入文件
InputStream input = entity.getContent(); //6.3 将数据写入文件:将输入流中的数据写入到输出流
byte b[] = new byte[1024];
int j = 0;
while( (j = input.read(b))!=-1){
output.write(b,0,j);
}
output.flush();
output.close();
}
if (entity != null) {
entity.consumeContent();
}
}
} catch (IOException e) {
log.info("request url=" + url + ", exception, msg=" + e.getMessage());
e.printStackTrace();
} finally {
if (response != null) try {
response.close(); //释放资源 } catch (IOException e) {
e.printStackTrace();
}
} return file;
} }

2.Token工具类—AuthHelper

package com.ray.dingtalk.qy.auth;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID; import javax.servlet.http.HttpServletRequest; import com.alibaba.fastjson.JSONObject;
import com.ray.dingtalk.qy.config.Env;
import com.ray.dingtalk.qy.util.HttpHelper; /**
* 钉钉相关配置参数的获取工具类
* @desc : AccessToken和jsticket的获取封装
*
* @author: shirayner
* @date : 2017年9月27日 下午5:00:25
*/
public class AuthHelper {
//private static Logger log = LoggerFactory.getLogger(AuthHelper.class);
//获取access_token的接口地址,有效期为7200秒
private static final String GET_ACCESSTOKEN_URL="https://oapi.dingtalk.com/gettoken?corpid=CORPID&corpsecret=CORPSECRET"; //获取getJsapiTicket的接口地址,有效期为7200秒
private static final String GET_JSAPITICKET_URL="https://oapi.dingtalk.com/get_jsapi_ticket?access_token=ACCESSTOKE"; /** 1.获取access_token
* @desc :
*
* @param corpId
* @param corpSecret
* @return
* @throws Exception String
*/
public static String getAccessToken(String corpId,String corpSecret) throws Exception {
//1.获取请求url
String url=GET_ACCESSTOKEN_URL.replace("CORPID", corpId).replace("CORPSECRET", corpSecret); //2.发起GET请求,获取返回结果
JSONObject jsonObject=HttpHelper.doGet(url); //3.解析结果,获取accessToken
String accessToken="";
if (null != jsonObject) {
accessToken=jsonObject.getString("access_token"); //4.错误消息处理
if (0 != jsonObject.getInteger("errcode")) {
int errCode = jsonObject.getInteger("errcode");
String errMsg = jsonObject.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
} return accessToken;
} /**
* 2、获取JSTicket, 用于js的签名计算
* 正常的情况下,jsapi_ticket的有效期为7200秒,所以开发者需要在某个地方设计一个定时器,定期去更新jsapi_ticket
* @throws Exception
*/
public static String getJsapiTicket(String accessToken) throws Exception {
//1.获取请求url
String url=GET_JSAPITICKET_URL.replace("ACCESSTOKE", accessToken); //2.发起GET请求,获取返回结果
JSONObject jsonObject=HttpHelper.doGet(url); //3.解析结果,获取ticket
String ticket="";
if (null != jsonObject) {
ticket=jsonObject.getString("ticket"); //4.错误消息处理
if (0 != jsonObject.getInteger("errcode")) {
int errCode = jsonObject.getInteger("errcode");
String errMsg = jsonObject.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
} return ticket;
} /**
* @desc : 3.生成签名的函数
*
* @param ticket jsticket
* @param nonceStr 随机串,自己定义
* @param timeStamp 生成签名用的时间戳
* @param url 需要进行免登鉴权的页面地址,也就是执行dd.config的页面地址
* @return
* @throws Exception String
*/ public static String getSign(String jsTicket, String nonceStr, Long timeStamp, String url) throws Exception {
String plainTex = "jsapi_ticket=" + jsTicket + "&noncestr=" + nonceStr + "&timestamp=" + timeStamp + "&url=" + url;
System.out.println(plainTex);
try {
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(plainTex.getBytes("UTF-8"));
return byteToHex(crypt.digest());
} catch (NoSuchAlgorithmException e) {
throw new Exception(e.getMessage());
} catch (UnsupportedEncodingException e) {
throw new Exception(e.getMessage());
}
} //将bytes类型的数据转化为16进制类型
private static String byteToHex(byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash) {
formatter.format("%02x", new Object[] { Byte.valueOf(b) });
}
String result = formatter.toString();
formatter.close();
return result;
} /**
* @desc :获取前端jsapi需要的配置参数(已弃用,请用getConfig(HttpServletRequest))
*
* @param request request:在钉钉中点击微应用图标跳转的url地址
* @return Map<String,Object> 将需要的参数存入map,并返回
*/
public static Map<String, Object> getDDConfig(HttpServletRequest request){ Map<String, Object> configMap = new HashMap<String, Object>(); //1.准备好参与签名的字段
/*
*以http://localhost/test.do?a=b&c=d为例
*request.getRequestURL的结果是http://localhost/test.do
*request.getQueryString的返回值是a=b&c=d
*/
String urlString = request.getRequestURL().toString();
String queryString = request.getQueryString(); String queryStringEncode = null;
String url;
if (queryString != null) {
queryStringEncode = URLDecoder.decode(queryString);
url = urlString + "?" + queryStringEncode;
} else {
url = urlString;
} String nonceStr=UUID.randomUUID().toString(); //随机数
long timeStamp = System.currentTimeMillis() / 1000; //时间戳参数 String signedUrl = url;
String accessToken = null;
String ticket = null;
String signature = null; //签名 //2.进行签名,获取signature
try {
accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET); ticket=AuthHelper.getJsapiTicket(accessToken);
signature=getSign(ticket,nonceStr,timeStamp,signedUrl); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} System.out.println("accessToken:"+accessToken);
System.out.println("ticket:"+ticket);
System.out.println("nonceStr:"+nonceStr);
System.out.println("timeStamp:"+timeStamp);
System.out.println("signedUrl:"+signedUrl);
System.out.println("signature:"+signature);
System.out.println("agentId:"+Env.AGENTID);
System.out.println("corpId:"+Env.CORP_ID); //3.将配置参数存入Map
configMap.put("agentId", Env.AGENTID);
configMap.put("corpId", Env.CORP_ID);
configMap.put("timeStamp", timeStamp);
configMap.put("nonceStr", nonceStr);
configMap.put("signature", signature); return configMap;
} public static String getConfig(HttpServletRequest request){ //1.准备好参与签名的字段
/*
*以http://localhost/test.do?a=b&c=d为例
*request.getRequestURL的结果是http://localhost/test.do
*request.getQueryString的返回值是a=b&c=d
*/
String urlString = request.getRequestURL().toString();
String queryString = request.getQueryString(); String queryStringEncode = null;
String url;
if (queryString != null) {
queryStringEncode = URLDecoder.decode(queryString);
url = urlString + "?" + queryStringEncode;
} else {
url = urlString;
} String nonceStr=UUID.randomUUID().toString(); //随机数
long timeStamp = System.currentTimeMillis() / 1000; //时间戳参数 String signedUrl = url;
String accessToken = null;
String ticket = null;
String signature = null; //签名 //2.进行签名,获取signature
try {
accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET); ticket=AuthHelper.getJsapiTicket(accessToken);
signature=getSign(ticket,nonceStr,timeStamp,signedUrl); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} System.out.println("accessToken:"+accessToken);
System.out.println("ticket:"+ticket);
System.out.println("nonceStr:"+nonceStr);
System.out.println("timeStamp:"+timeStamp);
System.out.println("signedUrl:"+signedUrl);
System.out.println("signature:"+signature);
System.out.println("agentId:"+Env.AGENTID);
System.out.println("corpId:"+Env.CORP_ID); String configValue = "{jsticket:'" + ticket + "',signature:'" + signature + "',nonceStr:'" + nonceStr + "',timeStamp:'"
+ timeStamp + "',corpId:'" + Env.CORP_ID + "',agentId:'" + Env.AGENTID + "'}";
System.out.println(configValue); return configValue;
} }

3.成员实体类—User

package com.ray.dingtalk.qy.model.contact;

import java.util.List;

import com.alibaba.fastjson.JSONObject;

/**@desc  : 用户类
*
* @author: shirayner
* @date : 2017年9月28日 上午9:38:25
*/
public class User { public String userid;
public String name; //必须
public boolean active;
public String avatar;
public List<Long> department; //必须
public String position;
public String mobile; //必须
public String tel;
public String workPlace;
public String remark;
public String email;
public String jobnumber;
public JSONObject extattr;
public boolean isAdmin;
public boolean isBoss;
public String dingId; /**
* @return the userid
*/
public String getUserid() {
return userid;
}
/**
* @param userid the userid to set
*/
public void setUserid(String userid) {
this.userid = userid;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the active
*/
public boolean isActive() {
return active;
}
/**
* @param active the active to set
*/
public void setActive(boolean active) {
this.active = active;
}
/**
* @return the avatar
*/
public String getAvatar() {
return avatar;
}
/**
* @param avatar the avatar to set
*/
public void setAvatar(String avatar) {
this.avatar = avatar;
}
/**
* @return the department
*/
public List<Long> getDepartment() {
return department;
}
/**
* @param department the department to set
*/
public void setDepartment(List<Long> department) {
this.department = department;
}
/**
* @return the position
*/
public String getPosition() {
return position;
}
/**
* @param position the position to set
*/
public void setPosition(String position) {
this.position = position;
}
/**
* @return the mobile
*/
public String getMobile() {
return mobile;
}
/**
* @param mobile the mobile to set
*/
public void setMobile(String mobile) {
this.mobile = mobile;
}
/**
* @return the tel
*/
public String getTel() {
return tel;
}
/**
* @param tel the tel to set
*/
public void setTel(String tel) {
this.tel = tel;
}
/**
* @return the workPlace
*/
public String getWorkPlace() {
return workPlace;
}
/**
* @param workPlace the workPlace to set
*/
public void setWorkPlace(String workPlace) {
this.workPlace = workPlace;
}
/**
* @return the remark
*/
public String getRemark() {
return remark;
}
/**
* @param remark the remark to set
*/
public void setRemark(String remark) {
this.remark = remark;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return the jobnumber
*/
public String getJobnumber() {
return jobnumber;
}
/**
* @param jobnumber the jobnumber to set
*/
public void setJobnumber(String jobnumber) {
this.jobnumber = jobnumber;
}
/**
* @return the extattr
*/
public JSONObject getExtattr() {
return extattr;
}
/**
* @param extattr the extattr to set
*/
public void setExtattr(JSONObject extattr) {
this.extattr = extattr;
}
/**
* @return the isAdmin
*/
public boolean isAdmin() {
return isAdmin;
}
/**
* @param isAdmin the isAdmin to set
*/
public void setAdmin(boolean isAdmin) {
this.isAdmin = isAdmin;
}
/**
* @return the isBoss
*/
public boolean isBoss() {
return isBoss;
}
/**
* @param isBoss the isBoss to set
*/
public void setBoss(boolean isBoss) {
this.isBoss = isBoss;
}
/**
* @return the dingId
*/
public String getDingId() {
return dingId;
}
/**
* @param dingId the dingId to set
*/
public void setDingId(String dingId) {
this.dingId = dingId;
} @Override
public String toString() {
return "User[userid:" + userid + ", name:" + name + ", active:" + active + ", "
+ "avatar:" + avatar + ", department:" + department +
", position:" + position + ", mobile:" + mobile + ", email:" + email +
", extattr:" + extattr;
} }

4.部门实体类—Department

package com.ray.dingtalk.qy.model.contact;

/**@desc  :
*
* @author: shirayner
* @date : 2017年10月18日 下午2:14:20
*/
public class Department {
//部门id
private long id;
//是 部门名称。长度限制为1~64个字符。不允许包含字符‘-’‘,’以及‘,’。
private String name;
//是 父部门id。根部门id为1
private String parentid;
//否 在父部门中的次序值。order值小的排序靠前
private String order;
//否 是否创建一个关联此部门的企业群,默认为false
private Boolean createDeptGroup; //否 是否隐藏部门, true表示隐藏, false表示显示
private Boolean deptHiding;
//否 可以查看指定隐藏部门的其他部门列表,如果部门隐藏,则此值生效,
//取值为其他的部门id组成的的字符串,使用 | 符号进行分割。总数不能超过200。
private String deptPerimits;
//否 可以查看指定隐藏部门的其他人员列表,如果部门隐藏,则此值生效,取值为其他的人员userid组成的的字符串,
//使用| 符号进行分割。总数不能超过200。
private String userPerimits;
//否 是否本部门的员工仅可见员工自己, 为true时,本部门员工默认只能看到员工自己
private Boolean outerDept;
//否 本部门的员工仅可见员工自己为true时,可以配置额外可见部门,值为部门id组成的的字符串,
//使用|符号进行分割。总数不能超过200。
private String outerPermitDepts;
//否 本部门的员工仅可见员工自己为true时,可以配置额外可见人员,值为userid组成的的字符串,
//使用|符号进行分割。总数不能超过200。
private String outerPermitUsers;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParentid() {
return parentid;
}
public void setParentid(String parentid) {
this.parentid = parentid;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
public Boolean getCreateDeptGroup() {
return createDeptGroup;
}
public void setCreateDeptGroup(Boolean createDeptGroup) {
this.createDeptGroup = createDeptGroup;
}
public Boolean getDeptHiding() {
return deptHiding;
}
public void setDeptHiding(Boolean deptHiding) {
this.deptHiding = deptHiding;
}
public String getDeptPerimits() {
return deptPerimits;
}
public void setDeptPerimits(String deptPerimits) {
this.deptPerimits = deptPerimits;
}
public String getUserPerimits() {
return userPerimits;
}
public void setUserPerimits(String userPerimits) {
this.userPerimits = userPerimits;
}
public Boolean getOuterDept() {
return outerDept;
}
public void setOuterDept(Boolean outerDept) {
this.outerDept = outerDept;
}
public String getOuterPermitDepts() {
return outerPermitDepts;
}
public void setOuterPermitDepts(String outerPermitDepts) {
this.outerPermitDepts = outerPermitDepts;
}
public String getOuterPermitUsers() {
return outerPermitUsers;
}
public void setOuterPermitUsers(String outerPermitUsers) {
this.outerPermitUsers = outerPermitUsers;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
} }

5.成员管理业务类—UserService

package com.ray.dingtalk.qy.service.contact;

import java.util.List;
import java.util.Map; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ray.dingtalk.qy.model.contact.User;
import com.ray.dingtalk.qy.util.HttpHelper; /**@desc : 成员管理业务类
*
* @author: shirayner
* @date : 2017年9月28日 上午9:53:51
*/
public class UserService {
//1.获取成员详情 接口
private static final String GET_USER_URL="https://oapi.dingtalk.com/user/get?access_token=ACCESS_TOKEN&userid=ID";
//2.创建成员 接口
private static final String CREATE_USER_URL="https://oapi.dingtalk.com/user/create?access_token=ACCESS_TOKEN";
//3.更新成员
private static final String UPDATE_USER_URL="https://oapi.dingtalk.com/user/update?access_token=ACCESS_TOKEN";
//4.删除成员
private static final String DELETE_USER_URL="https://oapi.dingtalk.com/user/delete?access_token=ACCESS_TOKEN&userid=ID";
//5.批量删除成员
private static final String BATCHDELETE_USER_URL="https://oapi.dingtalk.com/user/batchdelete?access_token=ACCESS_TOKEN";
//6.获取部门成员(simplelist)
private static final String LIST_DEPARTMENTUSER_URL="https://oapi.dingtalk.com/user/simplelist?access_token=ACCESS_TOKEN&department_id=DEPARTMENTID";
//7.获取部门成员(详情)
private static final String LIST_DEPARTMENTUSERDETAIL_URL="https://oapi.dingtalk.com/user/list?access_token=ACCESS_TOKEN&department_id=DEPARTMENTID";
//8.获取管理员列表
private static final String LIST_ADMIN_URL="https://oapi.dingtalk.com/user/get_admin?access_token=ACCESS_TOKEN";
//9.根据unionid获取成员的userid
private static final String GET_USERID_BYUNIONID_URL="https://oapi.dingtalk.com/user/getUseridByUnionid?access_token=ACCESS_TOKEN&unionid=UNIONID";
//10.通过CODE换取用户身份
private static final String GET_USERINFO_BYCODE_URL="https://oapi.dingtalk.com/user/getuserinfo?access_token=ACCESS_TOKEN&code=CODE"; /** 1.根据userid获取成员详情
* @desc :获取成员详情
* 参考文档: https://open-doc.dingtalk.com/docs/doc.htm?spm=0.0.0.0.jjSfQQ&treeId=371&articleId=106816&docType=1#s0
* @param accessToken
* @param userId
* return JSONObject 返回用户详情
* @throws Exception
*/
public JSONObject getUser(String accessToken, String userId) throws Exception { //1.获取请求url
String url=GET_USER_URL.replace("ACCESS_TOKEN", accessToken).replace("ID", userId); //2.发起GET请求,获取返回结果
JSONObject jsonObject=HttpHelper.doGet(url);
System.out.println("jsonObject:"+jsonObject.toString());
//3.解析结果,获取User
if (null != jsonObject) { //4.请求成功,则返回jsonObject
if (0==jsonObject.getInteger("errcode")) {
return jsonObject;
} //5.错误消息处理
if (0 != jsonObject.getInteger("errcode")) {
int errCode = jsonObject.getInteger("errcode");
String errMsg = jsonObject.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
} } return null;
} /**2.创建成员
* @desc :
*
* @param accessToken
* @param user
* @return 返回用户id
* @throws Exception String
*/
public String createUser(String accessToken,User user) throws Exception {
//1.准备POST请求参数
Object data=JSON.toJSON(user);
System.out.println(data); //2.获取请求url
String url=CREATE_USER_URL.replace("ACCESS_TOKEN", accessToken); //3.发起POST请求,获取返回结果
JSONObject jsonObject=HttpHelper.doPost(url, data);
System.out.println("jsonObject:"+jsonObject.toString()); //4.解析结果,获取UserId
String userId="";
if (null != jsonObject) {
userId=jsonObject.getString("userid");
//5.错误消息处理
if (0 != jsonObject.getInteger("errcode")) {
int errCode = jsonObject.getInteger("errcode");
String errMsg = jsonObject.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
} return userId;
} /**3.更新成员
* @desc :
* 参数说明(如果非必须的字段未指定,则钉钉后台不改变该字段之前设置好的值)
* @param accessToken
* @param user
* @return
* @throws Exception String
*/
public void updateUser(String accessToken,User user) throws Exception {
//1.准备POST请求参数
Object data=JSON.toJSON(user);
System.out.println(data); //2.获取请求url
String url=UPDATE_USER_URL.replace("ACCESS_TOKEN", accessToken); //3.发起POST请求,获取返回结果
JSONObject jsonObject=HttpHelper.doPost(url, data);
System.out.println("jsonObject:"+jsonObject.toString()); //4.解析结果
if (null != jsonObject) { //5.错误消息处理
if (0 != jsonObject.getInteger("errcode")) {
int errCode = jsonObject.getInteger("errcode");
String errMsg = jsonObject.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
} } /** 4.删除成员
*
* @param accessToken
* @param userId void
* @throws Exception
*/
public JSONObject deleteUser(String accessToken, String userId) throws Exception { //1.获取请求url
String url=DELETE_USER_URL.replace("ACCESS_TOKEN", accessToken).replace("ID", userId); //2.发起GET请求,获取返回结果
JSONObject jsonObject=HttpHelper.doGet(url);
System.out.println("jsonObject:"+jsonObject.toString());
//3.解析结果,获取User
if (null != jsonObject) {
//4.请求成功,则返回jsonObject
if (0==jsonObject.getInteger("errcode")) {
return jsonObject;
}
//5.错误消息处理
if (0 != jsonObject.getInteger("errcode")) {
int errCode = jsonObject.getInteger("errcode");
String errMsg = jsonObject.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
} return null;
} /** 5.批量删除成员
* @desc :
*
* @param accessToken
* @param user
* @throws Exception void
*/
public void batchDeleteUser(String accessToken,Map< String , List<String> > userIdlistMap) throws Exception {
//1.准备POST请求参数
Object data=JSON.toJSON(userIdlistMap);
System.out.println(data); //2.获取请求url
String url=BATCHDELETE_USER_URL.replace("ACCESS_TOKEN", accessToken); //3.发起POST请求,获取返回结果
JSONObject jsonObject=HttpHelper.doPost(url, data);
System.out.println("jsonObject:"+jsonObject.toString()); //4.解析结果
if (null != jsonObject) { //5.错误消息处理
if (0 != jsonObject.getInteger("errcode")) {
int errCode = jsonObject.getInteger("errcode");
String errMsg = jsonObject.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
} } /** 6.获取部门成员(simplelist)
* @desc :
*
* @param accessToken
* @param departmentId
* return userList 用户列表
* @throws Exception void
*/
public JSONObject listDepartmentUser(String accessToken, String departmentId) throws Exception { //1.获取请求url
String url=LIST_DEPARTMENTUSER_URL.replace("ACCESS_TOKEN", accessToken).replace("DEPARTMENTID", departmentId); //2.发起GET请求,获取返回结果
JSONObject jsonObject=HttpHelper.doGet(url);
System.out.println("jsonObject:"+jsonObject.toString()); //3.解析结果,获取User
if (null != jsonObject) {
//4.请求成功,则返回jsonObject
if (0==jsonObject.getInteger("errcode")) {
return jsonObject;
} //5.错误消息处理
if (0 != jsonObject.getInteger("errcode")) {
int errCode = jsonObject.getInteger("errcode");
String errMsg = jsonObject.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
} return null;
} /** 7.获取部门成员(详情)
* @desc :
*
* @param accessToken
* @param departmentId
* return userList 用户列表
* @throws Exception void
*/
public JSONObject listDepartmentUserDetail(String accessToken, String departmentId) throws Exception { //1.获取请求url
String url=LIST_DEPARTMENTUSERDETAIL_URL.replace("ACCESS_TOKEN", accessToken).replace("DEPARTMENTID", departmentId); //2.发起GET请求,获取返回结果
JSONObject jsonObject=HttpHelper.doGet(url);
System.out.println("jsonObject:"+jsonObject.toString()); //3.解析结果,获取User
if (null != jsonObject) {
//4.请求成功,则返回jsonObject
if (0==jsonObject.getInteger("errcode")) {
return jsonObject;
} //4.错误消息处理
if (0 != jsonObject.getInteger("errcode")) {
int errCode = jsonObject.getInteger("errcode");
String errMsg = jsonObject.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
} return null;
} /**8.获取管理员列表
* @desc :
*
* @param accessToken
* @return adminList 管理员列表
* @throws Exception JSONObject
*/
public JSONObject listAdmin(String accessToken) throws Exception { //1.获取请求url
String url=LIST_ADMIN_URL.replace("ACCESS_TOKEN", accessToken); //2.发起GET请求,获取返回结果
JSONObject jsonObject=HttpHelper.doGet(url);
System.out.println("jsonObject:"+jsonObject.toString()); //3.解析结果,获取adminList
if (null != jsonObject) {
//4.请求成功,则返回jsonObject
if (0==jsonObject.getInteger("errcode")) {
return jsonObject;
} //5.错误消息处理
if (0 != jsonObject.getInteger("errcode")) {
int errCode = jsonObject.getInteger("errcode");
String errMsg = jsonObject.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
} return null;
} /** 9.根据unionid获取成员的userid
* @desc :
*
* @param accessToken
* @param unionId
* @return 用户id
* @throws Exception JSONObject
*/
public String getUserIdByUnionId(String accessToken, String unionId) throws Exception { //1.获取请求url
String url=GET_USERID_BYUNIONID_URL.replace("ACCESS_TOKEN", accessToken).replace("UNIONID", unionId); //2.发起GET请求,获取返回结果
JSONObject jsonObject=HttpHelper.doGet(url);
System.out.println("jsonObject:"+jsonObject.toString());
//3.解析结果,获取User
if (null != jsonObject) {
//4.请求成功,则返回jsonObject
if (0==jsonObject.getInteger("errcode")) {
return jsonObject.getString("userid");
}
//5.错误消息处理
if (0 != jsonObject.getInteger("errcode")) {
int errCode = jsonObject.getInteger("errcode");
String errMsg = jsonObject.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
} return null;
} /** 10.通过CODE换取用户身份
* @desc :钉钉服务器返回的用户信息为:
* userid 员工在企业内的UserID
* deviceId 手机设备号,由钉钉在安装时随机产生
* is_sys 是否是管理员
* sys_level 级别,0:非管理员 1:超级管理员(主管理员) 2:普通管理员(子管理员) 100:老板
*
* @param accessToken
* @param code
* @throws Exception void
*/
public JSONObject getUserInfo(String accessToken,String code) throws Exception { //1.获取请求url
String url=GET_USERINFO_BYCODE_URL.replace("ACCESS_TOKEN", accessToken).replace("CODE", code); //2.发起GET请求,获取返回结果
JSONObject jsonObject=HttpHelper.doGet(url);
System.out.println("jsonObject:"+jsonObject.toString()); //3.解析结果,获取User
if (null != jsonObject) {
//4.请求成功,则返回jsonObject
if (0==jsonObject.getInteger("errcode")) {
return jsonObject;
}
//5.错误消息处理
if (0 != jsonObject.getInteger("errcode")) {
int errCode = jsonObject.getInteger("errcode");
String errMsg = jsonObject.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
} return null;
} }

6.部门管理业务类—DepartmentServcie

package com.ray.dingtalk.qy.service.contact;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ray.dingtalk.qy.model.contact.Department;
import com.ray.dingtalk.qy.util.HttpHelper; /**@desc : 部门管理业务类
*
* @author: shirayner
* @date : 2017年10月18日 下午12:39:21
*/
public class DepartmentServcie {
//1.获取部门列表
private static final String LIST_DEPARTMENT_URL="https://oapi.dingtalk.com/department/list?access_token=ACCESS_TOKEN&id=ID";
//2.获取部门详情
private static final String GET_DEPARTMENTDETAIL_URL="https://oapi.dingtalk.com/department/get?access_token=ACCESS_TOKEN&id=ID";
//3.创建部门
private static final String CREATE_DEPARTMENT_URL="https://oapi.dingtalk.com/department/create?access_token=ACCESS_TOKEN";
//4.更新部门
private static final String UPDATE_DEPARTMENT_URL="https://oapi.dingtalk.com/department/update?access_token=ACCESS_TOKEN";
//5.删除部门
private static final String DELETE_DEPARTMENT_URL="https://oapi.dingtalk.com/department/delete?access_token=ACCESS_TOKEN&id=ID";
//6.查询部门的所有上级父部门路径
private static final String LIST_PARENTDEPTS_BYDEPT_URL="https://oapi.dingtalk.com/department/list_parent_depts_by_dept?access_token=ACCESS_TOKEN&id=ID";
//7.查询指定用户的所有上级父部门路径
private static final String LIST_PARENTDEPTS_BYUSER_URL="https://oapi.dingtalk.com/department/list_parent_depts?access_token=ACCESS_TOKEN&userId=USERID"; /** 1.获取部门列表
* @desc :获取指定部门下的部门列表
*
* @param accessToken
* @param departementId 父部门id
* @return
* @throws Exception JSONObject
*/
public JSONObject listDepartment(String accessToken,String departmentId) throws Exception {
//1.准备请求url
String url=LIST_DEPARTMENT_URL.replace("ACCESS_TOKEN", accessToken).replace("ID", departmentId); //2.调用接口,发送请求
JSONObject jsonObject=HttpHelper.doGet(url);
System.out.println(jsonObject); //3.解析请求结果
if (null != jsonObject) {
//4.请求成功,则返回jsonObject
if (0==jsonObject.getInteger("errcode")) {
return jsonObject;
}
//5.错误消息处理
if (0 != jsonObject.getInteger("errcode")) {
int errCode = jsonObject.getInteger("errcode");
String errMsg = jsonObject.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
} return null;
} /** 2.获取部门详情
* @desc :
*
* @param accessToken
* @param departementId 部门id
* @return
* @throws Exception JSONObject
*/
public JSONObject getDepartmentDetail(String accessToken,String departmentId) throws Exception {
//1.准备请求url
String url=GET_DEPARTMENTDETAIL_URL.replace("ACCESS_TOKEN", accessToken).replace("ID", departmentId); //2.调用接口,发送请求
JSONObject jsonObject=HttpHelper.doGet(url);
System.out.println(jsonObject); //3.解析请求结果
if (null != jsonObject) {
//4.请求成功,则返回jsonObject
if (0==jsonObject.getInteger("errcode")) {
return jsonObject;
}
//5.错误消息处理
if (0 != jsonObject.getInteger("errcode")) {
int errCode = jsonObject.getInteger("errcode");
String errMsg = jsonObject.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
} return null;
} /** 3.创建部门
* @desc :
*
* @param accessToken
* @param department
* @return
* @throws Exception String
*/
public String createDepartment(String accessToken,Department department) throws Exception {
//1.准备POST请求参数
Object data=JSON.toJSON(department);
System.out.println(data); //2.获取请求url
String url=CREATE_DEPARTMENT_URL.replace("ACCESS_TOKEN", accessToken); //3.发起POST请求,获取返回结果
JSONObject jsonObject=HttpHelper.doPost(url, data);
System.out.println("jsonObject:"+jsonObject.toString()); //4.解析结果,获取UserId
String departmentId="";
if (null != jsonObject) {
departmentId=jsonObject.getString("id");
//5.错误消息处理
if (0 != jsonObject.getInteger("errcode")) {
int errCode = jsonObject.getInteger("errcode");
String errMsg = jsonObject.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
} return departmentId;
} /** 4.更新部门
* @desc :
*
* @param accessToken
* @param department 其中id是必须的
* @return
* @throws Exception String
*/
public void updateDepartment(String accessToken,Department department) throws Exception {
//1.准备POST请求参数
Object data=JSON.toJSON(department);
System.out.println(data); //2.获取请求url
String url=UPDATE_DEPARTMENT_URL.replace("ACCESS_TOKEN", accessToken); //3.发起POST请求,获取返回结果
JSONObject jsonObject=HttpHelper.doPost(url, data);
System.out.println("jsonObject:"+jsonObject.toString()); //4.解析结果
if (null != jsonObject) {
//5.错误消息处理
if (0 != jsonObject.getInteger("errcode")) {
int errCode = jsonObject.getInteger("errcode");
String errMsg = jsonObject.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
} } /**5.删除部门
* @desc :
*
* @param accessToken
* @param departmentId
* @throws Exception void
*/
public void deleteDepartment(String accessToken,String departmentId) throws Exception {
//1.准备请求url
String url=DELETE_DEPARTMENT_URL.replace("ACCESS_TOKEN", accessToken).replace("ID", departmentId); //2.调用接口,发送请求
JSONObject jsonObject=HttpHelper.doGet(url);
System.out.println(jsonObject); //3.解析请求结果
if (null != jsonObject) { //5.错误消息处理
if (0 != jsonObject.getInteger("errcode")) {
int errCode = jsonObject.getInteger("errcode");
String errMsg = jsonObject.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
} } /** 6.查询部门的所有上级父部门路径
* @desc :
* 返回的结果按顺序依次为其所有父部门的ID,直到根部门
* @param accessToken
* @param departementId 部门id
* @return
* @throws Exception JSONObject
*/
public JSONObject listParentDepartementsByDept(String accessToken,String departmentId) throws Exception {
//1.准备请求url
String url=LIST_PARENTDEPTS_BYDEPT_URL.replace("ACCESS_TOKEN", accessToken).replace("ID", departmentId); //2.调用接口,发送请求
JSONObject jsonObject=HttpHelper.doGet(url);
System.out.println(jsonObject); //3.解析请求结果
if (null != jsonObject) {
//4.请求成功,则返回jsonObject
if (0==jsonObject.getInteger("errcode")) {
return jsonObject;
}
//5.错误消息处理
if (0 != jsonObject.getInteger("errcode")) {
int errCode = jsonObject.getInteger("errcode");
String errMsg = jsonObject.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
} return null;
} /** 7.查询指定用户的所有上级父部门路径
* @desc :
* 返回的结果按顺序依次为其所有父部门的ID,直到根部门
* @param accessToken
* @param departementId 部门id
* @return
* @throws Exception JSONObject
*/
public JSONObject listParentDepartementsByUser(String accessToken,String userID) throws Exception {
//1.准备请求url
String url=LIST_PARENTDEPTS_BYUSER_URL.replace("ACCESS_TOKEN", accessToken).replace("USERID", userID); //2.调用接口,发送请求
JSONObject jsonObject=HttpHelper.doGet(url);
System.out.println(jsonObject); //3.解析请求结果
if (null != jsonObject) {
//4.请求成功,则返回jsonObject
if (0==jsonObject.getInteger("errcode")) {
return jsonObject;
}
//5.错误消息处理
if (0 != jsonObject.getInteger("errcode")) {
int errCode = jsonObject.getInteger("errcode");
String errMsg = jsonObject.getString("errmsg");
throw new Exception("error code:"+errCode+", error message:"+errMsg);
}
} return null;
} }

7.成员管理测试类—UserServiceTest

package com.ray.dingtalk.qy.service.contact;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.junit.Test; import com.ray.dingtalk.qy.auth.AuthHelper;
import com.ray.dingtalk.qy.config.Env;
import com.ray.dingtalk.qy.model.contact.User; /**@desc : 成员管理测试类
*
* @author: shirayner
* @date : 2017年9月28日 上午10:09:34
*/
public class UserServiceTest { /**
* @desc :1.获取成员
*
* @throws Exception void
*/
@Test
public void testGetUser() throws Exception {
String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
String userId="manager6777"; UserService us=new UserService();
us.getUser(accessToken, userId); } /**
* @desc :2.创建成员
*
* @throws Exception void
*/
@Test
public void testCreateUser() throws Exception {
String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET); User user=new User();
user.setName("测试2"); //王子明
List<Long> departmentList=new ArrayList<Long>();
departmentList.add(new Long(53191107));
user.setDepartment(departmentList);
user.setUserid("ceishi2");;
user.setMobile("18771419624"); // UserService us=new UserService();
String userId=us.createUser(accessToken, user);
System.out.println("userId:"+userId); } /** 3.更新成员
* @desc :参数说明(如果非必须的字段未指定,则钉钉后台不改变该字段之前设置好的值)
*
* @throws Exception void
*/
@Test
public void testUpdateUser() throws Exception {
String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET); User user=new User();
user.setName("测试专用");
List<Long> departmentList=new ArrayList<Long>();
departmentList.add(new Long(1));
user.setDepartment(departmentList);
user.setMobile("13764363757");
user.setUserid("142322032127997575");
user.setPosition("网管"); UserService us=new UserService();
us.updateUser(accessToken, user); }
/** 4.删除成员
* @desc :
*
* @throws Exception void
*/
@Test
public void testDeleteUser() throws Exception {
String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
String userId="142322032127997575"; UserService us=new UserService();
us.deleteUser(accessToken, userId); } /** 5.批量删除成员
* @desc :
*
* @throws Exception void
*/
@Test
public void testBatchDeleteUser() throws Exception {
String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET); //1.1为构造JSon做准备:["ceishi1","ceishi2"]
List<String> userIdlist=new ArrayList<String>();
userIdlist.add("ceishi1");
userIdlist.add("ceishi2"); //1.2为构造JSon做准备:{"useridlist":["ceishi1","ceishi2"]}
Map< String , List<String> > userIdListMap=new HashMap< String, List<String> >();
userIdListMap.put("useridlist", userIdlist); UserService us=new UserService();
us.batchDeleteUser(accessToken, userIdListMap); } /** 6.获取部门成员(simplelist)
* @desc :
*
* @throws Exception void
*/
@Test
public void testListDepartmentUser() throws Exception {
String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
String departmentId="1"; UserService us=new UserService();
us.listDepartmentUser(accessToken, departmentId); } /** 7.获取部门成员(详情)
* @desc :
*
* @throws Exception void
*/
@Test
public void testListDepartmentUserDetail() throws Exception {
String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
String departmentId="1"; UserService us=new UserService();
us.listDepartmentUserDetail(accessToken, departmentId); } /** 8.获取管理员列表
* @desc :
*
* @throws Exception void
*/
@Test
public void testListAdmin() throws Exception {
String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET); UserService us=new UserService();
us.listAdmin(accessToken); } }

8.部门管理测试类—DepartmentServcieTest

package com.ray.dingtalk.qy.service.contact;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test; import com.alibaba.fastjson.JSONObject;
import com.ray.dingtalk.qy.auth.AuthHelper;
import com.ray.dingtalk.qy.config.Env;
import com.ray.dingtalk.qy.model.contact.Department; /**@desc : 部门管理测试类
*
* @author: shirayner
* @date : 2017年10月18日 下午1:31:32
*/
public class DepartmentServcieTest {
private static final Logger log = LogManager.getLogger(DepartmentServcieTest.class); /** 1.获取部门列表
* @throws Exception
* @desc :
* void
*/
@Test
public void testListDepartement() throws Exception {
String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
String departmentId="1";
DepartmentServcie departmentServcie= new DepartmentServcie();
JSONObject jsonObject=departmentServcie.listDepartment(accessToken, departmentId);
log.info(jsonObject); } /** 2.获取部门详情
* @throws Exception
* @desc :
* void
*/
@Test
public void testGetDepartementDetail() throws Exception {
String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
String departmentId="1";
DepartmentServcie departmentServcie= new DepartmentServcie();
JSONObject jsonObject=departmentServcie.getDepartmentDetail(accessToken, departmentId);
log.info(jsonObject); } /** 3.创建部门
* @throws Exception
* @desc :
* void
*/
@Test
public void testCreateDepartment() throws Exception {
String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET);
Department department =new Department();
department.setName("HEC北京分公司");
department.setParentid("1"); DepartmentServcie departmentServcie= new DepartmentServcie();
String departmentId=departmentServcie.createDepartment(accessToken, department);
log.info(departmentId); } /** 4.更新部门
*
* @throws Exception
* @desc :
* void
*/
@Test
public void testUpdateDepartment() throws Exception {
String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET); Department department =new Department();
department.setName("HEC大汉分公司");
department.setId(53125124); DepartmentServcie departmentServcie= new DepartmentServcie();
departmentServcie.updateDepartment(accessToken, department); } /** 5.删除部门
* @throws Exception
* @desc :
* void
*/
@Test
public void testDeleteDepartement() throws Exception {
String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET); String departmentId="53181144"; DepartmentServcie departmentServcie= new DepartmentServcie();
departmentServcie.deleteDepartment(accessToken, departmentId); } /** 6.查询部门的所有上级父部门路径
* @throws Exception
* @desc :
* void
*/
@Test
public void testListParentDepartementsByDept() throws Exception {
String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET); String departmentId="53191107"; DepartmentServcie departmentServcie= new DepartmentServcie();
JSONObject jsonObject=departmentServcie.listParentDepartementsByDept(accessToken, departmentId);
log.info(jsonObject.get("parentIds")); } /** 7.查询指定用户的所有上级父部门路径
* @throws Exception
* @desc :
* void
*/
@Test
public void testListParentDepartementsByUser() throws Exception {
String accessToken=AuthHelper.getAccessToken(Env.CORP_ID, Env.CORP_SECRET); String userID="ceishi2"; DepartmentServcie departmentServcie= new DepartmentServcie();
JSONObject jsonObject=departmentServcie.listParentDepartementsByUser(accessToken, userID);
log.info(jsonObject.get("department")); } }

Java钉钉开发_03_通讯录管理之 人员管理 和 部门管理的更多相关文章

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

    一.本节要点 1.获取通讯录密钥 获取方式: 登录企业微信—>管理工具—>通讯录同步助手—>开启“API接口同步”  ; 开启后,即可看到通讯录密钥,也可设置通讯录API的权限:读取 ...

  2. Java企业微信开发_03_自定义菜单

    一.本节要点 1.菜单相关实体类的封装 参考官方文档中的请求包的内容,对菜单相关实体类进行封装. 这里需要格外注意的是,企业微信中请求包的数据是Json字符串格式的,而不是xml格式.关于json序列 ...

  3. Java企业微信开发_02_通讯录同步

    一.本节要点 1.获取通讯录密钥 获取方式: 登录企业微信—>管理工具—>通讯录同步助手—>开启“API接口同步”  ; 开启后,即可看到通讯录密钥,也可设置通讯录API的权限:读取 ...

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

    注: 源码已上传github: https://github.com/shirayner/WeiXin_QiYe_Demo 一.本节要点 1.1 授权回调域(可信域名) 在开始使用网页授权之前,需要先 ...

  5. Java钉钉开发_01_开发前的准备

    源码已上传GitHub:传送门 一.准备事项 1.1  一个能在公网上访问的项目: 参见:Java微信开发_02_本地服务器映射外网 1.2  一个钉钉账号 去注册 1.3 创建一个应用 登录钉钉后台 ...

  6. Java钉钉开发_02_免登授权(身份验证)(附源码)

    源码已上传GitHub: https://github.com/shirayner/DingTalk_Demo 一.本节要点 1.免登授权的流程 (1)签名校验 (2)获取code,并传到后台 (3) ...

  7. java钉钉通讯录同步

    钉钉做了好好几个项目了,和阿里云还有阿里钉钉合作也挺不错.因为之前就做过微信公众号,接触钉钉感觉还是比较顺手的,虽然也有一些不一样的地方. 因为之前写了一个微信公众号的开发文档,一直想写一个钉钉的开发 ...

  8. Java钉钉开发_02_免登授权(身份验证)

    源码已上传GitHub: https://github.com/shirayner/DingTalk_Demo 一.本节要点 1.免登授权的流程 (1)签名校验 (2)获取code,并传到后台 (3) ...

  9. Java钉钉开发_00_资源帖

    1.源码 本系列教程的源码已上传至GitHub:  https://github.com/shirayner/DingTalk_Demo 2.官方 官方源码:https://github.com/op ...

随机推荐

  1. css 浮动和清除浮动

    在写页面布局的过程中,浮动是大家经常用的属性.在好多的排版布局中都是用的的浮动比如说下面这些地方都是应用到了浮动. 在我学习浮动的时候可是熬坏了脑筋,在这里我分享一下我对浮动这块知识的总结. 一.浮动 ...

  2. MVC3/4/5/6 布局页及Razor语法及Route路由配置

    一.目录结构 二.Razor语法 代码块:@{},如:@{Html.Raw(“”);} @if(){} @switch(){} @for(){} @foreach(){} @while(){} @do ...

  3. 即时通信系统Openfire分析之五:会话管理

    什么是会话? A拨了B的电话 电话接通 A问道:Are you OK? B回复:I have a bug! A挂了电话 这整个过程就是会话. 会话(Session)是一个客户与服务器之间的不中断的请求 ...

  4. python之HTMLParser解析HTML文档

    HTMLParser是Python自带的模块,使用简单,能够很容易的实现HTML文件的分析.本文主要简单讲一下HTMLParser的用法. 使用时需要定义一个从类HTMLParser继承的类,重定义函 ...

  5. Sql Server 数据库中调用dll文件

    1.首先新建一个空的解决方案,并添加一个类库,代码如下,编译并生产dll using System; using System.Collections.Generic; using System.Da ...

  6. Collection和Map的默认扩容参数

    初始大小:调用无参构造函数时默认的容量 加载因子:超过 (当前容量*加载因子) 时会进行扩容 扩容因子:扩容时增加的容量为 (当前容量*扩容因子)        容器         初始容量    ...

  7. 修改Oracle【12C】字符集

    select userenv('language') from dual; //查看系统字符集编码 select * from nls_database_parameters where parame ...

  8. bootstrap 鼠标悬停显示

    1. <button type="button" rel="drevil" data-content="报名截止时间:'+time+'" ...

  9. Yii2之事件

    众所周知,yii的三大特性是:属性.事件.行为,上一篇博文简单讲解了yii中的属性,本文接着讲讲yii的事件. 事件是代码解耦的一种方式,设计业务流程的一种模式.在yii2.0中,通过Yii\base ...

  10. LeetCode 205. Isomorphic Strings (同构字符串)

    Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the chara ...