Here’s how you can integrate a WeCom self-built app (自建应用机器人) with an external group chat using Java.
1. Setup & Prerequisites
Get API Credentials
- Go to WeCom Admin Panel → App Management → Self-Built Apps (自建应用)
- Ensure the app has External Contact (外部联系人) permissions.
- Note down:
CorpID
Secret
(for External Contact API, not the general app API)AgentID
Add Required Dependencies
Include the following in your pom.xml
if using Maven:
<dependencies> <!-- Spring Boot (optional) --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.5.15</version> </dependency> <!-- HTTP Client --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> <!-- JSON Processing --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.5</version> </dependency> </dependencies>
2. Get WeCom API Access Token
Before making any API calls, obtain an access token:
Java Code
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; public class WeComUtil { private static final String CORP_ID = "your_corp_id"; private static final String SECRET = "your_external_contact_secret"; public static String getAccessToken() throws IOException { String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + CORP_ID + "&corpsecret=" + SECRET; CloseableHttpClient client = HttpClients.createDefault(); HttpGet request = new HttpGet(url); CloseableHttpResponse response = client.execute(request); String responseString = EntityUtils.toString(response.getEntity()); ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = mapper.readTree(responseString); return jsonNode.get("access_token").asText(); } public static void main(String[] args) throws IOException { System.out.println("Access Token: " + getAccessToken()); } }
3. Fetch External Group Chat List
API: /externalcontact/groupchat/list
This method retrieves all available external group chats.
Java Code
public static void getExternalGroupChats() throws IOException { String accessToken = getAccessToken(); String url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/list?access_token=" + accessToken; String requestBody = "{ \"status_filter\": 0, \"limit\": 50 }"; CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(url); post.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON)); CloseableHttpResponse response = client.execute(post); String responseString = EntityUtils.toString(response.getEntity()); System.out.println("Group Chat List: " + responseString); }
Sample Response
{ "errcode": 0, "errmsg": "ok", "group_chat_list": [ { "chat_id": "wrOgQhDgAAAbCdEfGhiJKLmn", "status": 0 } ] }
chat_id
is required for sending messages.
4. Send Messages to External Group
API: /externalcontact/groupchat/send
Now that we have the chat_id
, we can send messages.
Java Code
public static void sendGroupMessage(String chatId, String message) throws IOException { String accessToken = getAccessToken(); String url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/send?access_token=" + accessToken; String requestBody = "{" + "\"chat_id_list\": [\"" + chatId + "\"]," + "\"msgtype\": \"text\"," + "\"text\": { \"content\": \"" + message + "\" }" + "}"; CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(url); post.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON)); CloseableHttpResponse response = client.execute(post); String responseString = EntityUtils.toString(response.getEntity()); System.out.println("Send Message Response: " + responseString); } public static void main(String[] args) throws IOException { sendGroupMessage("wrOgQhDgAAAbCdEfGhiJKLmn", "Hello from Java Bot!"); }
Expected Response
{ "errcode": 0, "errmsg": "ok", "fail_list": [] }
If fail_list
is empty, the message was sent successfully.
5. Set Up a Webhook for Receiving Messages
To listen for messages from external groups, set up a Spring Boot webhook.
Java Webhook Controller
import org.springframework.web.bind.annotation.*; import java.util.Map; @RestController @RequestMapping("/wecom") public class WeComWebhookController { @PostMapping("/webhook") public Map<String, Object> handleWebhook(@RequestBody Map<String, Object> payload) { System.out.println("Received message: " + payload); // Extract group chat ID and message content String chatId = (String) payload.get("chat_id"); String sender = (String) payload.get("sender"); String content = (String) payload.get("content"); // Auto-reply if message is "Hello" if ("Hello".equalsIgnoreCase(content)) { try { sendGroupMessage(chatId, "Hi " + sender + ", how can I help?"); } catch (Exception e) { e.printStackTrace(); } } return Map.of("status", "ok"); } }
Register Webhook in WeCom
- Go to WeCom Admin Panel → 应用管理 (App Management)
- Select your self-built app
- Configure Webhook URL:
https://your-server.com/wecom/webhook
- Deploy the Spring Boot app and ensure the server is publicly accessible.
Final Summary
Step | Action |
---|---|
1 | Obtain CorpID , Secret , and API access token |
2 | Fetch external group chat list (groupchat/list ) |
3 | Send messages to the external group (groupchat/send ) |
4 | Set up a webhook to receive messages (/wecom/webhook ) |
5 | Automate responses based on received messages |