前端开发入门到精通的在线学习网站

网站首页 > 资源文章 正文

JAVA后端推送企业微信消息到普通微信

qiguaw 2025-01-08 16:43:02 资源文章 15 ℃ 0 评论

接收消息的用户不需要安装企业微信,普通微信就可以。特殊情况开发者需要推送某些即时消息到普通微信端的时候可用,支持推送文字,图文,视频,文件,markdown,及模板等消息

# 1.申请注册企业微信(目前个人能注册)

https://work.weixin.qq.com/wework_admin/register_wx?from=myhome

# 2.添加一个应用,主要是为了拿到AgentId和Secret(下图)

# 3.查看新建应用的AgentId和Secret

# 4.查看刚才注册的企业ID

打开UC浏览器 查看更多精彩图片

# 5.腾讯企业微信的接口

腾讯企业微信API文档地址:

https://work.weixin.qq.com/api/doc/90000/90135/90664

调用流程:获取access_token -> 调用具体的API接口

# 6.编写java工具类

示例代码:

public class SendWxMessageUtil {

//新建应用的agentid

private static String agentid = "应用的agentid";

//新建应用的corpsecret

private static String corpsecret = "应用的corpsecret";

//企业ID

private static String corpid = "企业ID";

//腾讯企业微信接口:获取TOKEN地址(GET)

private static String apiGetTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret;

//腾讯企业微信接口:发送消息(POST)

private static String apiSendMessageUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";

/**

* 发送企业微信文本类消息

* @param userId 用户ID可在企业微信后台查看关注用户的ID,@all表示全体用户

* @param content 消息正文

*/

public static void sendTextMsg(String userId,String content){

String token=JSONObject.parseObject(HttpClientUtil.doGet(apiGetTokenUrl)).getString("access_token");

Map<String,Object> struct = new HashMap<>(); //要发送的消息结构体

Map<String,Object> msgcontent = new HashMap<>(); //消息正文

msgcontent.put("content",content);

struct.put("agentid",agentid); //企业微信中的小程序ID

struct.put("msgtype","text"); //消息类型,这里是text文本型

struct.put("touser",userId); //接收用户的ID,全部用户是"@all" 指定接收消息的成员,成员ID列表(多个接收者用‘|’分隔,最多支持1000个)

struct.put("text",msgcontent);

JSONObject res = JSONObject.parseObject(HttpClientUtil.doPostJson(apiSendMessageUrl + token, JSONObject.toJSONString(struct)));

System.out.println(res);//返回体:{"errcode":0,"errmsg":"ok","msgid":""} errcode为0表示成功

}

}

其中HttpClientUtil.doGet 和 HttpClientUtil.doPostJson 是封装的一个HTTP请求的工具类,网上现成的很多。

7.调用

在需要的地方调用就可以了

@RequestMapping("/sendwxmessage")

public ResultVO sendWxmMssage(){

SendWxMessageUtil.sendTextMsg("@all","测试测试");

return new ResultVO(ResultCode.SUCCESS);

}

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表