前言

企业微信的开发有很多api,其中较常用的api则是关于通过企业微信,向企业内的人员发送消息,以下针对发送消息这里,讲解如何简单的实现向企业微信发送消息。

项目结构

本次采用的是maven项目的结构,纯后端实现向企业微信的成员发送消息
以下为项目的结构
在这里插入图片描述

由于只是简单的发送信息,并没有涉及到数据库
所以只有这四个部分:
api文件夹:具体的功能实现代码
utils文件夹:工具栏,连接企业微信和重置token功能
App.java启动类:启动项目
pom.xml:导入依赖

当然,实际开发的话,肯定是会涉及到数据库的,需要连接数据库的,建议看看我之前的博客文章。

企业微信

在正式开始之前,有一个很重要的事情需要做,那就是你需要有一个企业微信,不管是加入还是说自己创建。
因为发送企业微信信息是需要企业微信的id的,还有应用的secret和应用id信息。
我这里给大家讲一下,如何创建企业自己的企业微信。
第一种在手机端下载企业微信,打开企业微信列表处选择创建
在这里插入图片描述

需要注意的是,创建要选择企业类型

在这里插入图片描述
第二种就是电脑端,打开企业微信的网址进行创建
企业微信入口

然后在企业微信的管理端进行查看企业微信的企业id
企业微信管理端
在这里插入图片描述
登录后点击我的企业-企业信息下滑到最下面,就可以看到企业微信id
在这里插入图片描述
需要注意,要把自己的企业id保存好,不要泄露,否则有安全隐患

创建企业微信应用

这里的教学方式是把信息发送到应用里,毕竟企业微信可以有很多地方可以接收到信息,你必须要指定一个位置进行接收才可以

在企业微信的管理端,选择应用,下滑到最下面可以创建应用
在这里插入图片描述
创建完应用后,打开刚刚创建的应用,就可以看到agentId和secret
需要记住这两个
在这里插入图片描述

应用和依赖

创建完之前,你还需要有安装redis,启动本地redis即可

然后就是pom.xml依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.hxc</groupId>
    <artifactId>sendMessageToqywx</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
<!--        企业微信配置依赖-->
        <dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>weixin-java-cp</artifactId>
            <version>4.0.8.B</version>
        </dependency>
<!--        redis依赖-->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.6.0</version>
        </dependency>
<!--        fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>
    </dependencies>
</project>

utils工具类

这个工具类是配置企业微信服务的,以及检测和重置token
WxCongfig.java代码:

package utils;

import com.alibaba.fastjson.JSON;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author hxc
 * 推送企业微信配置
 * */
public class WxConfig {
    private static Integer agentId=1000002;
    private static String secret="企业微信应用secret";
    private static String corpId="企业微信id";
    // 配置企业微信服务
    public static WxCpService getWxCpService() {
        WxCpService wxCpService=new WxCpServiceImpl();
        WxCpDefaultConfigImpl config =new WxCpDefaultConfigImpl();
        config.setAgentId(agentId);
        config.setCorpSecret(secret);
        config.setCorpId(corpId);
        resetTokenAndJsApi(wxCpService,config);
        return wxCpService;
    }
// 重置token
    public static void resetTokenAndJsApi(WxCpService wxCpService,WxCpDefaultConfigImpl wxCpDefaultConfig) {
    // 配置redis
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(8);
        jedisPoolConfig.setMaxTotal(18);
        // redis启动后,默认启动的是6379端口,和我的一样即可
        Jedis jedis =new JedisPool(jedisPoolConfig,"localhost",6379,5000).getResource();

        wxCpService.setWxCpConfigStorage(wxCpDefaultConfig);
        String wxAccessToken = "wx"+agentId;
        String json=jedis.get(wxAccessToken);
        if(!StringUtils.isEmpty(json)){
            wxCpDefaultConfig = JSON.parseObject(json,WxCpDefaultConfigImpl.class);
        }
        if(wxCpDefaultConfig.isAccessTokenExpired()){
            try {
                String accessToken = null;
                accessToken =wxCpService.getAccessToken(false);
                wxCpDefaultConfig.setAccessToken(accessToken);
            }catch (WxErrorException e){
                e.printStackTrace();
            }
        }
        if(wxCpDefaultConfig.isJsapiTicketExpired()){
            String jsApi = null;
            try {
                jsApi = wxCpService.getJsapiTicket();
                wxCpDefaultConfig.setJsapiTicket(jsApi);
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
        }
        jedis.set(wxAccessToken,JSON.toJSONString(wxCpDefaultConfig));
        jedis.close();
    }
}

功能实现

前面的工作都做完了,就差发送信息了,这里就涉及到另一个问题,发送信息给谁?
所以,就需要知道企业微信的userId
每一个加入企业微信的成员都是有一个userId的,同样,打开企业微信管理端,点击通讯录可以查看成员的userId
如我的为HuangXianChun,emmm,默认为我的姓名的拼音缩写。。。。

然后就是发送信息的功能代码:

package api;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.impl.WxCpMessageServiceImpl;
import me.chanjar.weixin.cp.bean.message.WxCpMessage;
import utils.WxConfig;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * 发送消息功能代码
 * */
public class sendMessage {
    public static void SendToWx()throws WxErrorException {
        //微信消息对象
        WxCpMessageServiceImpl wxCpMessageService = new WxCpMessageServiceImpl(WxConfig.getWxCpService());
        WxCpMessage wxCpMessage = new WxCpMessage();
        wxCpMessage.setSafe("0");
        wxCpMessage.setMsgType("textcard");

        //发送给用户:userid

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String time=sdf.format(new Date());
        //设置发送用户
        wxCpMessage.setToUser("HuangXianChun");
        //发送的标题
        wxCpMessage.setTitle("测试");
        //发送内容
        wxCpMessage.setDescription("测试文本内容"
                +"\n"+"当前时间为:"
                +time+"\n"
                +"点击下方前往企业微信api说明");
        //设置跳转url:www.baidu.com
        wxCpMessage.setUrl("https://work.weixin.qq.com/api/doc/90000/90135/91025");
        wxCpMessage.setBtnTxt("api");
        wxCpMessageService.send(wxCpMessage);

    }
}

我在这里设置的发送文本为卡片形式,即textcard,一般可以根据api文档选择自己需要的进行设置。
api文档链接:
企业微信api

启动类

最后就是启动类的main方法了。
代码:

import api.sendMessage;
import me.chanjar.weixin.common.error.WxErrorException;

public class App {
    /**
     * 启动类
     *
     * */
    //实例化
    private static sendMessage message;
    public static void main(String[] args)throws WxErrorException {
        message=new sendMessage();
        try{
            message.SendToWx(); 
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}

最终效果:
在这里插入图片描述

结语

以上,就是企业微信的发送信息的简单应用,后面根据情况对企业微信的api进行进一步的讲解

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