企业微信接口开发
1、
/**
* media_type 媒体文件类型,分别有图片(image)、视频(video)、普通文件(file)
* attachment_type 附件类型,不同的附件类型用于不同的场景。1:朋友圈;2:商品图册
* 上传附件资源
* @author zqd
* @date 2022/6/28
* https://qyapi.weixin.qq.com/cgi-bin/media/upload_attachment?access_token=ACCESS_TOKEN&media_type=TYPE&attachment_type=1
*/
File file = new File(filePath);
logger.log(MyLogUtil.LOG_INFO, "图片路径:ewMediaUrl = "+ filePath);
// 获取mediaId(此接口是:素材管理-上传临时素材 接口)
String bufferStr = enterpriseWechatUtils.uploadAttachment(file, "image",1);
/** * media_type 媒体文件类型,分别有图片(image)、视频(video)、普通文件(file) * attachment_type 附件类型,不同的附件类型用于不同的场景。1:朋友圈;2:商品图册 * 上传附件资源 * @author zqd * @date 2022/6/28 * https://qyapi.weixin.qq.com/cgi-bin/media/upload_attachment?access_token=ACCESS_TOKEN&media_type=TYPE&attachment_type=1 */ public String uploadAttachment(File file, String mediaType,int attachmentType){ logger.log(MyLogUtil.LOG_ERROR, "开始上传附件资源!"); String accessToken = getAccessToken(); String urlStr = "https://qyapi.weixin.qq.com/cgi-bin/media/upload_attachment?access_token="+accessToken+"&media_type="+mediaType+"&attachment_type="+attachmentType; StringBuffer buffer = new StringBuffer(); try{ //1.建立连接 URL url = new URL(urlStr); HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); //打开链接 //1.1输入输出设置 httpUrlConn.setDoInput(true); httpUrlConn.setDoOutput(true); httpUrlConn.setUseCaches(false); // post方式不能使用缓存 //1.2设置请求头信息 httpUrlConn.setRequestProperty("Connection", "Keep-Alive"); httpUrlConn.setRequestProperty("Charset", "UTF-8"); //1.3设置边界 String BOUNDARY = "----------" + System.currentTimeMillis(); httpUrlConn.setRequestProperty("Content-Type","multipart/form-data; boundary="+ BOUNDARY); // 请求正文信息 // 第一部分: //2.将文件头输出到微信服务器 StringBuilder sb = new StringBuilder(); sb.append("--"); // 必须多两道线 sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + file.length() + "\";filename=\""+ file.getName() + "\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] head = sb.toString().getBytes("utf-8"); // 获得输出流 OutputStream outputStream = new DataOutputStream(httpUrlConn.getOutputStream()); // 将表头写入输出流中:输出表头 outputStream.write(head); //3.将文件正文部分输出到微信服务器 // 把文件以流文件的方式 写入到微信服务器中 DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { outputStream.write(bufferOut, 0, bytes); } in.close(); //4.将结尾部分输出到微信服务器 byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线 outputStream.write(foot); outputStream.flush(); outputStream.close(); //5.将微信服务器返回的输入流转换成字符串 InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); // 释放资源 inputStream.close(); inputStream = null; httpUrlConn.disconnect(); } catch (Exception e) { logger.log(MyLogUtil.LOG_ERROR, "上传附件资源异常!", e); } return buffer.toString(); }
2、
/**
* 企业群发
* 开发文档对应的接口地址:https://developer.work.weixin.qq.com/document/path/92135
* 开发文档对应的接口目录:企业微信开发这中心 - 企业内部开发 - 服务端API - 客户联系 - 消息推送 - 创建企业群发
* @author zqd
* @date 2022/5/16
* @param
*/
public JSONObject groupSendToExternal(Map<String, Object> params){ logger.log(MyLogUtil.LOG_INFO, "进入创建企业群发参数:"+ JSON.toJSONString(params)); String accessToken = getAccessToken(); String chatType = String.valueOf(params.get("chatType")); List<String> externalUserid = new ArrayList<>(Arrays.asList(params.get("externalUserid").toString().split(","))); String sender = String.valueOf(params.get("sender")); String msgtype = String.valueOf(params.get("msgtype")); // 推文小程序参数拼接格式 Map<String,Object> sendParams = new HashMap<>(); sendParams.put("chat_type",chatType); sendParams.put("external_userid",externalUserid); Map<String,Object> content = new HashMap<>(); if(!"".equals(sender)){ sendParams.put("sender",sender); } content.put("content",String.valueOf(params.get("content"))); sendParams.put("text",content); List<Map<String,Object>> attachments = new ArrayList<>(); // 小程序部分的参数 if("miniprogram".equals(msgtype)){ Map<String,Object> miniprogram = new HashMap<>(); miniprogram.put("title", String.valueOf(params.get("title"))); miniprogram.put("pic_media_id",String.valueOf(params.get("mediaId"))); miniprogram.put("appid",String.valueOf(params.get("appId"))); miniprogram.put("page",String.valueOf(params.get("page"))); Map<String,Object> map = new HashMap<>(); map.put("msgtype","miniprogram"); map.put("miniprogram",miniprogram); attachments.add(map); } //图文消息的参数 if("link".equals(msgtype)){ // ... } sendParams.put("attachments",attachments); logger.log(MyLogUtil.LOG_INFO, "创建企业群发参数:"+ JSON.toJSONString(sendParams)); String url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_msg_template?access_token="+accessToken; logger.log(MyLogUtil.LOG_INFO, "企业群发开始"); JSONObject result = null; try { String resultStr = HttpClientUtil.doJsonPost(url, sendParams); logger.log(MyLogUtil.LOG_INFO, "企业群发结果:" + resultStr); result = JSONObject.parseObject(resultStr.replaceAll("'", "\'").replaceAll("\"", "'")); return result; }catch (Exception e){ logger.log(MyLogUtil.LOG_ERROR, "企业群发异常", e); result.put("errcode",500); result.put("errmsg",e.getMessage()); return result; } }
public static String doJsonPost(String url, Map<String, Object> paramMap) { CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse httpResponse = null; String result = ""; HttpPost httpPost = new HttpPost(url); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build(); httpPost.setConfig(requestConfig); httpPost.addHeader("Content-Type", "application/json;charset=UTF-8"); if (null != paramMap && paramMap.size() > 0) { String paramStr = (new JSONObject(paramMap)).toString(); paramStr = paramStr.replaceAll("\\\\u0000", ""); StringEntity se = new StringEntity(paramStr, "UTF-8"); se.setContentType("text/json"); httpPost.setEntity(se); } try { httpResponse = httpClient.execute(httpPost); HttpEntity entity = httpResponse.getEntity(); InputStream in_st = entity.getContent(); BufferedReader in = new BufferedReader(new InputStreamReader(in_st, "UTF-8")); StringBuffer buffer = new StringBuffer(); String line = ""; while((line = in.readLine()) != null) { buffer.append(line); } result = buffer.toString(); } catch (ClientProtocolException var27) { var27.printStackTrace(); } catch (IOException var28) { var28.printStackTrace(); } finally { if (null != httpResponse) { try { httpResponse.close(); } catch (IOException var26) { var26.printStackTrace(); } } if (null != httpClient) { try { httpClient.close(); } catch (IOException var25) { var25.printStackTrace(); } } } return result; }
***
获取access_token
public String getAccessToken(){ String accessToken = redisTemplateUtils.getStrValue("enterprise_wechat_accessToken"); if(accessToken != null && StringUtils.isNotBlank(accessToken)){ //如果缓存中存在Access Token,则直接从缓存中取 return accessToken; } //如果缓存中没有Access Token,通过接口获取 String ci = corpid; String cs = corpsecret; if("Y".equals(isThirdDevelop)){ cs = getPermanentCode(); logger.log(MyLogUtil.LOG_INFO, "当前是第三方代开发应用,corpsecret = " + cs); }else{ logger.log(MyLogUtil.LOG_INFO, "当前不是第三方代开发应用,corpsecret = " + cs); } String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+ci+"&corpsecret="+cs; logger.log(MyLogUtil.LOG_INFO, "获取企微Access Token"); try { String resultStr = HttpClientUtil.huGet(url); logger.log(MyLogUtil.LOG_INFO, "获取企微Access Token结果:" + resultStr); JSONObject result = JSONObject.parseObject(resultStr.replaceAll("\"", "'")); if(result.containsKey("access_token") && StringUtils.isNotBlank(result.getString("access_token"))){ //获取Access Token成功 logger.log(MyLogUtil.LOG_INFO, "Access Token:" + result.getString("access_token")); //获取Access Token后放入redis缓存,有效期为微信侧定义的有效期 redisTemplateUtils.setValue("enterprise_wechat_accessToken", result.getString("access_token"), 90 * 60); accessToken = result.getString("access_token"); }else{ logger.log(MyLogUtil.LOG_ERROR, "获取企微Access Token失败:" + result.getString("errmsg")); } }catch (Exception e){ logger.log(MyLogUtil.LOG_ERROR, "获取企微Access Token异常", e); } return accessToken; }
/** * 获取企微代开发应用永久授权码 * @Author: * @Date: 2022/4/18 */ public String getPermanentCode(){ String permanentCode = redisTemplateUtils.getStrValue("enterprise_wechat_permanentCode"); if(permanentCode != null && StringUtils.isNotBlank(permanentCode)){ //如果缓存中存在suiteAccessToken,则直接从缓存中取 return permanentCode; } String suiteAccessToken = getSuiteAccessToken(); String url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_permanent_code?suite_access_token=" + suiteAccessToken; logger.log(MyLogUtil.LOG_INFO, "取企微代开发应用永久授权码"); try { Map<String, Object> params = new HashMap<>(); String authCode = redisTemplateUtils.getStrValue("enterprise_wechat_authCode"); params.put("auth_code", authCode); logger.log(MyLogUtil.LOG_INFO, "获取企微代开发应用永久授权码参数:" + JSONObject.toJSONString(params)); String resultStr = HttpClientUtil.doJsonPost(url, params); logger.log(MyLogUtil.LOG_INFO, "获取企微代开发应用永久授权码结果:" + resultStr); JSONObject result = JSONObject.parseObject(resultStr.replaceAll("'", "\'").replaceAll("\"", "'")); if(result.containsKey("permanent_code") && StringUtils.isNotBlank(result.getString("permanent_code"))){ //获取企微代开发应用永久授权码成功 logger.log(MyLogUtil.LOG_INFO, "permanent_code:" + result.getString("permanent_code")); //获取企微代开发应用永久授权码后放入redis缓存 redisTemplateUtils.setValue("enterprise_wechat_permanentCode", result.getString("permanent_code")); // redisTemplateUtils.setValue("enterprise_wechat_accessToken", result.getString("access_token"), 90 * 60); permanentCode = result.getString("permanent_code"); }else{ logger.log(MyLogUtil.LOG_ERROR, "获取企微代开发应用永久授权码失败:" + result.getString("errmsg")); } }catch (Exception e){ logger.log(MyLogUtil.LOG_ERROR, "获取企微代开发应用永久授权码异常", e); } return permanentCode; }
/** * 获取代开发应用suite_access_token * @Author: * @Date: 2022/4/18 */ public String getSuiteAccessToken(){ String suiteAccessToken = redisTemplateUtils.getStrValue("enterprise_wechat_suiteAccessToken"); if(suiteAccessToken != null && StringUtils.isNotBlank(suiteAccessToken)){ //如果缓存中存在suiteAccessToken,则直接从缓存中取 return suiteAccessToken; } //如果缓存中没有suiteAccessToken,通过接口获取 String url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token"; logger.log(MyLogUtil.LOG_INFO, "获取企微代开发应用suite_access_token"); try { Map<String, Object> params = new HashMap<>(); String suiteId = redisTemplateUtils.getStrValue("enterprise_wechat_suiteId"); params.put("suite_id", suiteId); //第三方代开发应用的应用secret为应用模板中的secret params.put("suite_secret", corpsecret); String suiteTicket = redisTemplateUtils.getStrValue("enterprise_wechat_suiteTicket"); params.put("suite_ticket", suiteTicket); logger.log(MyLogUtil.LOG_INFO, "获取企微代开发应用suite_access_token参数:" + JSONObject.toJSONString(params)); String resultStr = HttpClientUtil.doJsonPost(url, params); logger.log(MyLogUtil.LOG_INFO, "获取企微代开发应用suite_access_token结果:" + resultStr); JSONObject result = JSONObject.parseObject(resultStr.replaceAll("'", "\'").replaceAll("\"", "'")); if(result.containsKey("suite_access_token") && StringUtils.isNotBlank(result.getString("suite_access_token"))){ //获取suite_access_token成功 logger.log(MyLogUtil.LOG_INFO, "suite_access_token:" + result.getString("suite_access_token")); //获取suite_access_token后放入redis缓存,有效期为2小时 redisTemplateUtils.setValue("enterprise_wechat_suiteAccessToken", result.getString("suite_access_token"), 120 * 60); suiteAccessToken = result.getString("suite_access_token"); }else{ logger.log(MyLogUtil.LOG_ERROR, "获取企微代开发应用suite_access_token失败:" + result.getString("errmsg")); } }catch (Exception e){ logger.log(MyLogUtil.LOG_ERROR, "获取企微代开发应用suite_access_token异常", e); } return suiteAccessToken; }