QiWe开放平台提供了后台直登功能,登录成功后获取相关参数,快速Apifox在线测试,所有登录功能都是基于QiWe平台API自定义开发。
核心前提:获取chat_id
外部群消息发送的前提是:你的应用(自建应用或代开发应用)必须已经获取到了该群的chat_id。
通常通过
客户群列表查询接口获取。外部群消息必须由配置了“客户联系”权限的人员创建或所在。
1. Python 实现(轻量化)
使用requests库,适合脚本任务或快速集成。
import requests import json def send_to_external_group(access_token, chat_id, text_content): # 企业微信应用推送接口 url = f"https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token={access_token}" payload = { "chatid": chat_id, "msgtype": "text", "text": { "content": text_content } } try: response = requests.post(url, data=json.dumps(payload)) result = response.json() if result.get("errcode") == 0: print("消息发送成功") else: print(f"发送失败: {result.get('errmsg')}") except Exception as e: print(f"请求异常: {e}")2. Go 实现(高性能)
利用结构体序列化,适合高并发推送场景。
package main import ( "bytes" "encoding/json" "fmt" "net/http" ) type WeChatMsg struct { ChatID string `json:"chatid"` MsgType string `json:"msgtype"` Text struct { Content string `json:"content"` } `json:"text"` } func SendExternalGroupMsg(token string, chatId string, content string) { url := "https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token=" + token msg := WeChatMsg{ ChatID: chatId, MsgType: "text", } msg.Text.Content = content jsonData, _ := json.Marshal(msg) resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("请求错误: %v\n", err) return } defer resp.Body.Close() fmt.Println("响应状态:", resp.Status) }3. Java 实现(企业级)
使用RestTemplate或OkHttp,建议配合Jackson处理数据。
public void sendWechatMsg(String accessToken, String chatId, String message) { String url = "https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token=" + accessToken; // 构建请求体 Map<String, Object> body = new HashMap<>(); body.put("chatid", chatId); body.put("msgtype", "text"); Map<String, String> textContent = new HashMap<>(); textContent.put("content", message); body.put("text", textContent); // 发送请求 (以 RestTemplate 为例) RestTemplate restTemplate = new RestTemplate(); String result = restTemplate.postForObject(url, body, String.class); System.out.println("接口返回: " + result); }🛠️ 关键避坑指南
1. 接口选择:Webhook vs 应用 API
群机器人 (Webhook):如果是为了方便,且群成员愿意手动添加机器人,直接用 Webhook 最简单。
应用 API (
appchat/send):如果是为了程序化大规模管理,必须用此接口。注意:外部群的chatid获取权限较严,需要应用在客户联系范围内。
2. AccessToken 的缓存
千万不要每次发消息都重新获取access_token。它的有效期是 2 小时,频繁调用会导致接口被封禁。建议在 Redis 中缓存。
3. 外部群的特殊限制
敏感词:外部群消息受到腾讯更严格的语义过滤。
频率限制:对同一个外部群的推送不宜过快(建议单群每秒不超过 1 条),否则会触发风控。
可见性:只有应用在配置的“可见范围”内的成员,才能作为群主或成员正常触发消息。