java调用企业微信接口发送消息

2022-06-04 00:00:00 调用 接口 发送消息

企业微信官网服务API地址:https://work.weixin.qq.com/api/doc/90001/90143/91201

1、注册企业微信
获取企业ID:在注册后:我的企业最下面
《java调用企业微信接口发送消息》
《java调用企业微信接口发送消息》
2、在应用管理
《java调用企业微信接口发送消息》
中创建应用
《java调用企业微信接口发送消息》
然后进入应用获取:应用id(agentID)和管理组的凭证秘钥【CorpSecret】=Secret
《java调用企业微信接口发送消息》
依赖:

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.5</version>
</dependency>

用到的UrlData类和WeChatData

 import org.springframework.stereotype.Component;

@Component
public class UrlData {
//应用组织编号(企业ID)   corpsecret应用秘钥
String corpid;
 // corpsecret应用秘钥  管理组的凭证秘钥【CorpSecret】 用的 企业号/团队号 Secret
String corpsecret;
//获取ToKen的请求
String Get_Token_Url;
//发送消息的请求
String SendMessage_Url;
public String getCorpid() {
    return corpid;
}
public void setCorpid(String corpid) {
    this.corpid = corpid;
}
public String getCorpsecret() {
    return corpsecret;
}
public void setCorpsecret(String corpsecret) {
    this.corpsecret = corpsecret;
}
public void setGet_Token_Url(String corpid,String corpsecret) {
    this.Get_Token_Url ="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpid+"&corpsecret="+corpsecret;
}
public String getGet_Token_Url() {
    return Get_Token_Url;
}
public String getSendMessage_Url(){
    SendMessage_Url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";

    return SendMessage_Url;
}

@Override
public String toString() {
    return "UrlData{" +
            "corpid='" + corpid + '\'' +
            ", corpsecret='" + corpsecret + '\'' +
            ", Get_Token_Url='" + Get_Token_Url + '\'' +
            ", SendMessage_Url='" + SendMessage_Url + '\'' +
            '}';
}
}

WeChatData 类

import org.springframework.stereotype.Component;

@Component
public class WeChatData {
//“微信消息发送”的post数据对象文件
//发送微信消息的URL
//    String sendMsgUrl="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
//成员账号
String touser;
//消息类型
String msgtype;
//企业应用的agentID
int agentid;
//实际接收Map类型数据
Object text;

public Object getText() {
    return text;
}
public void setText(Object text) {
    this.text = text;
}
public String getMsgtype() {
    return msgtype;
}
public void setMsgtype(String msgtype) {
    this.msgtype = msgtype;
}
public int getAgentid() {
    return agentid;
}
public void setAgentid(int agentid) {
    this.agentid = agentid;
}
public String getTouser() {
    return touser;
}
public void setTouser(String touser) {
    this.touser = touser;
}
}

get请求信息(请求地址可以参考官网)

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bigdata.bean.UrlData;
import com.bigdata.bean.WeChatData;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.stereotype.Component;

@Component
public class Send_weChatMsg<controller> {
//“发送微信实体”代码
private CloseableHttpClient httpClient;
private HttpPost httpPost;//用于提交登陆数据
private HttpGet httpGet;//用于获得登录后的页面
public static final String CONTENT_TYPE = "Content-Type";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//


private static Gson gson = new Gson();


/**
 * 微信授权请求,GET类型,获取授权响应,用于其他方法截取token
 * @param Get_Token_Url
 * @return String 授权响应内容
 * @throws IOException
 */
protected String toAuth(String Get_Token_Url) throws IOException {

    httpClient = HttpClients.createDefault();
    httpGet = new HttpGet(Get_Token_Url);
    CloseableHttpResponse response = httpClient.execute(httpGet);
    String resp;
    try {
        HttpEntity entity = response.getEntity();
        resp = EntityUtils.toString(entity, "utf-8");
        EntityUtils.consume(entity);
    } finally {
        response.close();
    }
    LoggerFactory.getLogger(getClass()).info(" resp:{}", resp);
    return resp;
}

/**
 * 获取toAuth(String Get_Token_Url)返回结果中键值对中access_token键的值
 * @param
 */
public   String getToken(String corpid,String corpsecret) throws IOException {
    Send_weChatMsg sw = new Send_weChatMsg();
    UrlData uData = new UrlData();
    uData.setGet_Token_Url(corpid,corpsecret);
    String resp = sw.toAuth(uData.getGet_Token_Url());

    Map<String, Object> map = gson.fromJson(resp,
            new TypeToken<Map<String, Object>>() {
            }.getType());
    return map.get("access_token").toString();
}



public String createpostdata(String touser, String msgtype,
                                int application_id, String contentKey ,String contentValue) {
    WeChatData wcd = new WeChatData();
    wcd.setTouser(touser);
    wcd.setAgentid(application_id);
    wcd.setMsgtype(msgtype);
    Map<Object, Object> content = new HashMap<Object, Object>();
    content.put(contentKey,contentValue+"\n");
    wcd.setText(content);
    return gson.toJson(wcd);
}


public String post(String charset, String contentType, String url,
                   String data,String token) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    httpPost = new HttpPost(url+token);
    httpPost.setHeader(CONTENT_TYPE, contentType);
    httpPost.setEntity(new StringEntity(data, charset));
    CloseableHttpResponse response = httpclient.execute(httpPost);
    String resp;
    try {
        HttpEntity entity = response.getEntity();
        resp = EntityUtils.toString(entity, charset);
        EntityUtils.consume(entity);
    } finally {
        response.close();
    }
    LoggerFactory.getLogger(getClass()).info(
            "call [{}], param:{}, resp:{}", url, data, resp);
    return resp;
}


