网上那些都是零零碎碎的,不完整,重新整理下,代码可直接使用。微信公众号消息推送大致分为两类,一是文本推送,二是带图片/视频推送。
文本推送很好理解,可以用模板消息以及自定义消息推送。
图文/视频推送就稍微麻烦些步骤分为 上传素材到临时/永久库->上传图文消息->消息推送。
贴几个官方文档,有总比没有好。
上传素材官方文档:https://developers.weixin.qq.com/doc/offiaccount/asset_management/new_temporary_materials.html
一、文本推送
这里文本推送,可以采取模板和自定义推送内容。以下是模板方式推送,在图片/视频推送中会使用自定义内容推送演示。
首先需要在微信公众号上把测试的环境弄好。
点击开发者工具->公众平台测试账号。进去创建好对应的消息模板以及关注该测试的公众号。里面会有appid/appsecret,用户,模板以及能体验接口的信息,没有认证的微信号,有些接口是没有权限的,而且部分接口在没有认证的情况下每天都会有调用次数限制。



添加依赖,因为项目里面用了自己的http封装类,需替换下
<dependency> <groupid>com.squareup.okhttp3</groupid> <artifactid>okhttp</artifactid> <version>5.0.0-alpha.14</version> </dependency> <dependency> <groupid>com.squareup.okio</groupid> <artifactid>okio</artifactid> <version>3.6.0</version> </dependency>
wxtoken
用于生成请求接口token
/**
* 存储微信公众号token的pojo类
*
* @author zjw
* @description
*/
public class wxtoken {
// 存储token信息
private string accesstoken;
// 10:00:00
// 12:00:00
// 存储当前的token有效期到什么时间点
private long expire;
public string getaccesstoken() {
// 获取token之前,需要先判断生存时间到了没
return expire == null || expire < (system.currenttimemillis() / 1000) ? null : this.accesstoken;
}
public void setaccesstoken(string accesstoken) {
this.accesstoken = accesstoken;
}
public long getexpire() {
return expire;
}
public void setexpire(long expire) {
this.expire = system.currenttimemillis() / 1000 + expire;
}
}
wxmagpushreq
这里要注意下模板的填充值data的格式,keyword1就是你在模板里面所需要替换的参数名称,后面value就是参数的值,模板里面的参数是和传入的参数需一一对应
@data
@schema(description = "微信消息推送部分用户实体")
@jsoninclude(jsoninclude.include.non_null) //这个注解是用于实体转json的时候,空值就在转换的时候排除掉
public class wxmagpushreq {
@schema(description = "用户openid")
private list<string> openidlist;
@notblank(message = "模板id不能为空")
@schema(description = "模板id")
private string templateid;
@schema(description = "模板需填充的值,keyword1就是模板里面需替换的参数名 如:{" +
" \"keyword1\":{\n" +
" \"value\":\"巧克力\"\n" +
" },\n" +
" \"keyword2\": {\n" +
" \"value\":\"39.8元\"\n" +
" },\n"+
" }")
@notblank(message = "模板需填充的值不能为空")
private string data;
}
controller
result 是自定义的返回类,换成自己的即可
/**
* 微信公众号消息推送--需选用户openid发送
*
* @return
*/
@operation(summary = "微信公众号消息推送--需选用户openid发送")
@postmapping("/wxmsgpush")
public result wxmsgpush(@requestbody @valid wxmagpushreq wxmagpushreq) {
return messageservice.wxmsgpush(wxmagpushreq);
}
service
result wxmsgpush(wxmagpushreq wxmagpushreq);
serviceimpl
因为未认证的微信群发接口无法请求,采用循环发送的方式。
@value("${weixin.msg.secret}")
private string secret;
@value("${weixin.msg.appid}")
private string appid;
private static wxtoken wxtoken = new wxtoken();
@override
public result wxmsgpush(wxmagpushreq wxmagpushreq) {
//1、拿到请求路径
string url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + gettokenstring();
if (wxmagpushreq == null || wxmagpushreq.getopenidlist().size() == 0 || stringutils.isempty(wxmagpushreq.getdata()) || stringutils.isempty(wxmagpushreq.gettemplateid())) {
throw serviceexception.error(errorcode.param_exception, "参数为空");
}
//装推送失败的openid
list<string> list = new linkedlist<>();
//传入的openid去重
list<string> collect = wxmagpushreq.getopenidlist().stream().distinct().collect(collectors.tolist());
for (string openid : collect) {
//2、请求参数
string params = "{\n" +
" \"touser\":\"" + openid + "\",\n" +
" \"template_id\":\"" + wxmagpushreq.gettemplateid() + "\",\n" +
" \"data\":" + wxmagpushreq.getdata() +
// " \"data\":{\n" +
// " \"tel\":{\n" +
// " \"value\":\"18700000000\"\n" +
// " }\n" +
// " }\n" +
" }";
httprequest request = httputil.createpost(url);
request.body(params);
string str = request.execute().body();
jsonobject json = jsonobject.parseobject(str);
integer errcode = json.getinteger("errcode");
if (0 != errcode) {
list.add(openid);
}
}
return result.ok(list);
}
//用于生成认证token
private string gettoken() {
string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
//2、基于doget方法,调用地址获取token
httprequest request = httputil.createget(url);
string resultjson = request.execute().body();
jsonobject jsonobject = jsonobject.parseobject(resultjson);
string accesstoken = jsonobject.getstring("access_token");
long expiresin = jsonobject.getlong("expires_in");
//3、存储到wxtoken对象里
wxtoken.setaccesstoken(accesstoken);
wxtoken.setexpire(expiresin);
//4、返回token
return wxtoken.getaccesstoken();
}
public string gettokenstring() {
// 从对象中获取accesstoken
string accesstoken = wxtoken.getaccesstoken();
// 获取的accesstoken为null,可能之前没获取,可能过期了
if (accesstoken == null) {
// 加锁
synchronized (wxtoken) {
// 再次判断
if (wxtoken.getaccesstoken() == null) {
gettoken();
}
}
}
return wxtoken.getaccesstoken();
}
代码中注释掉的tel就是模板中对应的参数名称。

