Commit bde49f53 authored by shenjunlin's avatar shenjunlin

Initial commit

parents
/src/main/java/com/dingHelper/MainTest.java
/dingHelper.iml
/.idea
### Java template
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
# Created by .ignore support plugin (hsz.mobi)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.com.duiba.shark</groupId>
<artifactId>dingHelper</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>dingHelper</name>
<dependencies>
<!--钉钉ISV需要jar-->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.3.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.6</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!---->
<!--JSON-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</version>
</dependency>
<!---->
</dependencies>
<build>
<finalName>dingHelper</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<includes>
<include>**/*Tests.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.dingHelper;
/**
* 静态常量
* Created by Saber on 16/8/24.
*/
public class Contant {
/**
* 钉钉网关
*/
public static final String OAPI_HOST = "https://oapi.dingtalk.com";
/**
* 创建微应用
*/
public static final String MICRO_APP_CREATE_HOST =OAPI_HOST+"/microapp/create?access_token=";
/**
* 获取企业设置的微应用可见范围
*/
public static final String MICRO_APP_VISIBLE_SCOPES_HOST =OAPI_HOST+"/microapp/visible_scopes?access_token=";
/**
* 设置微应用的可见范围
*/
public static final String MICRO_APP_SET_VISIBLE_SCOPES_HOST =OAPI_HOST+"/microapp/set_visible_scopes?access_token=";
}
package com.dingHelper;
public class Env {
public static final String OAPI_HOST = "https://oapi.dingtalk.com";
public static final String OA_BACKGROUND_URL = "";
public static String suiteTicket;
public static String authCode;
public static String suiteToken;
}
package com.dingHelper;
public class OApiException extends Exception {
public OApiException(int errCode, String errMsg) {
super("error code: " + errCode + ", error message: " + errMsg);
}
}
package com.dingHelper;
public class OApiResultException extends OApiException {
public static final int ERR_RESULT_RESOLUTION = -2;
public OApiResultException(String field) {
super(ERR_RESULT_RESOLUTION, "Cannot resolve field " + field + " from oapi resonpse");
}
}
package com.dingHelper;
import java.io.Serializable;
/**
* 基础的响应码
* Created by Saber on 16/8/24.
*/
public class ResultCode implements Serializable{
private static final long serialVersionUID = 3312006345445716275L;
/**
* 返回码
*/
private int errcode;
/**
* 对返回码的文本描述内容
*/
private String errmsg;
public int getErrcode() {
return errcode;
}
public void setErrcode(int errcode) {
this.errcode = errcode;
}
public String getErrmsg() {
return errmsg;
}
public void setErrmsg(String errmsg) {
this.errmsg = errmsg;
}
@Override
public String toString() {
return "ResultCode{" +
"errcode=" + errcode +
", errmsg='" + errmsg + '\'' +
'}';
}
}
package com.dingHelper.agent;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dingHelper.Contant;
import com.dingHelper.OApiException;
import com.dingHelper.ResultCode;
import com.dingHelper.agent.request.AgentRequest;
import com.dingHelper.agent.request.SetVisibleScopesReq;
import com.dingHelper.agent.response.AgentResponse;
import com.dingHelper.agent.response.VisibleScopesRep;
import com.dingHelper.utils.HttpHelper;
/**
* 操作微应用相关
* Created by Saber on 16/8/24.
*/
public class AgentHelper {
/**
* 创建微应用
* @param accessToken accessToken
* @param createReq 请求包结构体
* @return
*/
public static AgentResponse createAgent(String accessToken, AgentRequest createReq) throws OApiException {
AgentResponse createRep = null;
String url = Contant.MICRO_APP_CREATE_HOST + accessToken;
JSONObject resultJSON = HttpHelper.httpPost(url, JSON.toJSON(createReq));
createRep = JSON.parseObject(resultJSON.toString(), AgentResponse.class);
return createRep;
}
/**
* 获取企业设置的微应用可见范围
* @param accessToken accessToken
* @param agentId 微应用id
* @return
*/
public static VisibleScopesRep getVisibleScopesRep(String accessToken,Long agentId) throws OApiException {
VisibleScopesRep visibleScopesRep =null;
String url = Contant.MICRO_APP_VISIBLE_SCOPES_HOST + accessToken;
JSONObject param = new JSONObject();
param.put("agentId",agentId);
JSONObject resultJSON = HttpHelper.httpPost(url, JSON.toJSON(param));
visibleScopesRep = JSON.parseObject(resultJSON.toString(), VisibleScopesRep.class);
return visibleScopesRep;
}
/**
* 设置微应用的可见范围
* @param accessToken accessToken
* @param setVisibleScopesReq 请求包结构体
* @return
*/
public static ResultCode setVisibleScopes(String accessToken,SetVisibleScopesReq setVisibleScopesReq) throws OApiException {
ResultCode resultCode = null;
String url = Contant.MICRO_APP_SET_VISIBLE_SCOPES_HOST + accessToken;
JSONObject resultJSON = HttpHelper.httpPost(url, JSON.toJSON(setVisibleScopesReq));
resultCode = JSON.parseObject(resultJSON.toString(), ResultCode.class);
return resultCode;
}
}
package com.dingHelper.agent.request;
/**
* 创建微应用 请求体
* Created by Saber on 16/8/24.
*/
public class AgentRequest {
/**
* 微应用的图标。需要调用上传接口将图标上传到钉钉服务器后获取到的mediaId<br/>
* 必须: 是
*/
private String appIcon;
/**
* 微应用的名称。长度限制为1~10个字符
* 必须: 是
*/
private String appName;
/**
* 微应用的描述。长度限制为1~20个字符
* 必须: 是
*/
private String appDesc;
/**
* 微应用的移动端主页,必须以http开头或https开头
* 必须: 是
*/
private String homepageUrl;
/**
* 微应用的PC端主页,必须以http开头或https开头,如果不为空则必须与homepageUrl的域名一致
* 必须: 否
*/
private String pcHomepageUrl;
/**
* 微应用的OA后台管理主页,必须以http开头或https开头
* 必须:
*/
private String ompLink;
//无参构造方法
public AgentRequest() {
}
/**
* 必须的参数
* @param appIcon 微应用的图标
* @param appName 微应用的名称
* @param appDesc 微应用的描述
* @param homepageUrl 微应用的移动端主页
*/
public AgentRequest(String appIcon, String appName, String appDesc, String homepageUrl) {
this.appIcon = appIcon;
this.appName = appName;
this.appDesc = appDesc;
this.homepageUrl = homepageUrl;
}
//----------------------------------------------------------
public String getAppIcon() {
return appIcon;
}
public void setAppIcon(String appIcon) {
this.appIcon = appIcon;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getAppDesc() {
return appDesc;
}
public void setAppDesc(String appDesc) {
this.appDesc = appDesc;
}
public String getHomepageUrl() {
return homepageUrl;
}
public void setHomepageUrl(String homepageUrl) {
this.homepageUrl = homepageUrl;
}
public String getPcHomepageUrl() {
return pcHomepageUrl;
}
public void setPcHomepageUrl(String pcHomepageUrl) {
this.pcHomepageUrl = pcHomepageUrl;
}
public String getOmpLink() {
return ompLink;
}
public void setOmpLink(String ompLink) {
this.ompLink = ompLink;
}
@Override
public String toString() {
return "AgentCreate{" +
"appIcon='" + appIcon + '\'' +
", appName='" + appName + '\'' +
", appDesc='" + appDesc + '\'' +
", homepageUrl='" + homepageUrl + '\'' +
", pcHomepageUrl='" + pcHomepageUrl + '\'' +
", ompLink='" + ompLink + '\'' +
'}';
}
}
package com.dingHelper.agent.request;
import com.dingHelper.OApiException;
import com.dingHelper.agent.AgentHelper;
import com.dingHelper.agent.response.AgentResponse;
import com.dingHelper.auth.AuthHelper;
import com.dingHelper.media.MediaHelper;
import java.io.File;
/**
* Created by Saber on 2016/12/23.
*/
public class MainTest {
/********
* 测试企业 yfl1 Aptx4869
************/
public static final String CORP_ID = "ding909520c640789245";
public static final String SECRET = "LIlSU6DCjWMUA4ZQXrfHTA8-xxxDzHvtWn4L_ZDbMChquzTCOCl0lAd_qZN8HMOM";
public static final String SSO_Secret = "TMPGk5kaRxtrLtgiLP9CvQlmywYAWfN45x0pi9IFO9WvrFwgnGAYiKImcfaI8Asi";
public static void main(String[] args) throws OApiException {
//获取accessToken
String accessToken = AuthHelper.getAccessToken(CORP_ID, SECRET);
System.err.println("accessToken=" + accessToken);
//获取ticket
String ticket = AuthHelper.getJsapiTicket(accessToken);
System.err.println("ticket = " + ticket);
//上传微应用图标并获取图标地址
String appIconPath = System.getProperty("user.dir") + File.separatorChar + "appIcon.png";
File appIconFile = new File(appIconPath);
MediaHelper.MediaUploadResult mediaUploadResult = MediaHelper.upload(accessToken, MediaHelper.TYPE_IMAGE, appIconFile);
String appIconMediaId = mediaUploadResult.media_id;
System.err.println("logo 上传后的id " + appIconMediaId);
//1.新增微应用
AgentRequest agentRequest = new AgentRequest();
agentRequest.setAppIcon(appIconMediaId);
agentRequest.setAppName("测试应用");
agentRequest.setAppDesc("测试使用 随便写点什么...");
agentRequest.setHomepageUrl("http://www.baidu.com");
AgentResponse addAgentResponse = AgentHelper.createAgent(accessToken, agentRequest);
System.err.println("新增微应用结果 " + addAgentResponse.toString());
}
}
package com.dingHelper.agent.request;
import java.util.Arrays;
/**
* 设置微应用的可见范围 请求体
* Created by Saber on 16/8/24.
*/
public class SetVisibleScopesReq {
/**
* 微应用agentId <br/>
* 必须: 是
*/
private Long agentId;
/**
* 是否仅限管理员可见,true代表仅限管理员可见
* 必须: 否
*/
private Boolean isHidden;
/**
* 设置可见的部门id列表,格式为JSON数组
* 必须: 否
*/
private String[] deptVisibleScopes;
/**
* 设置可见的员工id列表,格式为JSON数组
* 必须: 否
*/
private String[] userVisibleScopes;
//无参构造方法
public SetVisibleScopesReq() {
}
/**
* 必须的参数
* @param agentId 微应用agentId
*/
public SetVisibleScopesReq(Long agentId) {
this.agentId = agentId;
}
//-------------------------------------------------------------
public Long getAgentId() {
return agentId;
}
public void setAgentId(Long agentId) {
this.agentId = agentId;
}
public Boolean getIsHidden() {
return isHidden;
}
public void setIsHidden(Boolean isHidden) {
this.isHidden = isHidden;
}
public String[] getDeptVisibleScopes() {
return deptVisibleScopes;
}
public void setDeptVisibleScopes(String[] deptVisibleScopes) {
this.deptVisibleScopes = deptVisibleScopes;
}
public String[] getUserVisibleScopes() {
return userVisibleScopes;
}
public void setUserVisibleScopes(String[] userVisibleScopes) {
this.userVisibleScopes = userVisibleScopes;
}
@Override
public String toString() {
return "SetVisibleScopesReq{" +
"agentId=" + agentId +
", isHidden=" + isHidden +
", deptVisibleScopes=" + Arrays.toString(deptVisibleScopes) +
", userVisibleScopes=" + Arrays.toString(userVisibleScopes) +
'}';
}
}
package com.dingHelper.agent.response;
import com.dingHelper.ResultCode;
/**
* 创建微应用 响应体
* Created by Saber on 16/8/24.
*/
public class AgentResponse extends ResultCode {
/**
* 创建的微应用id
*/
private Long agentid;
public Long getAgentid() {
return agentid;
}
public void setAgentid(Long agentid) {
this.agentid = agentid;
}
@Override
public String toString() {
return "AgentResponse{" +
"agentid=" + agentid +
"} " + super.toString();
}
}
package com.dingHelper.agent.response;
import com.dingHelper.ResultCode;
import java.util.Arrays;
/**
* 获取微应用可见范围返回 响应体
* Created by Saber on 16/8/24.
*/
public class VisibleScopesRep extends ResultCode{
/**
* 是否仅限管理员可见
*/
private boolean isHidden;
/**
* 微应用的可见部门id列表,格式为JSON数组
*/
private long[] deptVisibleScopes;
/**
* 微应用的可见用户id列表,格式为JSON数组
*/
private long[] userVisibleScopes;
//-----------------------------------------------------------------------
public boolean isHidden() {
return isHidden;
}
public void setIsHidden(boolean isHidden) {
this.isHidden = isHidden;
}
public long[] getDeptVisibleScopes() {
return deptVisibleScopes;
}
public void setDeptVisibleScopes(long[] deptVisibleScopes) {
this.deptVisibleScopes = deptVisibleScopes;
}
public long[] getUserVisibleScopes() {
return userVisibleScopes;
}
public void setUserVisibleScopes(long[] userVisibleScopes) {
this.userVisibleScopes = userVisibleScopes;
}
@Override
public String toString() {
return "VisibleScopesRep{" +
"isHidden=" + isHidden +
", deptVisibleScopes=" + Arrays.toString(deptVisibleScopes) +
", userVisibleScopes=" + Arrays.toString(userVisibleScopes) +
"} " + super.toString();
}
}
package com.dingHelper.auth;
import com.alibaba.fastjson.JSONObject;
import com.dingHelper.Env;
import com.dingHelper.OApiException;
import com.dingHelper.OApiResultException;
import com.dingHelper.utils.HttpHelper;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.Timer;
public class AuthHelper {
public static String jsapiTicket = null;
public static String accessToken = null;
public static Timer timer = null;
public static final Integer cacheTime = 1000 * 60 * 60 * 2;
public static long currentTime = 0 + cacheTime + 1;
public static long lastTime = 0;
/**
* 获取 accessToken
* @param corpId corpId
* @param corpSecret corpSecret
* @return
* @throws OApiException
*/
public static String getAccessToken(String corpId,String corpSecret) throws OApiException {
if (lastTime != 0) {
currentTime = System.currentTimeMillis();
}
if (currentTime - lastTime >= cacheTime) {
String url = Env.OAPI_HOST + "/gettoken?" + "corpid=" + corpId + "&corpsecret=" + corpSecret;
JSONObject response = HttpHelper.httpGet(url);
if (response.containsKey("access_token")) {
accessToken = response.getString("access_token");
} else {
throw new OApiResultException("access_token");
}
String url_ticket = Env.OAPI_HOST + "/get_jsapi_ticket?" + "type=jsapi" + "&access_token=" + accessToken;
JSONObject response_ticket = HttpHelper.httpGet(url_ticket);
if (response_ticket.containsKey("ticket")) {
jsapiTicket = response_ticket.getString("ticket");
currentTime = System.currentTimeMillis();
lastTime = System.currentTimeMillis();
} else {
throw new OApiResultException("ticket");
}
} else {
return accessToken;
}
return accessToken;
}
/**
* 获取 ticket
* 正常的情况下,jsapi_ticket的有效期为7200秒,所以开发者需要在某个地方设计一个定时器,定期去更新jsapi_ticket
* @param accessToken accessToken
* @return
* @throws OApiException
*/
public static String getJsapiTicket(String accessToken) throws OApiException {
if (jsapiTicket == null) {
String url = Env.OAPI_HOST + "/get_jsapi_ticket?" + "type=jsapi" + "&access_token=" + accessToken;
JSONObject response = HttpHelper.httpGet(url);
if (response.containsKey("ticket")) {
jsapiTicket = response.getString("ticket");
return jsapiTicket;
} else {
throw new OApiResultException("ticket");
}
} else {
return jsapiTicket;
}
}
public static String sign(String ticket, String nonceStr, long timeStamp, String url)
throws OApiException {
String plain = "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "&timestamp=" + String.valueOf(timeStamp) + "&url=" + url;
try {
MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
sha1.reset();
sha1.update(plain.getBytes("UTF-8"));
return bytesToHex(sha1.digest());
} catch (NoSuchAlgorithmException e) {
throw new OApiResultException(e.getMessage());
} catch (UnsupportedEncodingException e) {
throw new OApiResultException(e.getMessage());
}
}
private static String bytesToHex(byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash) {
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
/**
* 获取 config配置信息(页面JSAPI使用)
* @param urlString
* @param queryString
* @param corpId corpId
* @param corpSecret corpSecret
* @return
*/
public static String getConfig(String urlString, String queryString,String corpId,String corpSecret) {
String queryStringEncode = null;
String url;
if (queryString != null) {
queryStringEncode = URLDecoder.decode(queryString);
url = urlString + "?" + queryStringEncode;
} else {
url = urlString;
}
// System.out.println(url);
String nonceStr = "abcdefg";
long timeStamp = System.currentTimeMillis() / 1000;
String signedUrl = url;
String accessToken = null;
String ticket = null;
String signature = null;
try {
accessToken = AuthHelper.getAccessToken(corpId,corpSecret);
ticket = AuthHelper.getJsapiTicket(accessToken);
signature = AuthHelper.sign(ticket, nonceStr, timeStamp, signedUrl);
} catch (OApiException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "{jsticket:'" + ticket + "',signature:'" + signature + "',nonceStr:'" + nonceStr + "',timeStamp:'" + timeStamp + "',corpId:'" + corpId + "'}";
}
/**
* 获取SSoToken
* @param corpId corpId
* @param ssoSecret ssoSecret
* @return
* @throws OApiException
*/
public static String getSsoToken(String corpId,String ssoSecret) throws OApiException {
String url = "https://oapi.dingtalk.com/sso/gettoken?corpid=" + corpId + "&corpsecret=" + ssoSecret;
JSONObject response = HttpHelper.httpGet(url);
String ssoToken;
if (response.containsKey("access_token")) {
ssoToken = response.getString("access_token");
} else {
throw new OApiResultException("Sso_token");
}
return ssoToken;
}
}
package com.dingHelper.department;
/**
* {
* "errcode": 0,
* "errmsg": "ok",
* "id": 2,
* "name": "钉钉事业部",
* "order" : 10,
* "parentid": 1,
* "createDeptGroup": true,
* "autoAddUser": true,
* "deptHiding" : true,
* "deptPerimits" : "3|4",
* "userPerimits" : "userid1|userid2",
* "outerDept" : true,
* "outerPermitDepts" : "1|2",
* "outerPermitUsers" : "userid3|userid4",
* "orgDeptOwner" : "manager1122",
* "deptManagerUseridList" : "manager1122|manager3211"
* }
*/
public class Department {
private Long id; //部门id
private String name; //部门名称
private Long parentid; //父部门id,根部门id为1
private Integer order; //在父部门中的次序值
private Boolean createDeptGroup; //是否同步创建一个关联此部门的企业群, true表示是, false表示不是
private Boolean autoAddUser;//当群已经创建后,是否有新人加入部门会自动加入该群, true表示是, false表示不是
private Boolean deptHiding;//是否隐藏部门, true表示隐藏, false表示显示
private String deptPerimits;//可以查看指定隐藏部门的其他部门列表,如果部门隐藏,则此值生效,取值为其他的部门id组成的的字符串,使用|符号进行分割
private String userPerimits;//可以查看指定隐藏部门的其他人员列表,如果部门隐藏,则此值生效,取值为其他的人员userid组成的的字符串,使用|符号进行分割
private Boolean outerDept;//是否本部门的员工仅可见员工自己, 为true时,本部门员工默认只能看到员工自己
private String outerPermitDepts;//本部门的员工仅可见员工自己为true时,可以配置额外可见部门,值为部门id组成的的字符串,使用|符号进行分割
private String outerPermitUsers;//本部门的员工仅可见员工自己为true时,可以配置额外可见人员,值为userid组成的的字符串,使用| 符号进行分割
private String orgDeptOwner;//企业群群主
private String deptManagerUseridList;//部门的主管列表,取值为由主管的userid组成的字符串,不同的userid使用|符号进行分割
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getParentid() {
return parentid;
}
public void setParentid(Long parentid) {
this.parentid = parentid;
}
public Integer getOrder() {
return order;
}
public void setOrder(Integer order) {
this.order = order;
}
public Boolean getCreateDeptGroup() {
return createDeptGroup;
}
public void setCreateDeptGroup(Boolean createDeptGroup) {
this.createDeptGroup = createDeptGroup;
}
public Boolean getAutoAddUser() {
return autoAddUser;
}
public void setAutoAddUser(Boolean autoAddUser) {
this.autoAddUser = autoAddUser;
}
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 String getOrgDeptOwner() {
return orgDeptOwner;
}
public void setOrgDeptOwner(String orgDeptOwner) {
this.orgDeptOwner = orgDeptOwner;
}
public String getDeptManagerUseridList() {
return deptManagerUseridList;
}
public void setDeptManagerUseridList(String deptManagerUseridList) {
this.deptManagerUseridList = deptManagerUseridList;
}
@Override
public String toString() {
return "Department{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", parentid='" + parentid + '\'' +
", order=" + order +
", createDeptGroup=" + createDeptGroup +
", autoAddUser=" + autoAddUser +
", deptHiding=" + deptHiding +
", deptPerimits='" + deptPerimits + '\'' +
", userPerimits='" + userPerimits + '\'' +
", outerDept=" + outerDept +
", outerPermitDepts='" + outerPermitDepts + '\'' +
", outerPermitUsers='" + outerPermitUsers + '\'' +
", orgDeptOwner='" + orgDeptOwner + '\'' +
", deptManagerUseridList='" + deptManagerUseridList + '\'' +
'}';
}
}
package com.dingHelper.department;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingHelper.Env;
import com.dingHelper.OApiException;
import com.dingHelper.OApiResultException;
import com.dingHelper.ResultCode;
import com.dingHelper.utils.HttpHelper;
import java.util.ArrayList;
import java.util.List;
/**
* 部门管理工具类
*/
public class DepartmentHelper {
/**
* 创建部门
* @Author Saber
* @Date 2016/12/24 上午10:49
* @param accessToken accessToken
* @param name 部门名称
* @param parentId 上级部门id
* @param order 排序
* @param createDeptGroup 是否同步创建一个关联此部门的企业群, true表示是, false表示不是
* @return 创建的部门id
* @throws OApiException
*/
public static long createDepartment(String accessToken, String name, String parentId, String order, boolean createDeptGroup ) throws OApiException {
String url = Env.OAPI_HOST + "/department/create?" + "access_token=" + accessToken;
JSONObject args = new JSONObject();
args.put("name", name);
args.put("parentid", parentId);
args.put("order", order);
args.put("createDeptGroup", createDeptGroup);
JSONObject response = HttpHelper.httpPost(url, args);
if (response.containsKey("id")) {
return response.getLong("id");
}
else {
throw new OApiResultException("id");
}
}
/**
* 创建部门
* @Author Saber
* @Date 2016/12/23 下午4:37
* @param accessToken accessToken
* @param department 参数(id为空)
* @return 部门id
* @throws OApiException
*/
public static Long createDepartment(String accessToken, Department department) throws OApiException {
String url = Env.OAPI_HOST + "/department/create?" + "access_token=" + accessToken;
department.setId(null);
JSONObject response = HttpHelper.httpPost(url, JSONObject.toJSON(department));
if (response.containsKey("id")) {
return response.getLong("id");
} else {
throw new OApiResultException("id");
}
}
/**
* 创建部门前先查询部门是否存在
*
* @param accessToken accessToken
* @param department 参数(id为空)
* @return
* @throws OApiException
* @Author Saber
* @Date 2016/12/24 上午10:49
*/
public static Long createDepartmentWithCheck(String accessToken, Department department) throws OApiException {
/**
* 遍历所有部门查找重名部门
*/
List<Department> departmentList = DepartmentHelper.listDepartments(accessToken);
for (Department dept : departmentList) {
if (dept.equals(department.getName())) {
throw new OApiResultException("此部门已存在");
}
}
//新增
String url = Env.OAPI_HOST + "/department/create?" + "access_token=" + accessToken;
department.setId(null);
JSONObject response = HttpHelper.httpPost(url, JSONObject.toJSON(department));
if (response.containsKey("id")) {
return response.getLong("id");
} else {
throw new OApiResultException("id");
}
}
/**
* 获取部门列表(ISV默认无调用权限)
* @Author Saber
* @Date 2016/12/24 上午10:50
* @param accessToken accessToken
* @return 部门列表
* @throws OApiException
*/
public static List<Department> listDepartments(String accessToken) throws OApiException {
String url = Env.OAPI_HOST + "/department/list?" + "access_token=" + accessToken;
JSONObject response = HttpHelper.httpGet(url);
if (response.containsKey("department")) {
JSONArray arr = response.getJSONArray("department");
List<Department> list = new ArrayList();
for (int i = 0; i < arr.size(); i++) {
list.add(arr.getObject(i, Department.class));
}
return list;
}
else {
throw new OApiResultException("department");
}
}
/**
* 获取部门详情
* @Author Saber
* @Date 2016/12/24 上午10:50
* @param accessToken accessToken
* @param id 部门id
* @return 部门详情
* @throws OApiException
*/
public static Department getDepartment(String accessToken, Long id) throws OApiException {
String url = Env.OAPI_HOST + "/department/get?" + "access_token=" + accessToken + "&id=" + id;
JSONObject json = HttpHelper.httpGet(url);
if (json.getInteger("errcode") == 0) {
Department department = JSON.toJavaObject(json, Department.class);
return department;
}
return null;
}
/**
* 删除部门 (ISV默认无调用权限)
* @Author Saber
* @Date 2016/12/24 上午10:51
* @param accessToken accessToken
* @param id 部门id
* @return resultCode
* @throws OApiException
*/
public static ResultCode deleteDepartment(String accessToken, Long id) throws OApiException{
String url = Env.OAPI_HOST + "/department/delete?" + "access_token=" + accessToken + "&id=" + id;
JSONObject result = HttpHelper.httpGet(url);
return JSON.parseObject(result.toJSONString(),ResultCode.class);
}
/**
* 更新部门
* @Author Saber
* @Date 2016/12/24 上午10:51
* @param accessToken accessToken
* @param name 名称
* @param parentId 父级部门id
* @param order 排序
* @param id 部门id
* @param autoAddUser 当群已经创建后,是否有新人加入部门会自动加入该群, true表示是, false表示不是
* @param deptManagerUseridList 部门的主管列表,取值为由主管的userid组成的字符串,不同的userid使用’| 符号进行分割
* @param deptHiding 是否隐藏部门, true表示隐藏, false表示显示
* @param deptPerimits 可以查看指定隐藏部门的其他部门列表,如果部门隐藏,则此值生效,取值为其他的部门id组成的的字符串,使用 | 符号进行分割
* @throws OApiException
*/
public static void updateDepartment(String accessToken, String name, String parentId, String order, long id, boolean autoAddUser, String deptManagerUseridList, boolean deptHiding, String deptPerimits) throws OApiException{
String url = Env.OAPI_HOST + "/department/update?" + "access_token=" + accessToken;
JSONObject args = new JSONObject();
args.put("name", name);
args.put("parentid", parentId);
args.put("order", order);
args.put("id",id);
args.put("autoAddUser",autoAddUser);
args.put("deptManagerUseridList",deptManagerUseridList);
args.put("deptHiding",deptHiding);
args.put("deptPerimits",deptPerimits);
HttpHelper.httpPost(url, args);
}
/**
* 更新部门
* @Author Saber
* @Date 2016/12/24 上午10:51
* @param accessToken accessToken
* @param department 参数
* @return resultCode
* @throws OApiException
*/
public static ResultCode updateDepartment(String accessToken, Department department) throws OApiException {
String url = Env.OAPI_HOST + "/department/update?" + "access_token=" + accessToken;
JSONObject result = HttpHelper.httpPost(url, JSONObject.toJSON(department));
return JSON.parseObject(result.toJSONString(),ResultCode.class);
}
}
package com.dingHelper.eventchange;
import com.dingHelper.Env;
import com.dingHelper.OApiException;
import com.dingHelper.OApiResultException;
import com.dingHelper.utils.HttpHelper;
import com.alibaba.fastjson.JSONObject;
import java.util.List;
public class eventChangeHelper {
//注册事件回调接口
public static String registerEventChange(String accessToken, List<String> callBackTag, String token, String aesKey, String url) throws OApiException{
String signUpUrl = Env.OAPI_HOST + "/call_back/register_call_back?" +
"access_token=" + accessToken;
JSONObject args = new JSONObject();
args.put("call_back_tag", callBackTag);
args.put("token", token);
args.put("aes_key", aesKey);
args.put("url", url);
JSONObject response = HttpHelper.httpPost(signUpUrl, args);
if (response.containsKey("errcode")) {
return response.getString("errcode");
}
else {
throw new OApiResultException("errcode");
}
}
//查询事件回调接口
public static String getEventChange(String accessToken) throws OApiException{
String url = Env.OAPI_HOST + "/call_back/get_call_back?" +
"access_token=" + accessToken;
JSONObject response = HttpHelper.httpGet(url);
return response.toString();
}
//更新事件回调接口
public static String updateEventChange(String accessToken, List<String> callBackTag, String token, String aesKey, String url) throws OApiException{
String signUpUrl = Env.OAPI_HOST + "/call_back/update_call_back?" +
"access_token=" + accessToken;
JSONObject args = new JSONObject();
args.put("call_back_tag", callBackTag);
args.put("token", token);
args.put("aes_key", aesKey);
args.put("url", url);
JSONObject response = HttpHelper.httpPost(signUpUrl, args);
if (response.containsKey("errcode")) {
return response.getString("errcode");
}
else {
throw new OApiResultException("errcode");
}
}
//删除事件回调接口
public static String deleteEventChange(String accessToken) throws OApiException{
String url = Env.OAPI_HOST + "/call_back/delete_call_back?" +
"access_token=" + accessToken;
JSONObject response = HttpHelper.httpGet(url);
return response.toString();
}
public static String getFailedResult(String accessToken) throws OApiException{
String url = Env.OAPI_HOST + "/call_back/get_call_back_failed_result?" +
"access_token=" + accessToken;
JSONObject response = HttpHelper.httpGet(url);
return response.toString();
}
}
package com.dingHelper.media;
import com.dingHelper.Env;
import com.dingHelper.OApiException;
import com.dingHelper.OApiResultException;
import com.dingHelper.utils.HttpHelper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.File;
public class MediaHelper {
public static final String TYPE_IMAGE = "image";
public static final String TYPE_VOICE = "voice";
public static final String TYPE_VIDEO = "video";
public static final String TYPE_FILE = "file";
public static class MediaUploadResult {
public String type;
public String media_id;
public String created_at;
}
public static MediaUploadResult upload(String accessToken, String type, File file) throws OApiException {
String url = Env.OAPI_HOST + "/media/upload?" +
"access_token=" + accessToken + "&type=" + type;
JSONObject response = HttpHelper.uploadMedia(url, file);
if (!response.containsKey("type") || !response.containsKey("media_id") ||
response.containsKey("created_at")) {
return JSON.parseObject(response.toJSONString(), MediaUploadResult.class);
}
else {
throw new OApiResultException("type or media_id or create_at");
}
}
public static void download(String accessToken, String mediaId, String fileDir) throws OApiException {
String url = Env.OAPI_HOST + "/media/get?" +
"access_token=" + accessToken + "&media_id=" + mediaId;
JSONObject response = HttpHelper.downloadMedia(url, fileDir);
System.out.println(response);
}
}
package com.dingHelper.message;
import com.alibaba.fastjson.JSONObject;
public class ConversationMessageDelivery extends MessageDelivery {
public String sender;
public String cid;
public String agentid;
public ConversationMessageDelivery(String sender, String cid,
String agentId) {
this.sender = sender;
this.cid = cid;
this.agentid = agentId;
}
public JSONObject toJsonObject() {
JSONObject json = super.toJsonObject();
json.put("sender", this.sender);
json.put("cid", this.cid);
json.put("agentid", this.agentid);
return json;
}
}
package com.dingHelper.message;
public class ImageMessage extends Message {
public String media_id;
public ImageMessage(String mediaId) {
super();
media_id = mediaId;
}
@Override
public String type() {
return "image";
}
}
package com.dingHelper.message;
import com.alibaba.fastjson.JSONObject;
public class LightAppMessageDelivery extends MessageDelivery {
public String touser;
public String toparty;
public String agentid;
public LightAppMessageDelivery(String toUsers, String toParties, String agentId) {
this.touser = toUsers;
this.toparty = toParties;
this.agentid = agentId;
}
@Override
public JSONObject toJsonObject() {
JSONObject json = super.toJsonObject();
json.put("touser", this.touser);
json.put("toparty", this.toparty);
json.put("agentid", this.agentid);
return json;
}
}
package com.dingHelper.message;
public class LinkMessage extends Message {
public String messageUrl;
public String picUrl;
public String title;
public String text;
public LinkMessage(String messageUrl, String picUrl, String title, String text) {
super();
this.messageUrl = messageUrl;
this.picUrl = picUrl;
this.title = title;
this.text = text;
}
@Override
public String type() {
return "link";
}
}
package com.dingHelper.message;
public abstract class Message {
public abstract String type();
}
package com.dingHelper.message;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class MessageDelivery {
public String msgtype;
public Message message;
public MessageDelivery withMessage(Message msg) {
this.msgtype = msg.type();
this.message = msg;
return this;
}
public JSONObject toJsonObject() {
JSONObject json = new JSONObject();
json.put("msgtype", this.msgtype);
json.put(this.msgtype, JSON.toJSON(this.message));
return json;
}
}
package com.dingHelper.message;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dingHelper.Env;
import com.dingHelper.OApiException;
import com.dingHelper.OApiResultException;
import com.dingHelper.utils.HttpHelper;
import java.util.List;
public class MessageHelper {
public static class Receipt {
String invaliduser;
String invalidparty;
}
public static Receipt send(String accessToken, LightAppMessageDelivery delivery)
throws OApiException {
String url = Env.OAPI_HOST + "/message/send?" +
"access_token=" + accessToken;
JSONObject response = HttpHelper.httpPost(url, delivery.toJsonObject());
if (response.containsKey("invaliduser") || response.containsKey("invalidparty")) {
Receipt receipt = new Receipt();
receipt.invaliduser = response.getString("invaliduser");
receipt.invalidparty = response.getString("invalidparty");
return receipt;
}
else {
throw new OApiResultException("invaliduser or invalidparty");
}
}
public static String send(String accessToken, ConversationMessageDelivery delivery)
throws OApiException {
String url = Env.OAPI_HOST + "/message/send_to_conversation?" +
"access_token=" + accessToken;
JSONObject response = HttpHelper.httpPost(url, delivery.toJsonObject());
if (response.containsKey("receiver")) {
return response.getString("receiver");
}
else {
throw new OApiResultException("receiver");
}
}
/**
* 获取消息已读未读状态
*
* @param accessToken accessToken
* @param messageId 消息id
* @Author Saber
* @Date 2016/12/23 上午10:44
*/
public static MessageRead getMessageStatus(String accessToken, String messageId) throws OApiException {
String url = Env.OAPI_HOST + "/message/list_message_status?access_token=" + accessToken;
JSONObject paramJOSN = new JSONObject();
paramJOSN.put("messageId", messageId);
JSONObject response = HttpHelper.httpPost(url, paramJOSN);
if (response.getIntValue("errcode") == 0) {
MessageRead messageRead = new MessageRead();
//已读
List<String> readList = JSON.parseArray(response.getString("read"), String.class);
messageRead.setReadList(readList);
//未读
List<String> unreadList = JSON.parseArray(response.getString("unread"), String.class);
messageRead.setUnreadList(unreadList);
return messageRead;
} else {
throw new OApiResultException("errmsg");
}
}
public static void main(String[] args) {
String accessToken = "2290a9088d0a38489ca105bbe3fa02ed";
String messageId = "b24fee6132843a4692190ac811dd90d1";
//accessToken="11c48a9c625f38e794664c191b4527c8";
messageId = "78732610fe02373193feb9e692dbc3e2";
messageId = "b7fd2a47b7f236249f4850ca61df6a13";
try {
MessageRead messageRead = getMessageStatus(accessToken, messageId);
//System.err.println("messageRead:"+messageRead.toString());
System.err.println("已读数量:" + messageRead.getReadList().size() + "\n已读:" + messageRead.getReadList());
System.err.println("未读数量:" + messageRead.getUnreadList().size() + "\n未读:" + messageRead.getUnreadList());
} catch (OApiResultException e) {
e.printStackTrace();
} catch (OApiException e) {
e.printStackTrace();
}
}
}
package com.dingHelper.message;
import java.util.List;
/**
* Created by Saber on 2016/12/21.
*/
public class MessageRead {
/**
* 已读的人员userId
*/
private List<String> readList;
/**
* 未读得到人员userId
*/
private List<String> unreadList;
public List<String> getReadList() {
return readList;
}
public void setReadList(List<String> readList) {
this.readList = readList;
}
public List<String> getUnreadList() {
return unreadList;
}
public void setUnreadList(List<String> unreadList) {
this.unreadList = unreadList;
}
@Override
public String toString() {
return "MessageRead{" +
"readList=" + readList +
", unreadList=" + unreadList +
'}';
}
}
package com.dingHelper.message;
import java.util.List;
/**
{
"message_url": "http://dingtalk.com",
"head": {
"bgcolor": "FFCC0000"
},
"body": {
"title": "标题",
"form": [
{
"key": "姓名",
"value": "张三"
},
{
"key": "年龄",
"value": "30"
}
],
"rich": {
"num": "15.6",
"unit": "元"
},
"content": "大段文本",
"image": "@lADOAAGXIszazQKA",
"file_count": "3",
"author": "李四"
}
*/
public class OAMessage extends Message {
public String message_url;
public Head head;
public Body body;
@Override
public String type() {
return "oa";
}
//content
public static class Head {
public String bgcolor;
}
public static class Body {
public String title;
public List<Form> form;
public Rich rich;
public String content;
public String image;
public String file_found;
public String author;
public static class Form {
public String key;
public String value;
}
public static class Rich {
public String num;
public String unit;
}
}
}
package com.dingHelper.message;
public class TextMessage extends Message {
public String content;
public TextMessage(String content) {
super();
this.content = content;
}
@Override
public String type() {
return "text";
}
}
package com.dingHelper.service;
import com.dingHelper.Env;
import com.dingHelper.OApiException;
import com.dingHelper.utils.HttpHelper;
import com.alibaba.fastjson.JSONObject;
public class ServiceHelper {
public static String getSuiteToken(String suite_key, String suite_secret,String suite_ticket){
String url = Env.OAPI_HOST + "/service/get_suite_token";
JSONObject json = new JSONObject();
json.put("suite_key", suite_key);
json.put("suite_secret", suite_secret);
json.put("suite_ticket", suite_ticket);
JSONObject reponseJson = null;
String suiteAccessToken = null;
try {
reponseJson = HttpHelper.httpPost(url, json);
suiteAccessToken = reponseJson.getString("suite_access_token");
} catch (OApiException e) {
e.printStackTrace();
}
return suiteAccessToken;
}
public static JSONObject getPermanentCode(String tmp_auth_cod, String suiteAccessToken ){
String url = Env.OAPI_HOST + "/service/get_permanent_code?suite_access_token=" + suiteAccessToken ;
JSONObject json = new JSONObject();
json.put("tmp_auth_code", tmp_auth_cod);
JSONObject reponseJson = null;
try {
reponseJson = HttpHelper.httpPost(url,json);
} catch (OApiException e) {
e.printStackTrace();
}
return reponseJson;
}
public static String getCorpToken(String auth_corpid, String permanent_code, String suiteAccessToken ){
String url = Env.OAPI_HOST + "/service/get_corp_token?suite_access_token=" + suiteAccessToken ;
JSONObject json = new JSONObject();
json.put("auth_corpid", auth_corpid);
json.put("permanent_code", permanent_code);
JSONObject reponseJson = null;
String corpToken = null;
try {
reponseJson = HttpHelper.httpPost(url,json);
corpToken = reponseJson.getString("access_token");
} catch (OApiException e) {
e.printStackTrace();
}
return corpToken;
}
public static JSONObject getAuthInfo(String suiteAccessToken, String suite_key, String auth_corpid, String permanent_code){
String url = Env.OAPI_HOST + "/service/get_auth_info?suite_access_token=" + suiteAccessToken ;
JSONObject json = new JSONObject();
json.put("suite_key", suite_key);
json.put("auth_corpid", auth_corpid);
json.put("permanent_code", permanent_code);
JSONObject reponseJson = null;
try {
reponseJson = HttpHelper.httpPost(url,json);
} catch (OApiException e) {
e.printStackTrace();
}
return reponseJson;
}
public static JSONObject getAgent(String suiteAccessToken, String suite_key, String auth_corpid, String permanent_code, String agentid){
String url = Env.OAPI_HOST + "/service/get_agent?suite_access_token=" + suiteAccessToken ;
JSONObject json = new JSONObject();
json.put("suite_key", suite_key);
json.put("auth_corpid", auth_corpid);
json.put("permanent_code", permanent_code);
json.put("agentid", agentid);//agentid可以通过getAuthInfo返回的json中得到
JSONObject reponseJson = null;
try {
reponseJson = HttpHelper.httpPost(url,json);
} catch (OApiException e) {
e.printStackTrace();
}
return reponseJson;
}
public static JSONObject getActivateSuite(String suiteAccessToken, String suite_key, String auth_corpid, String permanent_code ){
String url = Env.OAPI_HOST + "/service/activate_suite?suite_access_token=" + suiteAccessToken ;
JSONObject json = new JSONObject();
json.put("suite_key", suite_key);
json.put("auth_corpid", auth_corpid);
json.put("permanent_code", permanent_code);
JSONObject reponseJson = null;
try {
reponseJson = HttpHelper.httpPost(url,json);
} catch (OApiException e) {
e.printStackTrace();
}
return reponseJson;
}
}
package com.dingHelper.user;
import com.alibaba.fastjson.JSONObject;
import java.util.List;
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 email;
public String openId;
public int status;
public JSONObject extattr;
public User() {
}
public User(String userid, String name) {
this.userid = userid;
this.name = name;
}
@Override
public String toString() {
List<User> users;
return "User[userid:" + userid + ", name:" + name + ", active:" + active + ", "
+ "avatar:" + avatar + ", department:" + department +
", position:" + position + ", mobile:" + mobile + ", email:" + email +
", openId:" + openId + ", status:" + status +", extattr:" + extattr;
}
}
package com.dingHelper.user;
import com.dingHelper.Env;
import com.dingHelper.OApiException;
import com.dingHelper.OApiResultException;
import com.dingHelper.utils.HttpHelper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class UserHelper {
//创建成员
public static void createUser(String accessToken, User user) throws OApiException {
String url = Env.OAPI_HOST + "/user/create?" +
"access_token=" + accessToken;
HttpHelper.httpPost(url, user);
}
//更新成员
public static void updateUser(String accessToken, User user) throws OApiException {
String url = Env.OAPI_HOST + "/user/update?" +
"access_token=" + accessToken;
HttpHelper.httpPost(url, user);
}
//删除成员
public static void deleteUser(String accessToken, String userid) throws OApiException {
String url = Env.OAPI_HOST + "/user/delete?" +
"access_token=" + accessToken + "&userid=" + userid;
HttpHelper.httpGet(url);
}
//获取成员
public static User getUser(String accessToken, String userid) throws OApiException {
String url = Env.OAPI_HOST + "/user/get?" +
"access_token=" + accessToken + "&userid=" + userid;
JSONObject json = HttpHelper.httpGet(url);
return JSON.parseObject(json.toJSONString(), User.class);
}
//批量删除成员
public static void batchDeleteUser(String accessToken, List<String> useridlist)
throws OApiException {
String url = Env.OAPI_HOST + "/user/batchdelete?" +
"access_token=" + accessToken;
JSONObject args = new JSONObject();
args.put("useridlist", useridlist);
HttpHelper.httpPost(url, args);
}
//获取部门成员
public static List<User> getDepartmentUser(String accessToken, long department_id)
throws OApiException {
String url = Env.OAPI_HOST + "/user/simplelist?" +
"access_token=" + accessToken + "&department_id=" + department_id;
JSONObject response = HttpHelper.httpGet(url);
if (response.containsKey("userlist")) {
List<User> list = new ArrayList();
JSONArray arr = response.getJSONArray("userlist");
for (int i = 0; i < arr.size(); i++) {
list.add(arr.getObject(i, User.class));
}
return list;
}
else {
throw new OApiResultException("userlist");
}
}
//获取部门成员(详情)
public static List<User> getUserDetails(String accessToken, long department_id)
throws OApiException {
String url = Env.OAPI_HOST + "/user/list?" +
"access_token=" + accessToken + "&department_id=" + department_id;
JSONObject response = HttpHelper.httpGet(url);
if (response.containsKey("userlist")) {
JSONArray arr = response.getJSONArray("userlist");
List<User> list = new ArrayList();
for (int i = 0; i < arr.size(); i++) {
list.add(arr.getObject(i, User.class));
}
return list;
}
else {
throw new OApiResultException("userlist");
}
}
public static JSONObject getUserInfo(String accessToken, String code) throws OApiException{
String url = Env.OAPI_HOST + "/user/getuserinfo?" + "access_token=" + accessToken + "&code=" + code;
JSONObject response = HttpHelper.httpGet(url);
return response;
}
public static JSONObject getAgentUserInfo(String ssoToken, String code) throws OApiException{
String url = Env.OAPI_HOST + "/sso/getuserinfo?" + "access_token=" + ssoToken + "&code=" + code;
JSONObject response = HttpHelper.httpGet(url);
return response;
}
}
package com.dingHelper.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class FileUtils {
public static final String FILEPATH = "Permanent_Data";
public static JSON generateJSON(String key, String value) {
JSONObject json = new JSONObject();
json.put(key, value);
return json;
}
public static JSON generateJSON(Map<String, String> values) {
JSONObject json = new JSONObject();
Iterator<Entry<String, String>> iter = values.entrySet().iterator();
while (iter.hasNext()) {
Entry entry = (Entry) iter.next();
json.put(entry.getKey().toString(), entry.getValue().toString());
}
return json;
}
// json写入文件
public static void write2File(Object json, String fileName) {
BufferedWriter writer = null;
File filePath = new File(FILEPATH);
JSONObject eJSON = null;
if (!filePath.exists() && !filePath.isDirectory()) {
filePath.mkdirs();
}
File file = new File(FILEPATH + File.separator + fileName + ".xml");
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(new Date())+"path:" + file.getPath() + " abs path:" + file.getAbsolutePath());
if (!file.exists()) {
try {
file.createNewFile();
} catch (Exception e) {
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(new Date())+"createNewFile,出现异常:");
e.printStackTrace();
}
} else {
eJSON = (JSONObject) read2JSON(fileName);
}
try {
writer = new BufferedWriter(new FileWriter(file));
//if (eJSON.equals(null)) {
if (eJSON==null) {
writer.write(json.toString());
} else {
Object[] array = ((JSONObject) json).keySet().toArray();
if (eJSON.containsKey(array[0].toString())) {
@SuppressWarnings("unchecked")
Map<String, String> values = JSON.parseObject(eJSON.toString(), Map.class);
values.put(array[0].toString(), ((JSONObject) json).get(array[0].toString()).toString());
} else {
eJSON.put(array[0].toString(), ((JSONObject) json).get(array[0].toString()));
}
writer.write(eJSON.toString());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static JSONObject read2JSON(String fileName) {
File file = new File(FILEPATH + File.separator + fileName + ".xml");
if (!file.exists()) {
return null;
}
BufferedReader reader = null;
String laststr = "";
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
while ((tempString = reader.readLine()) != null) {
laststr += tempString;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
JSON.parse(laststr);
return (JSONObject) JSON.parse(laststr);
}
// 通过key值获取文件中的value
public static void getKey(String key) {
}
}
This diff is collapsed.
package com.dingHelper.utils.aes;
import java.util.HashMap;
import java.util.Map;
/**
* 钉钉开放平台加解密异常类
*/
public class DingTalkEncryptException extends Exception {
/**成功**/
public static final int SUCCESS = 0;
/**加密明文文本非法**/
public final static int ENCRYPTION_PLAINTEXT_ILLEGAL = 900001;
/**加密时间戳参数非法**/
public final static int ENCRYPTION_TIMESTAMP_ILLEGAL = 900002;
/**加密随机字符串参数非法**/
public final static int ENCRYPTION_NONCE_ILLEGAL = 900003;
/**不合法的aeskey**/
public final static int AES_KEY_ILLEGAL = 900004;
/**签名不匹配**/
public final static int SIGNATURE_NOT_MATCH = 900005;
/**计算签名错误**/
public final static int COMPUTE_SIGNATURE_ERROR = 900006;
/**计算加密文字错误**/
public final static int COMPUTE_ENCRYPT_TEXT_ERROR = 900007;
/**计算解密文字错误**/
public final static int COMPUTE_DECRYPT_TEXT_ERROR = 900008;
/**计算解密文字长度不匹配**/
public final static int COMPUTE_DECRYPT_TEXT_LENGTH_ERROR = 900009;
/**计算解密文字corpid不匹配**/
public final static int COMPUTE_DECRYPT_TEXT_CORPID_ERROR = 900010;
private static Map<Integer,String> msgMap = new HashMap<Integer,String>();
static{
msgMap.put(SUCCESS,"成功");
msgMap.put(ENCRYPTION_PLAINTEXT_ILLEGAL,"加密明文文本非法");
msgMap.put(ENCRYPTION_TIMESTAMP_ILLEGAL,"加密时间戳参数非法");
msgMap.put(ENCRYPTION_NONCE_ILLEGAL,"加密随机字符串参数非法");
msgMap.put(SIGNATURE_NOT_MATCH,"签名不匹配");
msgMap.put(COMPUTE_SIGNATURE_ERROR,"签名计算失败");
msgMap.put(AES_KEY_ILLEGAL,"不合法的aes key");
msgMap.put(COMPUTE_ENCRYPT_TEXT_ERROR,"计算加密文字错误");
msgMap.put(COMPUTE_DECRYPT_TEXT_ERROR,"计算解密文字错误");
msgMap.put(COMPUTE_DECRYPT_TEXT_LENGTH_ERROR,"计算解密文字长度不匹配");
msgMap.put(COMPUTE_DECRYPT_TEXT_CORPID_ERROR,"计算解密文字corpid或者suiteKey不匹配");
}
public Integer code;
public DingTalkEncryptException(Integer exceptionCode){
super(msgMap.get(exceptionCode));
this.code = exceptionCode;
}
}
package com.dingHelper.utils.aes;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* 钉钉开放平台加解密方法
* 在ORACLE官方网站下载JCE无限制权限策略文件
* JDK6的下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html
* JDK7的下载地址: http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
*/
public class DingTalkEncryptor {
private static final Charset CHARSET = Charset.forName("utf-8");
private static final Base64 base64 = new Base64();
private byte[] aesKey;
private String token;
private String corpId;
/**ask getPaddingBytes key固定长度**/
private static final Integer AES_ENCODE_KEY_LENGTH = 43;
/**加密随机字符串字节长度**/
private static final Integer RANDOM_LENGTH = 16;
/**
* 构造函数
* @param token 钉钉开放平台上,开发者设置的token
* @param encodingAesKey 钉钉开放台上,开发者设置的EncodingAESKey
* @param corpId ISV进行配置的时候应该传对应套件的SUITE_KEY,普通企业是Corpid
* @throws DingTalkEncryptException 执行失败,请查看该异常的错误码和具体的错误信息
*/
public DingTalkEncryptor(String token, String encodingAesKey, String corpId) throws DingTalkEncryptException{
if (null==encodingAesKey || encodingAesKey.length() != AES_ENCODE_KEY_LENGTH) {
throw new DingTalkEncryptException(DingTalkEncryptException.AES_KEY_ILLEGAL);
}
this.token = token;
this.corpId = corpId;
aesKey = Base64.decodeBase64(encodingAesKey + "=");
}
/**
* 将和钉钉开放平台同步的消息体加密,返回加密Map
* @param plaintext 传递的消息体明文
* @param timeStamp 时间戳
* @param nonce 随机字符串
* @return
* @throws DingTalkEncryptException
*/
public Map<String,String> getEncryptedMap(String plaintext, Long timeStamp, String nonce) throws DingTalkEncryptException {
if(null==plaintext){
throw new DingTalkEncryptException(DingTalkEncryptException.ENCRYPTION_PLAINTEXT_ILLEGAL);
}
if(null==timeStamp){
throw new DingTalkEncryptException(DingTalkEncryptException.ENCRYPTION_TIMESTAMP_ILLEGAL);
}
if(null==nonce){
throw new DingTalkEncryptException(DingTalkEncryptException.ENCRYPTION_NONCE_ILLEGAL);
}
// 加密
String encrypt = encrypt(Utils.getRandomStr(RANDOM_LENGTH), plaintext);
String signature = getSignature(token, String.valueOf(timeStamp), nonce, encrypt);
Map<String,String> resultMap = new HashMap<String, String>();
resultMap.put("msg_signature", signature);
resultMap.put("encrypt", encrypt);
resultMap.put("timeStamp", String.valueOf(timeStamp));
resultMap.put("nonce", nonce);
return resultMap;
}
/**
* 密文解密
* @param msgSignature 签名串
* @param timeStamp 时间戳
* @param nonce 随机串
* @param encryptMsg 密文
* @return 解密后的原文
* @throws DingTalkEncryptException
*/
public String getDecryptMsg(String msgSignature, String timeStamp, String nonce, String encryptMsg)throws DingTalkEncryptException {
//校验签名
String signature = getSignature(token, timeStamp, nonce, encryptMsg);
if (!signature.equals(msgSignature)) {
throw new DingTalkEncryptException(DingTalkEncryptException.COMPUTE_SIGNATURE_ERROR);
}
// 解密
String result = decrypt(encryptMsg);
return result;
}
/*
* 对明文加密.
* @param text 需要加密的明文
* @return 加密后base64编码的字符串
*/
private String encrypt(String random, String plaintext) throws DingTalkEncryptException {
try {
byte[] randomBytes = random.getBytes(CHARSET);
byte[] plainTextBytes = plaintext.getBytes(CHARSET);
byte[] lengthByte = Utils.int2Bytes(plainTextBytes.length);
byte[] corpidBytes = corpId.getBytes(CHARSET);
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byteStream.write(randomBytes);
byteStream.write(lengthByte);
byteStream.write(plainTextBytes);
byteStream.write(corpidBytes);
byte[] padBytes = PKCS7Padding.getPaddingBytes(byteStream.size());
byteStream.write(padBytes);
byte[] unencrypted = byteStream.toByteArray();
byteStream.close();
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
byte[] encrypted = cipher.doFinal(unencrypted);
String result = base64.encodeToString(encrypted);
return result;
} catch (Exception e) {
throw new DingTalkEncryptException(DingTalkEncryptException.COMPUTE_ENCRYPT_TEXT_ERROR);
}
}
/*
* 对密文进行解密.
* @param text 需要解密的密文
* @return 解密得到的明文
*/
private String decrypt(String text) throws DingTalkEncryptException {
byte[] originalArr;
try {
// 设置解密模式为AES的CBC模式
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
// 使用BASE64对密文进行解码
byte[] encrypted = Base64.decodeBase64(text);
// 解密
originalArr = cipher.doFinal(encrypted);
} catch (Exception e) {
throw new DingTalkEncryptException(DingTalkEncryptException.COMPUTE_DECRYPT_TEXT_ERROR);
}
String plainText;
String fromCorpid;
try {
// 去除补位字符
byte[] bytes = PKCS7Padding.removePaddingBytes(originalArr);
// 分离16位随机字符串,网络字节序和corpId
byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20);
int plainTextLegth = Utils.bytes2int(networkOrder);
plainText = new String(Arrays.copyOfRange(bytes, 20, 20 + plainTextLegth), CHARSET);
fromCorpid = new String(Arrays.copyOfRange(bytes, 20 + plainTextLegth, bytes.length), CHARSET);
} catch (Exception e) {
throw new DingTalkEncryptException(DingTalkEncryptException.COMPUTE_DECRYPT_TEXT_LENGTH_ERROR);
}
// corpid不相同的情况
if (!fromCorpid.equals(corpId)) {
throw new DingTalkEncryptException(DingTalkEncryptException.COMPUTE_DECRYPT_TEXT_CORPID_ERROR);
}
return plainText;
}
/**
* 数字签名
* @param token isv token
* @param timestamp 时间戳
* @param nonce 随机串
* @param encrypt 加密文本
* @return
* @throws DingTalkEncryptException
*/
public String getSignature(String token, String timestamp, String nonce, String encrypt) throws DingTalkEncryptException {
try {
String[] array = new String[] { token, timestamp, nonce, encrypt };
Arrays.sort(array);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 4; i++) {
sb.append(array[i]);
}
String str = sb.toString();
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(str.getBytes());
byte[] digest = md.digest();
StringBuffer hexstr = new StringBuffer();
String shaHex = "";
for (int i = 0; i < digest.length; i++) {
shaHex = Integer.toHexString(digest[i] & 0xFF);
if (shaHex.length() < 2) {
hexstr.append(0);
}
hexstr.append(shaHex);
}
return hexstr.toString();
} catch (Exception e) {
throw new DingTalkEncryptException(DingTalkEncryptException.COMPUTE_SIGNATURE_ERROR);
}
}
}
package com.dingHelper.utils.aes;
import java.security.MessageDigest;
import java.util.Formatter;
/**
* 钉钉jsapi签名工具类
*/
public class DingTalkJsApiSingnature {
/**
* 获取jsapi签名
* @param url
* @param nonce
* @param timeStamp
* @param jsTicket
* @return
* @throws DingTalkEncryptException
*/
public static String getJsApiSingnature(String url,String nonce,Long timeStamp,String jsTicket) throws DingTalkEncryptException{
String plainTex = "jsapi_ticket=" + jsTicket +"&noncestr=" + nonce +"&timestamp=" + timeStamp + "&url=" + url;
System.out.println(plainTex);
String signature = "";
try{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(plainTex.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
return signature;
}catch (Exception e){
throw new DingTalkEncryptException(DingTalkEncryptException.COMPUTE_SIGNATURE_ERROR);
}
}
private static String byteToHex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash){
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
public static void main(String args[]) throws Exception{
// signature:810e6657e9f411e6491b3e97dfaf7660e89eb874,serverSign:0e781e79966d6f27e2b6456b83d5cee0ebaeb81b
String url="http://10.62.53.138:3000/jsapi";
String nonce="abcdefgh";
Long timeStamp = 1437027269927L;
String tikcet="zHoQdGJuH0ZDebwo7sLqLzHGUueLmkWCC4RycYgkuvDu3eoROgN5qhwnQLgfzwEXtuR9SDzh6BdhyVngzAjrxV";
System.err.println(getJsApiSingnature(url,nonce,timeStamp,tikcet));
}
}
package com.dingHelper.utils.aes;
import java.nio.charset.Charset;
import java.util.Arrays;
/*
* PKCS7算法的加密填充
*/
public class PKCS7Padding {
private final static Charset CHARSET = Charset.forName("utf-8");
private final static int BLOCK_SIZE = 32;
/**
* 填充mode字节
* @param count
* @return
*/
public static byte[] getPaddingBytes(int count) {
int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);
if (amountToPad == 0) {
amountToPad = BLOCK_SIZE;
}
char padChr = chr(amountToPad);
String tmp = new String();
for (int index = 0; index < amountToPad; index++) {
tmp += padChr;
}
return tmp.getBytes(CHARSET);
}
/**
* 移除mode填充字节
* @param decrypted
* @return
*/
public static byte[] removePaddingBytes(byte[] decrypted) {
int pad = (int) decrypted[decrypted.length - 1];
if (pad < 1 || pad > BLOCK_SIZE) {
pad = 0;
}
return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
}
private static char chr(int a) {
byte target = (byte) (a & 0xFF);
return (char) target;
}
}
package com.dingHelper.utils.aes;
import java.util.Random;
/**
* 加解密工具类
*/
public class Utils {
/**
*
* @return
*/
public static String getRandomStr(int count) {
String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < count; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
/*
* int转byte数组,高位在前
*/
public static byte[] int2Bytes(int count) {
byte[] byteArr = new byte[4];
byteArr[3] = (byte) (count & 0xFF);
byteArr[2] = (byte) (count >> 8 & 0xFF);
byteArr[1] = (byte) (count >> 16 & 0xFF);
byteArr[0] = (byte) (count >> 24 & 0xFF);
return byteArr;
}
/**
* 高位在前bytes数组转int
* @param byteArr
* @return
*/
public static int bytes2int(byte[] byteArr) {
int count = 0;
for (int i = 0; i < 4; i++) {
count <<= 8;
count |= byteArr[i] & 0xff;
}
return count;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment