核心逻辑:外部群消息推送的两种方式
Webhook 机器人方式(最简单):
场景:手动在群里添加机器人,获取 Webhook 地址。
限制:需要群主开启机器人权限,且外部群可能不支持直接添加(需开启“外部群插件”)。
应用 API 方式(最专业):
场景:通过自建应用,利用
chat_id主动推送。限制:需要先通过接口获取
chat_id,且该应用必须在客户联系的业务范围内。
代码实现示例
以下均以应用 API 方式 (/cgi-bin/appchat/send)为例:
1. Python 实现 (使用requests)
Python 代码最为简洁,适合做脚本或快速验证。
import requests import json def send_to_external_group(token, chat_id, text): url = f"https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token={token}" data = { "chatid": chat_id, "msgtype": "text", "text": { "content": text }, "safe": 0 } res = requests.post(url, data=json.dumps(data)) return res.json()2. Go 实现 (使用标准库)
Go 适合追求性能的中间件推送服务。
func SendGroupMsg(token string, chatId string, content string) { url := "https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token=" + token body := map[string]interface{}{ "chatid": chatId, "msgtype": "text", "text": map[string]string{"content": content}, } jsonBody, _ := json.Marshal(body) http.Post(url, "application/json", bytes.NewBuffer(jsonBody)) }3. Java 实现 (使用 RestTemplate)
Java 方案通常集成在 Spring Boot 项目中。
public void sendMsg(String token, String chatId, String text) { String url = "https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token=" + token; Map<String, Object> params = new HashMap<>(); params.put("chatid", chatId); params.put("msgtype", "text"); params.put("text", Collections.singletonMap("content", text)); restTemplate.postForEntity(url, params, String.class); }⚠️ 开发者必看的三个“坑”
获取 ChatID 的前置条件:
你不能通过群名发消息。必须先调用 externalcontact/groupchat/list 获取群列表,再通过 get 接口获取具体的 chat_id。
应用可见性:
发送消息的应用,必须在企业微信后台配置的“可调用接口的应用”列表中,且群主必须在应用的可见范围内。
发送频率:
外部群对自动化消息有严格限制。如果短时间内发送频率过高,会导致接口返回 81013 错误或直接封禁应用发送功能。
QiWe开放平台提供了后台直登功能,登录成功后获取相关参数,快速Apifox在线测试,所有登录功能都是基于QiWe平台API自定义开发。