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

Posted missccy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java调用企业微信接口给微信发消息相关的知识,希望对你有一定的参考价值。

这里的消息是企业微信和微信都能收到消息

1.注册一个企业微信,记住企业ID(我的企业-企业id)

2.应用管理--创建应用(记住AgentId和Secret)

3.下面是代码

package com.jingmai.video.live.messagecenter.utils;

/**
 * @ClassName WeChatData
 * @Description
 * @Author lyf
 * @Date 2022/2/15 15:20
 **/
public class WeChatData 
    //发送微信消息的URLString sendMsgUrl="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token= ";
    /**
     * 成员账号
     */
    private String touser;
    /**
     * 部门账号
     */
    private String  toparty;
    /**
     * 消息类型
     */
    private String msgtype;
    /**
     * 企业应用的agentID
     */
    private int agentid;
    /**
     * 实际接收Map类型数据
     */
    private 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;
    

    public String getToparty() 
        return toparty;
    

    public void setToparty(String toparty) 
        this.toparty = toparty;
    

package com.jingmai.video.live.messagecenter.utils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
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;
/**
 * @ClassName WeChatMsgSend
 * @Description
 * @Author lyf
 * @Date 2022/2/15 15:20
 **/
public class WeChatMsgSend 
    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;
    


    /**corpid应用组织编号   corpsecret应用秘钥
     * 获取toAuth(String Get_Token_Url)返回结果中键值对中access_token键的值
     * @param
     */
    public  String getToken(String corpid,String corpsecret) throws IOException 
        WeChatMsgSend sw = new WeChatMsgSend();
        WeChatUrlData uData = new WeChatUrlData();
        uData.setGet_Token_Url(corpid,corpsecret);
        String resp = sw.toAuth(uData.getGet_Token_Url());
        System.out.println("resp=====:"+resp);
        try
            Map<String, Object> map = gson.fromJson(resp,new TypeToken<Map<String, Object>>() .getType());
            return map.get("access_token").toString();
        catch (Exception e) 
            return resp;
        
    




    /**
     * @Title:创建微信发送请求post数据
     * touser发送消息接收者    ,msgtype消息类型(文本/图片等),
     * application_id应用编号。
     * 本方法适用于text型微信消息,contentKey和contentValue只能组一对
     * @return String
     */
    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);
        wcd.setText(content);
        return gson.toJson(wcd);
    


    /**
     * @Title:创建微信发送请求post数据
     * touser发送消息接收者    ,msgtype消息类型(文本/图片等),
     * application_id应用编号。
     * 本方法适用于text型微信消息,contentKey和contentValue只能组一对
     * @return String
     */
    public String createpostdataForParty(String toparty, String msgtype,
                                 int application_id, String contentKey ,String contentValue) 
        WeChatData wcd = new WeChatData();
        wcd.setToparty(toparty);
        wcd.setAgentid(application_id);
        wcd.setMsgtype(msgtype);
        Map<Object, Object> content = new HashMap<Object, Object>();
        content.put(contentKey,contentValue);
        wcd.setText(content);
        return gson.toJson(wcd);
    

    /**
     * @Title  创建微信发送请求post实体
     * charset消息编码    ,contentType消息体内容类型,
     * url微信消息发送请求地址,data为post数据,token鉴权token
     * @return String
     */
    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;
    



package com.jingmai.video.live.messagecenter.utils;

import java.io.IOException;

/**
 * @ClassName WeChatUrlData
 * @Description
 * @Author lyf
 * @Date 2022/2/15 15:21
 **/
public class WeChatUrlData 
    /**
     *  企业Id
     */
    private String corpid;
    /**
     * secret管理组的凭证密钥
     */
    private String corpsecret;
    /**
     * 获取ToKen的请求
     */
    private String Get_Token_Url;
    /**
     * 发送消息的请求
     */
    private 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;
        System.out.printf(Get_Token_Url);
    
    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;
    

    public static void main(String[] args) 
        WeChatMsgSend swx = new WeChatMsgSend();
        try 
            String token = swx.getToken( "XXX1", "XXX2");
            //给所有人发
            //String postdata = swx.createpostdata( "@all", "text", XXX3, "content", "开始巡检!");
            //给单个人发
            //String postdata = swx.createpostdata( "LiYuanFang", "text", XXX3, "content", "开始巡检!");
            //给好几个人发,用|分隔
            //String postdata = swx.createpostdata( "LiYuanFang|lying", "text", XXX3, "content", "开始巡检!");

            //给部门发
            String postdata = swx.createpostdataForParty( "XXX4", "text", XXX3, "content", "开始巡检!");
            String resp = swx.post( "utf-8", WeChatMsgSend. CONTENT_TYPE,( new WeChatUrlData()).getSendMessage_Url(), postdata, token);
            System. out.println( "获取到的token======>" + token);
            System. out.println( "请求数据======>" + postdata);
            System. out.println( "发送微信的响应数据======>" + resp);
         catch (IOException e) 
            e.printStackTrace();
        
    


修改WeChatUrlData文件main方法里参数,替换为自己企业的。这里的XXX1是上面的企业ID,XXX2是Secret,XXX3是AgentId,XXX4是部门id

LiYuanFang为账号,可以在成员详情里查看。要记得在应用的可见范围里加上企业微信的成员,他才能收到消息。

这时运行可以在企业微信里收到消息

4.如果想微信也收到代码 ,就在企业微信后台打开我的企业-微信插件,然后用微信扫描并关注二维码。再次发送消息,你的微信就也能收到了。

以上是关于java调用企业微信接口给微信发消息的主要内容,如果未能解决你的问题,请参考以下文章

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

python怎样给微信发送

java-给微信推送消息 利用企业微信

java实现微信发送消息

给微信公众号发消息,他能收到吗?

zabbix使用企业微信发消息