package foundation.icall.connector;
|
|
import java.util.Date;
|
import java.util.HashMap;
|
import java.util.Map;
|
|
import com.alibaba.fastjson.JSONObject;
|
|
import foundation.dao.DataReader;
|
import foundation.data.entity.Entity;
|
import foundation.data.entity.Filter;
|
import foundation.data.object.DataObject;
|
import foundation.handler.DataPool;
|
import foundation.handler.ResultPool;
|
import foundation.icall.ICall;
|
import foundation.icall.callout.ICallRequest;
|
import foundation.icall.callout.JSONResponse;
|
import foundation.json.JObjectReader;
|
import foundation.json.JSONReader;
|
import foundation.json.JType;
|
import foundation.persist.NamedSQL;
|
import foundation.persist.SQLRunner;
|
import foundation.util.DingCallbackCrypto;
|
import foundation.util.ID;
|
import foundation.util.Util;
|
import foundation.workflow.WorkStep;
|
import okhttp3.MediaType;
|
import okhttp3.OkHttpClient;
|
import okhttp3.Request;
|
import okhttp3.RequestBody;
|
import okhttp3.Response;
|
|
public class DingConn extends HttpServerConn {
|
private static DingConn instance;
|
private static int TimeOutHour = 2;
|
private static String monitorId = "DingConn";
|
public Map<String, Date> serverLastTime;
|
private String token;
|
|
private DingConn() {
|
serverLastTime = new HashMap<String, Date>();
|
}
|
|
public static synchronized DingConn getInstance() {
|
if (instance == null) {
|
instance = new DingConn();
|
}
|
|
return instance;
|
}
|
|
@Override
|
public ResultPool echoSignature(ResultPool resultPool, DataPool dataPool) throws Exception{
|
String aesToken = meta.getString("token");
|
String aesKey = meta.getString("aes_key");
|
String keyField = dataPool.getParam("keyfield");
|
|
if (Util.isEmpty(keyField)){
|
keyField = "client_id";
|
}
|
String suitKey = meta.getString(keyField);
|
|
DingCallbackCrypto callbackCrypto = new DingCallbackCrypto(aesToken, aesKey, suitKey);
|
Map<String, String> resultMap = callbackCrypto.getEncryptedMap("success");
|
resultPool.addValue("msg_signature", resultMap.get("msg_signature"));
|
resultPool.addValue("encrypt", resultMap.get("encrypt"));
|
resultPool.addValue("timeStamp", resultMap.get("timeStamp"));
|
resultPool.addValue("nonce", resultMap.get("nonce"));
|
|
resultPool.setFireReplay(false);
|
|
//加密方法内传你的回调地址返回给钉钉服务器的四个参数
|
String result = callbackCrypto.getDecryptMsg(resultMap.get("msg_signature"), resultMap.get("timeStamp"), resultMap.get("nonce"), resultMap.get("encrypt"));
|
System.out.println(result);
|
|
return resultPool;
|
}
|
|
public ResultPool echo(ResultPool resultPool, DataPool dataPool) throws Exception{
|
// // 关注事件
|
// if(MessageType.Event == MessageType.parse(msgType) && EventType.Subscribe == EventType.parse(eventType)){
|
// // 1. 获取unionid
|
// login(null, null);
|
// Request request = new Request.Builder()
|
// .url("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token +"&openid=" + platformOpenId + "&lang=zh_CN")
|
// .get()
|
// .build();
|
// OkHttpClient httpClient = new OkHttpClient();
|
// Response response = httpClient.newCall(request).execute();
|
// JSONResponse result = new JSONResponse(response);
|
// String unionId = result.getString("unionid");
|
//
|
// DataObject accountbject = DataObject.getInstance("md_org_account");
|
//
|
// // 2.1 不存在场景ID(搜索关注), 则根据用户Id新建绑定关系
|
// if (Util.isEmpty(sceneId)) {
|
// Filter filter = new Filter();
|
// filter.add("union_id", unionId);
|
// EntitySet accountSet = accountbject.getTableEntitySet(filter);
|
//
|
// if (accountSet.size() < 1) {
|
// Entity account = createNewAccount(unionId, platformOpenId, null);
|
// accountbject.saveEntity(account);
|
// accountId = account.getId();
|
// }
|
// else {
|
// // 2.2 搜索关注并已绑定小程序, 更新户公众号唯一标识
|
// for (Entity account : accountSet) {
|
// if (Util.isEmpty(account.getString("wx_openid_platform"))) {
|
// account.set("wx_openid_platform", platformOpenId);
|
// accountbject.updateEntity(account);
|
// }
|
//
|
// accountId = account.getId();
|
// }
|
// }
|
// }
|
// else {
|
// EntitySet accountSet = accountbject.getTableEntitySet(new Filter("scene_id", sceneId));
|
//
|
// // 2.3 存在场景ID(扫码关注), 则根据场景Id更新用户ID
|
// for (Entity account : accountSet) {
|
// account.set("wx_openid_platform", platformOpenId);
|
// account.set("union_id", unionId);
|
// accountbject.updateEntity(account);
|
//
|
// accountId = account.getId();
|
// }
|
// }
|
//
|
// DataPackage dataPackage = DataPackage.getInstance("md_org_account");
|
// dataPackage.setMasterId(accountId);
|
// dataPackage.loadOneDataFromDB();
|
//
|
// SendTemplate sendTemplate = new SendTemplate("request/wx_subscribe_reply.txt");
|
// content = sendTemplate.generateFill(dataPackage) ;
|
// }
|
//
|
return resultPool;
|
}
|
|
@Override
|
public JObjectReader formatReader(DataReader reuqestReader) throws Exception{
|
DataPool dataPool = reuqestReader.getDataPool();
|
JObjectReader dataReader = dataPool.getJObjectReader();
|
String signature = dataPool.getParam("signature");
|
String msgSignature = dataPool.getParam("msg_signature");
|
String timeStamp = dataPool.getParam("timestamp");
|
String nonce = dataPool.getParam("nonce");
|
String encryptMsg = dataReader.getString("encrypt");
|
encryptMsg = encryptMsg.replace(' ', '+');
|
String aesToken = meta.getString("token");
|
String aesKey = meta.getString("aes_key");
|
String keyField = dataPool.getParam("keyfield");
|
|
if (Util.isEmpty(keyField)){
|
keyField = "client_id";
|
}
|
String suitKey = meta.getString(keyField);
|
|
DingCallbackCrypto callbackCrypto = new DingCallbackCrypto(aesToken, aesKey, suitKey);
|
String decryptMsg = callbackCrypto.getDecryptMsg(msgSignature, timeStamp, nonce, encryptMsg);
|
JObjectReader result = new JObjectReader(decryptMsg);
|
|
result.put("signature", signature);
|
result.put("timestamp", timeStamp);
|
result.put("nonce", nonce);
|
result.put("msgSignature", msgSignature);
|
return result;
|
}
|
|
private Entity createNewAccount(String unionId, String platformOpenId, String programOpenId) throws Exception {
|
DataObject accountbject = DataObject.getInstance("md_org_account");
|
Entity account = accountbject.createTableEntity(true);
|
|
if (!Util.isEmpty(platformOpenId)) {
|
logger.info("set wx_openid_platform :{}", platformOpenId);
|
account.set("wx_openid_platform", platformOpenId);
|
}
|
|
if (!Util.isEmpty(programOpenId)) {
|
logger.info("set wx_open_id :{}", programOpenId);
|
account.set("wx_open_id", programOpenId);
|
}
|
account.set("union_id", unionId);
|
|
String appid = meta.getString("appid");
|
DataObject platformObject = DataObject.getInstance("md_platform");
|
Entity platform = platformObject.getTableEntity(new Filter("wx_open_id", appid));
|
|
if (platform != null) {
|
String platformId = platform.getId();
|
String platformName = platform.getString("name");
|
account.set("company_id", platformId);
|
account.set("company_name", platformName);
|
account.set("division_id", platformId);
|
account.set("division_name", platformName);
|
}
|
|
account.set("scene_id", ID.newValue());
|
return account;
|
}
|
|
@Override
|
public Entity systemLogin(DataPool dataPool) throws Exception {
|
String code = dataPool.getParam("code");
|
String getUserUrl = meta.getString("ssoinfo_url")
|
+ "?access_token=" + token;
|
|
JSONObject jsonObject = new JSONObject();
|
jsonObject.put("code", code);
|
|
String jsonBody = jsonObject.toJSONString();
|
|
Request request = new Request.Builder()
|
.url(getUserUrl)
|
.post(RequestBody.create(MediaType.get("application/json"), jsonBody))
|
.build();
|
OkHttpClient httpClient = new OkHttpClient();
|
Response response = httpClient.newCall(request).execute();
|
JSONResponse result = new JSONResponse(response);
|
|
JSONReader reader = result.getReader();
|
JSONReader resultJson = reader.getReader("result", JType.Object);
|
String userId = resultJson.getString("userid");
|
logger.info("result.userId: {}", userId);
|
|
NamedSQL namedSQL = NamedSQL.getInstance("getUserBySystem");
|
namedSQL.setParam("userNameField", "dingtalk_id");
|
namedSQL.setParam("unionId", userId);
|
namedSQL.setParam("is_active", "T");
|
Entity account = SQLRunner.getEntity(namedSQL);
|
|
return account;
|
}
|
|
@Override
|
public void login(WorkStep step, ICall iCall) throws Exception {
|
if (!tokenExpired()) {
|
return;
|
}
|
|
//1. 获取 token
|
getToken();
|
}
|
|
@Override
|
public void logout(WorkStep step, ICall iCall) throws Exception {
|
|
}
|
|
@Override
|
public ICallRequest createRequest(String url) {
|
String requestUrl = "";
|
if (url.contains("?")) {
|
requestUrl = url + "&access_token="+ token;
|
}
|
else {
|
requestUrl = url + "?access_token=" + token;
|
}
|
|
ICallRequest request = new ICallRequest(requestUrl);
|
request.addHeader("x-acs-dingtalk-access-token", token);
|
return request;
|
}
|
|
private boolean tokenExpired() {
|
Date lastTime = serverLastTime.get(meta.getName());
|
|
if (Util.isEmpty(token) || lastTime == null) {
|
return true;
|
}
|
|
Date now = new Date();
|
boolean result = now.getTime() - lastTime.getTime() >= TimeOutHour * 60 * 60 * 1000;
|
logger.info("是否重新获取token:{}, 上次获取token时间:{}, 本次获取token时间:{}", result, lastTime, now);
|
|
return result;
|
}
|
|
private void getToken() throws Exception {
|
String appid = meta.getString("client_id");
|
String secret = meta.getString("client_secret");
|
String url = meta.getString("token_url");
|
|
JSONObject jsonObject = new JSONObject();
|
jsonObject.put("appKey", appid);
|
jsonObject.put("appSecret", secret);
|
|
String jsonBody = jsonObject.toJSONString();
|
|
Request request = new Request.Builder()
|
.url(url)
|
.post(RequestBody.create(MediaType.get("application/json"), jsonBody))
|
.build();
|
|
OkHttpClient httpClient = new OkHttpClient();
|
Response response = httpClient.newCall(request).execute();
|
JSONResponse result = new JSONResponse(response);
|
|
token = result.getString("accessToken");
|
logger.info("token:{}", token);
|
|
serverLastTime.put(meta.getName(), new Date());
|
}
|
|
public String getName() {
|
return meta.getName();
|
}
|
|
@Override
|
public String getAccessToken() {
|
return token;
|
}
|
}
|