調用流程
- 獲取 Access Token:
GET https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRET
- 發送消息:
POST https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=TOKEN
Body (JSON):{
"touser": "UserID1|UserID2",
"toparty": "PartyID",
"totag": "TagID",
"msgtype": "text",
"agentid": 1000001,
"text": { "content": "您好,這是測試消息" },
"safe": 0
}
Java 代碼片段
public class WeChatWorkClient {
private static final String GET_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
private static final String SEND_MSG_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send";
public static String getAccessToken(String corpId, String corpSecret) {
String url = GET_TOKEN_URL + "?corpid=" + corpId + "&corpsecret=" + corpSecret;
// 使用 HttpClient 或 RestTemplate 發送 GET
return parseJson(response).getString("access_token");
}
public static boolean sendTextMessage(String accessToken, String toUser, int agentId, String content) {
JSONObject body = new JSONObject();
body.put("touser", toUser);
body.put("msgtype", "text");
body.put("agentid", agentId);
body.put("text", new JSONObject().put("content", content));
// POST 發送
return parseJson(response).getInt("errcode") == 0;
}
}
注意事項
- Access Token 有效期 7200 秒,建議緩存並定時刷新。
- 消息類型還支持 image、voice、video、file、news、markdown 等。
- 發送頻率受限,避免高頻調用觸發限流。