//获取部门员工
public Set<String> getDepartmentData(String access_token,int department_id,int fetch_child) throws IOException {

    String Url="https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token="+access_token
            +"&department_id="+department_id+"&fetch_child="+fetch_child;

    httpClient = HttpClients.createDefault();
    httpGet = new HttpGet(Url);
    CloseableHttpResponse response = httpClient.execute(httpGet);
    String resp;
    try {
        HttpEntity entity = response.getEntity();
        resp = EntityUtils.toString(entity, "utf-8");
        EntityUtils.consume(entity);
    } finally {
        response.close();
    }
    LoggerFactory.getLogger(getClass()).info(" resp:{}", resp);
    JSONObject jsonObject = JSONObject.parseObject(resp);
    JSONArray userlist = jsonObject.getJSONArray("userlist");
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    //遍历jsonarray 数组
    if(userlist.size()>0){
        for(int i=0;i<userlist.size();i++){
            JSONObject jsonObject1 = userlist.getJSONObject(i);
            String userid = jsonObject1.get("userid").toString();
            map.put(userid,1);
        }
    }
    Set<String> useridkey = map.keySet();
    System.out.println(useridkey);
    return useridkey;
}

//获取企业微信标签下的成员
public Set<String> getTagsData(String access_token,int tags_id) throws IOException {

    String Url="https://qyapi.weixin.qq.com/cgi-bin/tag/get?access_token="+access_token+"&tagid="+tags_id;
    httpClient = HttpClients.createDefault();
    httpGet = new HttpGet(Url);
    CloseableHttpResponse response = httpClient.execute(httpGet);
    String resp;
    try {
        HttpEntity entity = response.getEntity();
        resp = EntityUtils.toString(entity, "utf-8");
        EntityUtils.consume(entity);
    } finally {
        response.close();
    }
    LoggerFactory.getLogger(getClass()).info(" resp:{}", resp);
    JSONObject jsonObject = JSONObject.parseObject(resp);
    JSONArray userlist = jsonObject.getJSONArray("userlist");
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    //遍历jsonarray 数组
    if(userlist.size()>0){
        for(int i=0;i<userlist.size();i++){
            JSONObject jsonObject1 = userlist.getJSONObject(i);
            String userid = jsonObject1.get("userid").toString();
            map.put(userid,1);
        }
    }
    Set<String> useridkey = map.keySet();
    System.out.println(useridkey);
    return useridkey;
}
}

上面是获取token的方法和get请求,然后获取成员,下面是发送消息(文本格式的),群发和单独发送

 //传入文本格式的直接发送消息,这个是发送给部门所有人 ,这里部门ID 写死了
public void send_MsgDepartment(String Msg){
    Send_weChatMsg sw = new Send_weChatMsg();
    try {
 
        String agentId = Property.getProperty("AgentId");
        String token = sw.getToken(Property.getProperty("CorpID"),Property.getProperty("Secret"));
        Set<String> departmentData = sw.getDepartmentData(token, 1, 0);
        for (String departmentDatum : departmentData) {
            String name=departmentDatum;
            String postdata = sw.createpostdata(name, "text", Integer.parseInt(agentId), "content",Msg);
            String resp = sw.post("utf-8", Send_weChatMsg.CONTENT_TYPE,(new UrlData()).getSendMessage_Url(), postdata, token);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

//单独输入信息发送,这个是发送给人(配置文件里面配置的人员)
public void send_Msgpersonnel(String Information){
    Send_weChatMsg sw = new Send_weChatMsg();
    try {
   
        String agentId = Property.getProperty("AgentId");
        String token = sw.getToken(Property.getProperty("CorpID"),Property.getProperty("Secret"));
        String userName = Property.getProperty("UserName");
        String[] split = userName.split(",");
        for (int i=0;i<split.length ;i++ ){
            String name = split[i];
            String postdata = sw.createpostdata(name, "text", Integer.parseInt(agentId), "content",Information);
            String resp = sw.post("utf-8", Send_weChatMsg.CONTENT_TYPE,(new UrlData()).getSendMessage_Url(), postdata, token);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

//发给标签下的人员 ,标签见配置文件
public void send_MsgTags(String Msg){
    Send_weChatMsg sw = new Send_weChatMsg();
    try {
    
        String agentId = Property.getProperty("AgentId");
        String token = sw.getToken(Property.getProperty("CorpID"),Property.getProperty("Secret"));
        String tags = Property.getProperty("Tags");

//            System.out.println(token);

        Set<String> tagsData = sw.getTagsData(token, Integer.parseInt(tags));
        for (String departmentDatum : tagsData) {
            String name=departmentDatum;
            String postdata = sw.createpostdata(name, "text", Integer.parseInt(agentId), "content",Msg);
            String resp = sw.post("utf-8", Send_weChatMsg.CONTENT_TYPE,(new UrlData()).getSendMessage_Url(), postdata, token);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

以上是完整版的java对企业微信发送消息

如果需要发送图片可以借鉴:https://blog.csdn.net/ruren1/article/details/89374478
https://www.cnblogs.com/shirui/p/7405944.html

    原文作者:weixing_2006
    原文地址: https://blog.csdn.net/yilushunfengli/article/details/106001146
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章