企业微信 API:主动发送外部群消息实战指南
在企业微信的开发场景中向“外部群”发送消息与向“内部群”发送消息逻辑略有不同。通常有两种主流方式群机器人Webhook最简单但需要群主开启机器人。应用消息App Chat通过自建应用调用appchat接口。注意发送外部群消息的前提是该群必须由企业成员创建且应用需要有对应的客户联系权限。1. 前置准备在编码之前你需要获取以下信息CorpID企业标识。AppSecret自建应用的密钥。ChatID外部群的群聊 ID通过“获取客户群列表”接口获取。2. Python 实现简洁高效Python 适合快速原型开发和自动化脚本。import requests import json def get_access_token(corp_id, secret): url fhttps://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid{corp_id}corpsecret{secret} res requests.get(url).json() return res.get(access_token) def send_external_group_msg(token, chat_id, content): url fhttps://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token{token} data { chatid: chat_id, msgtype: text, text: {content: content}, safe: 0 } res requests.post(url, datajson.dumps(data)) return res.json() # 调用示例 token get_access_token(YOUR_CORPID, YOUR_SECRET) print(send_external_group_msg(token, EXTERNAL_CHAT_ID, Hello from Python!))3. Go 实现并发与性能Go 语言适合处理高频的推送任务。package main import ( bytes encoding/json fmt net/http ) type Msg struct { ChatID string json:chatid MsgType string json:msgtype Text struct { Content string json:content } json:text } func sendMessage(accessToken string, chatID string, text string) { url : https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token accessToken msg : Msg{ChatID: chatID, MsgType: text} msg.Text.Content text payload, _ : json.Marshal(msg) resp, err : http.Post(url, application/json, bytes.NewBuffer(payload)) if err ! nil { fmt.Println(Error:, err) return } defer resp.Body.Close() fmt.Println(Message sent!) } func main() { // 实际开发中建议将 token 缓存避免频繁请求 sendMessage(YOUR_ACCESS_TOKEN, EXTERNAL_CHAT_ID, Hello from Go!) }4. Java 实现企业级规范Java 方案通常配合OkHttp或RestTemplate使用。import com.google.gson.JsonObject; import okhttp3.*; public class QyWechatAppChat { private static final OkHttpClient client new OkHttpClient(); public static void sendMsg(String accessToken, String chatId, String content) throws Exception { String url https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token accessToken; JsonObject text new JsonObject(); text.addProperty(content, content); JsonObject body new JsonObject(); body.addProperty(chatid, chatId); body.addProperty(msgtype, text); body.add(text, text); RequestBody requestBody RequestBody.create( body.toString(), MediaType.parse(application/json; charsetutf-8)); Request request new Request.Builder().url(url).post(requestBody).build(); try (Response response client.newCall(request).execute()) { System.out.println(response.body().string()); } } } 技术要点总结Token 缓存机制access_token有效期为 2 小时千万不要每发一条消息就请求一次 Token会导致接口触发频率限制。建议存储在 Redis 中并设置过期时间。ChatID 获取外部群的chatid与内部群不同通常需要先调用externalcontact/groupchat/list接口获取列表再根据需求匹配目标群。消息类型限制主动发送外部群消息支持text、image、voice、video、file及textcard。注意textcard文本卡片在外部群展示效果最好最常用于业务提醒。安全合规企业微信对外部群消息推送有较严格的合规审计。严禁通过该接口发送任何垃圾营销信息否则会导致自建应用甚至整个企业主体被封禁。QiWe开放平台提供了后台直登功能登录成功后获取相关参数快速Apifox在线测试所有登录功能都是基于QiWe平台API自定义开发。