QyWebChatUtil.java 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package jnpf.util.third;
  2. import com.alibaba.fastjson.JSONObject;
  3. import jnpf.util.wxutil.HttpUtil;
  4. /**
  5. * 企业微信的接口类
  6. *
  7. * @版本: V3.1.0
  8. * @版权: 引迈信息技术有限公司(https://www.jnpfsoft.com)
  9. * @作者: JNPF开发平台组
  10. * @日期: 2021/4/21 8:20
  11. */
  12. public class QyWebChatUtil {
  13. /**
  14. * 获取企业微信TOKEN的接口路径
  15. */
  16. public static final String TOKEN = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s";
  17. /**
  18. * 往企业微信发送消息的接口路径
  19. */
  20. public static final String SEND_MESSAGE = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s";
  21. /**
  22. * 获取接口访问凭证
  23. */
  24. public static JSONObject getAccessToken(String corpId, String corpSecret) {
  25. JSONObject retMsg = new JSONObject();
  26. JSONObject rstObj = HttpUtil.httpRequest(String.format(TOKEN,corpId, corpSecret), "GET", null);
  27. // JSONObject rstObj = HttpUtil.httpsRequest(QyApi.getTokenUrl(corpId, corpSecret), "GET", null);
  28. return rstObj;
  29. }
  30. /**
  31. * 发送消息 20210416 Add By GongXishan
  32. * 不抛出异常,返回Json
  33. */
  34. public static JSONObject sendMessage(String message, String accessToken){
  35. JSONObject retMsg = new JSONObject();
  36. boolean codeFlag = true;
  37. String errorMsg = "";
  38. JSONObject rstObj = HttpUtil.httpRequest(String.format(SEND_MESSAGE, accessToken), "POST", message);
  39. // JSONObject rstObj = HttpUtil.httpsRequest(QyApi.sendMessage(accessToken), "POST", message);
  40. if (HttpUtil.isWxError(rstObj)) {
  41. codeFlag = false;
  42. errorMsg = rstObj.toString();
  43. }
  44. retMsg.put("code",codeFlag);
  45. retMsg.put("error",errorMsg);
  46. return retMsg;
  47. }
  48. /**
  49. * 向企业微信发送信息
  50. * @param corpId
  51. * @param corpSecret
  52. * @param agentId
  53. * @param toUserId
  54. * @param contents
  55. * @return
  56. */
  57. public static JSONObject sendWxMessage(String corpId,String corpSecret,String agentId,String toUserId,String contents) {
  58. JSONObject retMsg = null;
  59. JSONObject message = null;
  60. JSONObject tokenObject = null;
  61. JSONObject content = null;
  62. message = new JSONObject();
  63. message.put("touser", toUserId);
  64. message.put("agentid", agentId);
  65. content = new JSONObject();
  66. content.put("content", contents);
  67. message.put("text", content);
  68. message.put("msgtype", "text");
  69. tokenObject = getAccessToken(corpId, corpSecret);
  70. if(tokenObject.getString("access_token")!=null && !"".equals(tokenObject.getString("access_token"))){
  71. retMsg = sendMessage(message.toJSONString(), tokenObject.getString("access_token"));
  72. }else
  73. {
  74. retMsg.put("code",false);
  75. retMsg.put("error","access_token值为空,不能发送信息!");
  76. }
  77. return retMsg;
  78. }
  79. }