private void sendCustomWelcomeMessage(String openId) {
JSONObject article = new JSONObject();
article.put("title", "首次微信登录,请先验证");
article.put("description", "您好,首次微信登录,请先验证是否已完成注册。请点击这里进行验证:");
article.put("url", "换成自己的链接?openId=" + openId);
article.put("picurl", "照片url阿里云就行");
JSONObject news = new JSONObject();
news.put("articles", new JSONObject[]{article});
JSONObject message = new JSONObject();
message.put("touser", openId);
message.put("msgtype", "news");
message.put("news", news);
sendJsonMessageToUsers(message);
System.out.println("欢迎消息已发送给用户,OpenID: " + openId);
}
private void sendJsonMessageToUsers(JSONObject message) {
try {
String accessToken = getAccessTokenA();
String url = String.format(
"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s",
accessToken
);
String jsonPayload = message.toString();
System.out.println("发送消息的URL:" + url);
System.out.println("发送消息的内容:" + jsonPayload);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(jsonPayload, StandardCharsets.UTF_8));
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost)) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
System.out.println("消息发送成功!");
} else {
System.err.println("消息发送失败,状态码:" + statusCode);
String responseContent = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
System.err.println("响应内容:" + responseContent);
}
}
} catch (CustomAesException e) {
System.err.println("获取 AccessToken 时出错:" + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("发送 HTTP 请求时出错:" + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
System.err.println("发送消息时发生未知错误:" + e.getMessage());
e.printStackTrace();
}
}

public static String getAccessTokenA() throws CustomAesException {
String jsonResponse = HttpUtils.sendSSLGet(
accessTokenUrl,
"grant_type=" + grant_type + "&appid=" + appId + "&secret=" + appSecre,
Constants.UTF8
);
try {
JSONObject jsonObject = JSONObject.parseObject(jsonResponse);
String accessToken = jsonObject.getString("access_token");
if (accessToken == null || accessToken.isEmpty()) {
throw new RuntimeException("未能成功提取 access_token: " + jsonResponse);
}
System.out.println("提取的 access_token: " + accessToken);
return accessToken;
} catch (Exception e) {
}
return jsonResponse;
}
private static final String appId = "";
private static final String appSecre = "";
private static final String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token";
private static final String ticketUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create";
private static final String qrCodeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode";
private static final String grant_type = "client_credential";