how you can integrate a WeCom self-built app (自建应用机器人) with an external group chat using Java.

Here’s how you can integrate a WeCom self-built app (自建应用机器人) with an external group chat using Java.


1. Setup & Prerequisites

Get API Credentials

  1. Go to WeCom Admin PanelApp ManagementSelf-Built Apps (自建应用)
  2. Ensure the app has External Contact (外部联系人) permissions.
  3. 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

  1. Go to WeCom Admin Panel应用管理 (App Management)
  2. Select your self-built app
  3. Configure Webhook URL:

    https://your-server.com/wecom/webhook

  4. Deploy the Spring Boot app and ensure the server is publicly accessible.

Final Summary

StepAction
1Obtain CorpID, Secret, and API access token
2Fetch external group chat list (groupchat/list)
3Send messages to the external group (groupchat/send)
4Set up a webhook to receive messages (/wecom/webhook)
5Automate responses based on received messages
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值