首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

微信企業號主動發送消息接口調用流程與 Java 實現示例

     編輯:程式設計綜合問答

調用流程

  1. 獲取 Access Token:
    GET https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRET
  2. 發送消息:
    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 等。
  • 發送頻率受限,避免高頻調用觸發限流。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved