上一篇
企业微信Java消息推送如何实现
- 后端开发
- 2025-06-10
- 2262
使用Java在企业微信中推送消息需调用其API:先通过企业ID和密钥获取access_token,再用HTTP客户端(如OkHttp)向消息接口发送JSON格式请求体,包含目标用户和消息内容即可实现推送。
<p>企业微信作为高效的办公沟通工具,其消息推送功能可应用于系统告警、任务通知、数据报告等场景,下面详细介绍Java实现企业微信消息推送的技术方案:</p> <h3>一、准备工作</h3> <ol> <li><strong>创建企业微信应用</strong> <ul> <li>登录<a href="https://work.weixin.qq.com/" target="_blank">企业微信管理后台</a></li> <li>进入「应用管理」→「自建应用」→「创建应用」</li> <li>记录关键参数:<code>AgentId</code>(应用ID)、<code>Secret</code>(应用密钥)、<code>CorpId</code>(企业ID)</li> </ul> </li> <li><strong>配置应用权限</strong> <ul> <li>在应用详情页配置「可见范围」(指定接收消息的成员/部门)</li> <li>开启「接收消息」API权限</li> </ul> </li> </ol> <h3>二、Java实现步骤(Spring Boot示例)</h3> <h4>1. 添加Maven依赖</h4> <pre><code class="language-xml"><dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.83</version> </dependency></code></pre> <h4>2. 获取AccessToken</h4> <pre><code class="language-java">public String getAccessToken(String corpId, String secret) throws IOException { String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpId + "&corpsecret=" + secret; CloseableHttpClient client = HttpClients.createDefault(); HttpGet get = new HttpGet(url); try (CloseableHttpResponse response = client.execute(get)) { HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); JSONObject json = JSONObject.parseObject(result); return json.getString("access_token"); // 有效期7200秒 } }</code></pre> <h4>3. 构造消息体(文本+Markdown示例)</h4> <pre><code class="language-java">// 文本消息体 String textMsg = JSONObject.toJSONString(new HashMap<>() {{ put("touser", "@all"); // 接收人 put("msgtype", "text"); put("agentid", agentId); put("text", new HashMap<>() {{ put("content", "服务器CPU使用率超过90%!"); }}); }}); // Markdown消息体 String markdownMsg = JSONObject.toJSONString(new HashMap<>() {{ put("touser", "User1|User2"); put("msgtype", "markdown"); put("agentid", agentId); put("markdown", new HashMap<>() {{ put("content", "**实时监控报告**\n> 时间: " + new Date() + "\n> 状态: <font color=\"warning\">警告</font>"); }}); }});</code></pre> <h4>4. 发送消息请求</h4> <pre><code class="language-java">public void sendMessage(String accessToken, String messageJson) throws IOException { String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken; CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(url); post.setHeader("Content-Type", "application/json"); post.setEntity(new StringEntity(messageJson, StandardCharsets.UTF_8)); try (CloseableHttpResponse response = client.execute(post)) { String result = EntityUtils.toString(response.getEntity()); JSONObject json = JSONObject.parseObject(result); if (json.getIntValue("errcode") != 0) { throw new IOException("发送失败: " + json.getString("errmsg")); } } }</code></pre> <h3>三、完整调用示例</h3> <pre><code class="language-java">public void sendWechatAlert() { String corpId = "XXXXXX"; // 替换企业ID String secret = "YYYYYY"; // 替换应用密钥 int agentId = 1000002; // 替换应用ID try { String token = getAccessToken(corpId, secret); String msg = JSONObject.toJSONString(new HashMap<>() {{ put("touser", "@all"); put("msgtype", "text"); put("agentid", agentId); put("text", new HashMap<>() {{ put("content", "订单支付成功通知:\n订单号:202208150001\n金额:¥299.00"); }}); }}); sendMessage(token, msg); } catch (Exception e) { e.printStackTrace(); // 实际项目中应记录日志 } }</code></pre> <h3>四、常见问题处理</h3> <table border="1"> <tr> <th>错误码</th> <th>原因</th> <th>解决方案</th> </tr> <tr> <td>40001</td> <td>Secret错误或Token失效</td> <td>检查Secret配置,重新获取Token</td> </tr> <tr> <td>41007</td> <td>消息格式错误</td> <td>使用<a href="https://www.json.cn/" target="_blank">JSON校验工具</a>验证消息体</td> </tr> <tr> <td>60011</td> <td>权限不足</td> <td>检查应用可见范围是否包含接收人</td> </tr> </table> <h3>五、安全建议</h3> <ul> <li>将<code>Secret</code>存储在环境变量或配置中心,<strong>禁止硬编码在代码中</strong></li> <li>AccessToken需缓存复用(推荐Redis),避免频繁请求触发限流</li> <li>敏感消息内容进行加密传输</li> <li>设置IP白名单:企业微信后台「应用管理」→「权限管理」→「企业可信IP」</li> </ul> <h3>六、扩展能力</h3> <p>除文本消息外,企业微信还支持:</p> <ol> <li><strong>图文消息</strong>:发送带图片和链接的卡片</li> <li><strong>文件消息</strong>:上传临时素材发送文件</li> <li><strong>模板卡片</strong>:交互式消息按钮(需企业微信3.1+)</li> <li><strong>Webhook机器人</strong>:通过群机器人快速推送(无需创建应用)</li> </ol> <p>通过以上步骤,可快速实现企业级消息推送系统,建议阅读<a href="https://developer.work.weixin.qq.com/document/path/90236" target="_blank">官方文档-消息类型</a>获取最新规范。</p> <small>引用说明:本文代码示例基于企业微信API 4.1.0版本,部分参数需根据实际业务调整,官方接口更新请以<a href="https://developer.work.weixin.qq.com/document/path/90665" target="_blank">企业微信开发者文档</a>为准。</small>