启动项目就可以测试了,请求成功,所关注的公众号会发一条推送的信息过来。

二、图文推送
把图片/视频称为素材,带素材推送步骤。上传素材到临时/永久库->上传图文消息->消息推送。之前看社区说永久的素材库不能使用,下面的示例采用的是临时库。
注:上传素材的时候会返回media_id这个id在上传图文消息的时候需要用到,上传图文消息的时候也会返回media_id,这个id在消息推送的时候也会用到。

wxmagpushallreq
@data
@schema(description = "微信消息推送全部用户实体")
@jsoninclude(jsoninclude.include.non_null)
public class wxmagpushallreq {
@schema(description = "1-文本,2图文,当发送图文消息时,mediaid不能为空")
private string type;
// @notblank(message = "消息内容不能为空")
@schema(description = "图文mediaid")
private string mediaid;
// @notblank(message = "消息内容不能为空")
@schema(description = "消息内容")
private string content;
}
wxtuwen
@data
public class wxtuwen {
//图片media_id
@schema(description = "图片media_id")
private string thumb_media_id;
@schema(description = "图文消息的作者")
//图文消息的作者
private string author;
@schema(description = "标题")
//标题
private string title;
@schema(description = "在图文消息页面点击“阅读原文”后的页面,受安全限制,如需跳转appstore,可以使用itun.es或appsto.re的短链服务,并在短链后增加 #wechat_redirect 后缀")
//在图文消息页面点击“阅读原文”后的页面,受安全限制,如需跳转appstore,可以使用itun.es或appsto.re的短链服务,并在短链后增加 #wechat_redirect 后缀。
private string content_source_url;
@schema(description = "图文消息页面的内容")
//图文消息页面的内容,支持html标签。
private string content;
@schema(description = "图文消息的描述")
//图文消息的描述,如本字段为空
private string digest;
@schema(description = "是否显示封面,1为显示,0为不显示")
//是否显示封面,1为显示,0为不显示
private integer show_cover_pic;
}
controller
@operation(summary = "微信公众号消息推送--推送全部用户")
@postmapping("/wxmsgpushall")
public result wxmsgpushall(@requestbody @valid wxmagpushallreq wxmagpushallreq) {
return messageservice.wxmsgpushall(wxmagpushallreq);
}
@operation(summary = "微信公众号消息推送--上传临时素材")
@postmapping("/addmaterial")
public result addmaterial(@requestparam("media") multipartfile media, @requestparam("type") string type) {
return messageservice.addmaterial(media,type);
}
@operation(summary = "微信公众号消息推送--上传图文消息素材")
@postmapping("/uploadnews")
public result uploadnews(@requestbody @valid wxtuwen wxtuwen) {
return messageservice.uploadnews(wxtuwen);
}
serveice
result wxmsgpushall(wxmagpushallreq wxmagpushallreq);
result addmaterial(multipartfile media, string type);
result uploadnews(wxtuwen wxtuwen);
serviceimpl
@value("${weixin.msg.secret}")
private string secret;
@value("${weixin.msg.appid}")
private string appid;
private static wxtoken wxtoken = new wxtoken();
@override
public result wxmsgpushall(wxmagpushallreq wxmagpushallreq) {
string list = getwxuseropenid(gettokenstring(), "", "");
if (stringutils.isempty(list)) {
return result.ok();
}
string url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=" + gettokenstring();
//预览接口,可以看推送的效果
// string url = " https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=" + gettokenstring();
string params = "";
if ("1".equals(wxmagpushallreq.gettype())) {
//自定义推送内容
params = "{\n" +
" \"touser\":[" + list.substring(0, list.length() - 1) + "],\n" +
" \"msgtype\": \"text\",\n" +
" \"text\": { \"content\": \"" + wxmagpushallreq.getcontent() + "\"}" +
" }";
} else {
//带图文推送消息
params = "{\n" +
" \"touser\":[" + list.substring(0, list.length() - 1) + "],\n" +
" \"mpnews\":{\n" +
" \"media_id\":\"" + wxmagpushallreq.getmediaid() + "\"\n" +
" },\n" +
" \"msgtype\":\"mpnews\",\n" +
" \"send_ignore_reprint\":0\n" +
"}";
}
httprequest request = httputil.createpost(url);
request.body(params);
string str = request.execute().body();
system.out.println(str);
return result.ok(str);
}
@override
public result addmaterial(multipartfile media, string type) {
try {
string mediaid = uploadfile(transfertofile(media), gettokenstring(), type);
return result.ok(mediaid);
} catch (exception e) {
throw new runtimeexception(e);
}
}
@override
public result uploadnews(wxtuwen wxtuwen) {
//如需处理多个图文,修改为循环处理
string url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=" + gettokenstring();
string str = jsonobject.tojsonstring(wxtuwen);
str = "{" + "\"articles\":[" + str + "]" + "}";
httprequest request = httputil.createpost(url);
request.body(str);
string body = request.execute().body();
jsonobject jsonobject = jsonobject.parseobject(body);
return result.ok(jsonobject.getstring("media_id"));
}
//将类型multipartfile转为file类型
public file transfertofile(multipartfile file) {
try {
file convfile = new file(file.getoriginalfilename());
convfile.createnewfile();
inputstream in = file.getinputstream();
outputstream out = new fileoutputstream(convfile);
byte[] bytes = new byte[1024];
int read;
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
return convfile;
} catch (exception e) {
throw new runtimeexception();
}
}
//上传到临时库,返回一个id
public string uploadfile(file file, string accesstoken, string type) throws exception {
//临时素材地址
string url1 = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + accesstoken + "&type=" + type;
//永久素材的地址
// string url1 = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=" + accesstoken + "&type=" + type;
if (!file.exists() || !file.isfile()) {
throw new ioexception("文件不存在!");
}
url urlobj = new url(url1);
//连接
httpurlconnection conn = (httpurlconnection) urlobj.openconnection();
conn.setrequestmethod("post");
conn.setdoinput(true);
conn.setdooutput(true);
conn.setusecaches(false);
//请求头
conn.setrequestproperty("connection", "keep-alive");
conn.setrequestproperty("charset", "utf-8");
//conn.setrequestproperty("content-type","multipart/form-data;");
//设置边界
string boundary = "----------" + system.currenttimemillis();
conn.setrequestproperty("content-type", "multipart/form-data;boundary=" + boundary);
stringbuilder sb = new stringbuilder();
sb.append("--");
sb.append(boundary);
sb.append("\r\n");
sb.append("content-disposition:form-data;name=\"file\";filename=\"" + file.getname() + "\"\r\n");
sb.append("content-type:application/octet-stream\r\n\r\n");
system.out.println(sb);
byte[] head = sb.tostring().getbytes("utf-8");
//输出流
outputstream out = new dataoutputstream(conn.getoutputstream());
out.write(head);
//文件正文部分
datainputstream in = new datainputstream(new fileinputstream(file));
int bytes = 0;
byte[] bufferout = new byte[1024];
while ((bytes = in.read(bufferout)) != -1) {
out.write(bufferout, 0, bytes);
}
in.close();
//结尾
byte[] foot = ("\r\n--" + boundary + "--\r\n").getbytes("utf-8");
out.write(foot);
out.flush();
out.close();
//获取响应
stringbuffer buffer = new stringbuffer();
bufferedreader reader = null;
string result = null;
reader = new bufferedreader(new inputstreamreader(conn.getinputstream()));
string line = null;
while ((line = reader.readline()) != null) {
buffer.append(line);
}
if (result == null) {
result = buffer.tostring();
}
reader.close();
//需要添加json-lib jar包
jsonobject json = jsonobject.parseobject(result);
system.out.println(json);
string mediaid = json.getstring("thumb_media_id");
return result;
}
//根据appid和secretaccess_token
private string gettoken() {
string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
//2、基于doget方法,调用地址获取token
httprequest request = httputil.createget(url);
string resultjson = request.execute().body();
jsonobject jsonobject = jsonobject.parseobject(resultjson);
string accesstoken = jsonobject.getstring("access_token");
long expiresin = jsonobject.getlong("expires_in");
//3、存储到wxtoken对象里
wxtoken.setaccesstoken(accesstoken);
wxtoken.setexpire(expiresin);
//4、返回token
return wxtoken.getaccesstoken();
}
public string gettokenstring() {
// 从对象中获取accesstoken
string accesstoken = wxtoken.getaccesstoken();
// 获取的accesstoken为null,可能之前没获取,可能过期了
if (accesstoken == null) {
// 加锁
synchronized (wxtoken) {
// 再次判断
if (wxtoken.getaccesstoken() == null) {
gettoken();
}
}
}
return wxtoken.getaccesstoken();
}总结
到此这篇关于springboot(java)整合微信公众号消息推送的文章就介绍到这了,更多相关springboot整合微信公众号消息推送内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论