wangrenhuang
2023-04-03 aa0a7a2e1dc2b2aba12d5c014fd0037e30251224
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package com.hx.mp.util;
 
import com.hx.corp.entity.AppLetInfo;
import com.hx.exception.TipsException;
import com.hx.util.HttpMethodUtil;
import com.hx.util.StringUtils;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.poi.util.SystemOutLogger;
 
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
 
/**
 * 企业微信工具类
 */
public class CorpMpUtil {
 
    /**链接-获取应用accessToken*/
    public static final String URL_GET_ACCESS_TOKEN = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}";
    /**链接-获取session信息*/
    public static final String URL_CODE_2_SESSION = "https://qyapi.weixin.qq.com/cgi-bin/miniprogram/jscode2session?access_token={0}&js_code={1}&grant_type=authorization_code";
    /**链接-添加标签*/
    public static final String URL_ADD_LABEL = "https://qyapi.weixin.qq.com/cgi-bin/tag/create?access_token={0}";
    /**链接-添加部门*/
    public static final String URL_ADD_DEPARTMENT = "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token={0}";
    /**链接-修改部门*/
    public static final String URL_UPDATE_DEPARTMENT = "https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token={0}";
    /**链接-删除部门*/
    public static final String URL_DELETE_DEPARTMENT = "https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token={0}&id={1}";
    /**链接-添加成员*/
    public static final String URL_ADD_USER = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token={0}";
    /**链接-更新成员*/
    public static final String URL_UPDATE_USER = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token={0}";
    /**链接-删除成员*/
    public static final String URL_DELETE_USER = "https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token={0}&userid={1}";
    /**链接-成员详情*/
    public static final String URL_INFO_USER = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={0}&userid={1}";
    /**发送消息*/
    public static final String URL_MESSAGE_SEND = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
    /*生成小程序链接*/
    public static final String URL_LINK = "https://api.weixin.qq.com/wxa/generate_urllink";
 
    /**
     * 添加工作人员
     * @param at 访问at
     * @param userId 用户id
     * @param name 名称
     * @param depId 部门id
     * @param position 职位
     * @param tel 电话
     * @param email 邮箱
     * @return 返回
     */
    public static int addUser(String at, String userId, String name, int depId
            , String position,String tel,String email) {
 
        if(StringUtils.isEmpty(tel)&&StringUtils.isEmpty(email)){
            throw new TipsException("添加企业微信手机号和邮箱不能都为空!");
        }
 
        JSONObject obj = new JSONObject();
        obj.put("userid", userId);
        obj.put("name", name);
        obj.put("department", depId);
        obj.put("position", position);
        obj.put("mobile", tel);
        obj.put("email", email);
        obj = HttpURLUtil(MessageFormat.format(URL_ADD_USER, at), obj.toString());
        if(obj != null) {
            return obj.optInt("errcode", -1);
        }
        return -1;
    }
 
    /**
     * 添加工作人员
     * @param at 访问at
     * @param userId 用户id
     * @param name 名称
     * @param depId 部门id
     * @param position 职位
     * @param tel 电话
     * @param email 邮箱
     * @return 返回
     */
    public static JSONObject addUserObj(String at, String userId, String name, int depId
            , String position,String tel,String email) {
 
        if(StringUtils.isEmpty(tel)&&StringUtils.isEmpty(email)){
            throw new TipsException("添加企业微信手机号和邮箱不能都为空!");
        }
 
        JSONObject obj = new JSONObject();
        obj.put("userid", userId);
        obj.put("name", name);
        obj.put("department", depId);
        obj.put("position", position);
        obj.put("mobile", tel);
        obj.put("email", email);
        obj = HttpURLUtil(MessageFormat.format(URL_ADD_USER, at), obj.toString());
 
        if(obj == null){
            obj = new JSONObject();
        }
 
        return obj;
 
    }
 
    /**
     * 更新工作人员
     * @param at 访问at
     * @param userId 用户id
     * @param name 名称
     * @param depId 部门id
     * @param position 职位
     * @param tel 电话
     * @param email 邮箱
     * @return 返回
     */
    public static int updateUser(String at, String userId, String name, int depId
            , String position,String tel,String email) {
        JSONObject obj = new JSONObject();
        obj.put("userid", userId);
        obj.put("name", name);
        obj.put("department", depId);
        obj.put("position", position);
        obj.put("mobile", tel);
        obj.put("email", email);
 
        obj = HttpURLUtil(MessageFormat.format(URL_UPDATE_USER, at), obj.toString());
        if(obj != null && obj.optInt("errcode", -1) == 0) {
            return obj.optInt("errcode", -1);
        }
 
        return -1;
    }
 
    /**
     * 删除工作人员
     * @param at 访问at
     * @param userId 企业用户id
     * @return 返回
     */
    public static int deleteUser(String at, String userId) {
        JSONObject obj = new JSONObject();
        obj.put("userid", userId);
 
        obj = HttpURLUtil(MessageFormat.format(URL_DELETE_USER, at,userId), obj.toString());
        if(obj != null) {
            return obj.optInt("errcode", -1);
        }
        return -1;
    }
 
    /**
     * 工作人员判断是否存在企业微信
     * @param at 访问at
     * @param userId 用户id
     * @return 返回
     */
    public static int infoUser(String at, String userId) {
        JSONObject obj = new JSONObject();
        obj.put("userid", userId);
 
        obj = HttpURLUtil(MessageFormat.format(URL_INFO_USER, at,userId), obj.toString());
 
        if(obj != null) {
            return obj.optInt("errcode", -1);
        }
        return -1;
    }
 
    /**
     * 获取企业用户信息
     * @param at 访问at
     * @param userId 用户id
     * @return 返回
     */
    public static JSONObject userData(String at, String userId) {
        JSONObject obj = new JSONObject();
        obj.put("userid", userId);
 
        return obj = HttpURLUtil(MessageFormat.format(URL_INFO_USER, at,userId), obj.toString());
    }
 
 
    /**
     * 添加部门
     * @param name 部门名称
     * @return id
     */
    public static int addDepartment(String at, String name, int parentId) {
        JSONObject obj = new JSONObject();
        obj.put("name", name);
        obj.put("parentid", parentId);
 
        obj = HttpURLUtil(MessageFormat.format(URL_ADD_DEPARTMENT, at), obj.toString());
 
        if(obj != null && obj.optInt("errcode", -1) == 0) {
            return obj.optInt("id", -1);
        }
        return -1;
    }
 
    /**
     * 更新部门
     * @param name 部门名称
     * @param deaprtId 部门id
     * @param parentid 父类部门id,可以为空
     * @return  状态,0成功
     */
    public static int updateDepartment(String at, String name, int deaprtId,int parentid) {
        JSONObject obj = new JSONObject();
        obj.put("name", name);
        obj.put("id", deaprtId);
        obj.put("parentid", parentid);
 
        obj = HttpURLUtil(MessageFormat.format(URL_UPDATE_DEPARTMENT, at), obj.toString());
        return obj.optInt("errcode", -1);
    }
 
    /**删除部门
     * 删除的部门不能是根部门且没有成员
     * @param deaprtId 部门id
     * @return 状态,0成功
     */
    public static int deleteDepartment(String at,int deaprtId) {
        JSONObject obj = new JSONObject();
        obj.put("id", deaprtId);
 
        obj = HttpURLUtil(MessageFormat.format(URL_DELETE_DEPARTMENT,at,deaprtId), obj.toString());
        System.out.println("删除部门:"+obj.toString());
        return obj.optInt("errcode", -1);
    }
 
    /**发送企业应用消息
     * @param accessToken 企业accessToken
     * @param data 发送数据结构
     * @return
     */
    public static JSONObject messageSend(String accessToken,String data){
        return HttpURLUtil(URL_MESSAGE_SEND+accessToken,data);
    }
 
    /**添加用户标签,标签名称不能重复
     * @param at 访问at
     * @param label 标签名称
     * @return 返回 -1失败,0成功,1已存在
     */
    public static int addLabel(String at, String label) {
        String url = MessageFormat.format(URL_ADD_LABEL, at);
        JSONObject obj = new JSONObject();
        obj.put("tagname", label);
        obj = HttpURLUtil(url, obj.toString());
        System.out.println("obj....:"+obj.toString());
        if(obj != null ) {
            int errcode = obj.optInt("errcode", -1);
            if( errcode== 0){
                //上传成功
                return obj.optInt("tagid", -1);
            }if(errcode == 40071){
                //标签已经存在
                return 1;
            }
        }
        return -1;
    }
 
 
    /**
     * 获取应用accessToken
     * @param corpId 企业id
     * @param appSecret 应用密钥
     * @return
     * @throws Exception
     */
    public static JSONObject getApplicationAccessToken(String corpId, String appSecret) {
        String url = MessageFormat.format(URL_GET_ACCESS_TOKEN, corpId, appSecret);
        JSONObject obj = HttpURLUtil(url, null);
        return obj;
    }
 
    /**
     * 使用临时登录凭证code获取 session_key、用户userId以及用户所在企业的corpId等信息
     * @param accessToken 访问token
     * @param code 临时code
     * @return
     */
    public static JSONObject code2Session(String accessToken, String code) {
        String url = MessageFormat.format(URL_CODE_2_SESSION, accessToken, code);
        JSONObject obj = HttpURLUtil(url, null);
        return obj;
    }
 
 
 
    /** 请求http协议 获取信息工具 **/
    public static JSONObject HttpURLUtil(String url, String data) {
        HttpURLConnection con = null;
        URL u = null;
        String wxMsgXml = null;
        JSONObject obj = null;
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setReadTimeout(5000);
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
 
            if (data != null) {
                OutputStream os = con.getOutputStream();
                os.write(data.getBytes("utf-8"));
            }
 
            if (con.getResponseCode() != 200)
                throw new RuntimeException("请求url失败");
            // 读取返回内容
            wxMsgXml = IOUtils.toString(con.getInputStream(), "utf-8");
            obj = JSONObject.fromObject(wxMsgXml);
            // //System.out.println("HttpURLUtil:"+wxMsgXml);
        } catch (Exception e) {
            e.printStackTrace();
            obj = new JSONObject();
            try {
                obj.put("status", 1);
                obj.put("errMsg", e.getMessage());
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
        return obj;
    }
 
    /**
     * 生成小程序链接
     * @param path 通过 URL Link 进入的小程序页面路径,必须是已经发布的小程序存在的页面,不可携带 query 。path 为空时会跳转小程序主页
     * @param token 接口调用凭证,该参数为 URL 参数,非 Body 参数。使用getAccessToken 或者
     * @param env_version 默认值"release"。要打开的小程序版本。正式版为 "release",体验版为"trial",开发版为"develop",仅在微信外打开时生效。
     * @param query 通过 URL Link 进入小程序时的query,最大1024个字符,只支持数字,大小写英文以及部分特殊字符:!#$&'()*+,/:;=?@-._~%
     * @return appLetInfo
     */
    public static AppLetInfo getAppLetUrl(String path, String token, String env_version, String query) {
        Map<String, Object> map = new HashMap();
        map.put("access_token", token);
        com.alibaba.fastjson.JSONObject data = new com.alibaba.fastjson.JSONObject();
        data.put("path", path);
        data.put("env_version", env_version);
        if (!StringUtils.isEmpty(query)){
            data.put("query", query);
        }
        String datas = HttpMethodUtil.HttpURLUtilJson(URL_LINK, data.toString(), map, (Map)null, "POST");
        AppLetInfo appLetInfo = com.alibaba.fastjson.JSONObject.parseObject(datas, AppLetInfo.class);
        return appLetInfo;
    }
}