使用企业微信的API给指定用户发送消息

上个月比较忙,等不忙了继续写点基础教程(五一还在高铁上写项目在)。因为公司的原因,自己学习了点JavaWeb的知识,重新写了一个简单的后台管理,用于记录用户注册信息的。其中有这样的一个要求,就是在用户注册完成之后,能发送一个提示信息,当时我第一个想法是用qq做消息提醒,但是网上找了半天,发现企鹅把相关的接口给关了,然后继续搜索发现了可以用企业微信,但是网上的一些教程不算很详细,自己还是琢磨了半天,然后今天整理一下发给大家。

首先是准备工作,几个jar包:

使用企业微信的API给指定用户发送消息

数据库和servlet看个人所需。没有的话网上搜索一下。几个相关的java文件和对应的代码

使用企业微信的API给指定用户发送消息

public class SendWX {
  //发送消息的执行方法
    public void send(String tel, String sec) {
        WeChatMsgSend swx = new WeChatMsgSend();
        try {
       //这里的token获取待会会说从哪儿具体得到 String token
= swx.getToken("wqd51b29a3fb154c92", "KWSGMIpqSmJ_wY8ettuAWafhfAdfTUKN3OParcIfaaY"); String postdata = swx.createpostdata("ErShiYi", "text", 1000002, "content", "手机号:" + tel + "\n内容:" + sec); 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 (Exception e) { e.getStackTrace(); } } }
/**
 * 微信消息发送实体类
 * @author PC-MXF
 *
 */
public class WeChatData {
    //发送微信消息的URLString sendMsgUrl="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
    /**
     * 成员账号
     */
    private String touser;

    /**
     * 消息类型
     */
    private String msgtype;

    /**
     * 企业用用的agentid
     */
    private String agentid;

    /**
     * 十几接收map类型数据
     */
    private Object text;

    public String getTouser() {
        return touser;
    }

    public void setTouser(String touser) {
        this.touser = touser;
    }

    public String getMsgtype() {
        return msgtype;
    }

    public void setMsgtype(String msgtype) {
        this.msgtype = msgtype;
    }

    public String getAgentid() {
        return agentid;
    }

    public void setAgentid(String agentid) {
        this.agentid = agentid;
    }

    public Object getText() {
        return text;
    }

    public void setText(Object text) {
        this.text = text;
    }


}
/**
 * 微信发送消息
 *
 * @author PC-MXF
 *
 */
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);
        } catch (Exception e) {
            e.getStackTrace();
        } 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) {
            e.getStackTrace();
            return resp;
        }
    }

    /**
     * 创建微信发送请求post数据 touser发送消息接收者 ,msgtype消息类型(文本/图片等), application_id应用编号。
     * 本方法适用于text型微信消息,contentKey和contentValue只能组一对
     *
     * @param touser
     * @param msgtype
     * @param application_id
     * @param contentKey
     * @param contentValue
     * @return
     */
    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实体,charset消息编码    ,contentType消息体内容类型,
     * url微信消息发送请求地址,data为post数据,token鉴权token
     * @param charset
     * @param contentType
     * @param url
     * @param data
     * @param token
     * @return
     * @throws IOException
     */
    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;
    }
}
/**
 * 微信授权请求
 * @author PC-MXF
 *
 */
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 String getGet_Token_Url() {
        return Get_Token_Url;
    }

    public void setGet_Token_Url(String corpid,String corpsecret) {
        Get_Token_Url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpid+"&corpsecret="+corpsecret;
    }

    public String getSendMessage_Url() {
        SendMessage_Url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
        return SendMessage_Url;
    }

    public void setSendMessage_Url(String sendMessage_Url) {
        SendMessage_Url = sendMessage_Url;
    }


}

相关的代码准备完成之后,开始创建企业微信,打开企业微信官网:https://work.weixin.qq.com/注册,并登陆。点击应用与小程序,自建里面创建应用:

使用企业微信的API给指定用户发送消息

然后进入自己创建的应用,找到这两个信息,

使用企业微信的API给指定用户发送消息

分别对应的是

使用企业微信的API给指定用户发送消息

然后打开我的企业最下面有个企业ID

使用企业微信的API给指定用户发送消息

使用企业微信的API给指定用户发送消息

对应的是上面的getToken()第一个参数。下面的swx.createpostdata方法的第一个参数是用户名称,打开通讯录:

使用企业微信的API给指定用户发送消息

点进去你想要给他发送消息的公司成员:

使用企业微信的API给指定用户发送消息

这个账号即为用户的名称,修改为自己想要的。就可以发送文本信息。还有其他的相关的功能,可以自己去查看一下企业微信API寻找,比如发送图片等。

 

使用企业微信的API给指定用户发送消息

上一篇:微信小程序实现获取用户信息并存入数据库操作示例


下一篇:微信公众号数据抓取