P15GEN2\59518
2025-10-10 9f6890646993d16260d4201d613c092132856127
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
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;
    }
}