QiWe开放平台提供了后台直登功能,登录成功后获取相关参数,快速Apifox在线测试,所有登录功能都是基于QiWe平台API自定义开发。
核心前提
-
获取 ChatID :你不能直接通过群名发送。必须先通过"获取客户群列表"接口获取外部群的
chatid。 -
应用权限:你的自建应用必须在"客户联系"的业务范围内。
-
AccessToken :所有请求都需要有效的
access_token。
1. Python 实现 (使用 requests)
适用于快速脚本或轻量级后台。
python
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
},
"safe": 0
}
try:
response = requests.post(url, data=json.dumps(payload))
result = response.json()
if result.get("errcode") == 0:
print("消息发送成功")
else:
print(f"发送失败: {result}")
except Exception as e:
print(f"请求异常: {e}")
# 调用示例
# send_to_external_group("YOUR_TOKEN", "wrOgQhDgAA...", "Hello WeCom!")
2. Go 实现 (原生 http)
适用于高性能微服务场景。
Go
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
type WeChatMessage struct {
ChatID string `json:"chatid"`
MsgType string `json:"msgtype"`
Text struct {
Content string `json:"content"`
} `json:"text"`
}
func SendGroupMsg(token string, chatId string, content string) error {
apiURL := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token=%s", token)
msg := WeChatMessage{
ChatID: chatId,
MsgType: "text",
}
msg.Text.Content = content
body, _ := json.Marshal(msg)
resp, err := http.Post(apiURL, "application/json", bytes.NewBuffer(body))
if err != nil {
return err
}
defer resp.Body.Close()
// 解析返回结果可根据业务需求进一步处理
return nil
}
3. Java 实现 (使用 RestTemplate)
适用于 Spring Boot 项目。
Go
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
public class WeComService {
private final RestTemplate restTemplate = new RestTemplate();
public void sendMessage(String token, String chatId, String content) {
String url = "https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token=" + token;
// 构建请求体
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("chatid", chatId);
requestBody.put("msgtype", "text");
Map<String, String> textNode = new HashMap<>();
textNode.put("content", content);
requestBody.put("text", textNode);
try {
Map<String, Object> response = restTemplate.postForObject(url, requestBody, Map.class);
if (response != null && "0".equals(response.get("errcode").toString())) {
System.out.println("发送成功");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
避坑与进阶指南
-
群 ID 的坑 :外部群的
chatid与内部群格式不同。如果是通过"客户联系"接口获取的,通常以wr开头。 -
发送频率限制 :企业微信对主动向外部群推送消息有严格频率限制。如果短时间内发送过多,接口会返回
45009(接口调用超过限制)。 -
群机器人(Webhook) vs 应用消息:
-
如果你只是想往某个固定的外部群发通知,群机器人最简单,无需编写复杂的 Token 维护逻辑。
-
如果你需要程序化、动态地给不同的外部群发消息,必须走上述 应用 API 流程。
-
您是否需要我为您演示如何通过代码自动获取外部群的 chatid 列表?