微信小程序的消息推送简单的说就是发送一条微信通知给用户,用户点开消息可以查看消息内容,可以链接进入到小程序的指定页面。
1. Preparations
First, enable the message push function on the WeChat public platform and add a message template. You can select a template from the template library or create a template. After the template is added, the template ID will be used next.
APPID applet then get keys and
dimer to open the micro-channel development tools
plus a button, the button with the function to trigger the method
,//记得添加逗号哦。
sendDYMsg: function(e) {
wx.requestSubscribeMessage({
tmplIds: ['ooaZWfK6liHpqDAcnR2hgObdQuh2JqQP2Z_UR6vvraU'],
success(res) {
console.log("可以给用户推送一条中奖通知了。。。");
}
})
}
tmplIds is the template id of your small program. Triggering this function will pop up the following box.
3. Server-side (java) code development:
1. For the old rules, first check the official website Tencent api document: https://developers.weixin.qq.com /miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html
2. Introduce a tool for WeChat development (personally feels very good, you can go and see for yourself.):
git address: https://github.com/Wechat-Group/WxJava
Mini program document address: http://binary.ac.cn/weixin-java-miniapp-javadoc/
3. Integrated pom file:
<!-- 小程序开发包-->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.1.21</version>
</dependency>
4. Obtain the openid according to the code:
code: (emphasis) can only be used once, and only valid for 5 minutes .
/*
获取openid
*/
private static String getOpenid(String code){
//临时登录凭证
String URL = "https://api.weixin.qq.com/sns/jscode2session?appid="+APPID1+"&secret="+AppSecret1+"&js_code="+code+"&grant_type=authorization_code";
String openId=interfaceUtil(URL, "");
return openId;
};
This openid must be the openid of the applet, and the other openid cannot be
5. The final link is to push the applet subscription message
The subscription message transmission parameter is different from the template message, it needs to be filled in according to other people's rules, and the regular verification is added.
Push code
/**
* 微信小程序推送订阅消息
* create By KingYiFan on 2020/09/29
*/
@GetMapping(value = "/messagePush")
@ResponseBody
public Object sendDYTemplateMessage(String openId) throws Exception {
System.err.println("openId:"+openId);
wxsmallTemplate tem = new wxsmallTemplate();
//跳转小程序页面路径
tem.setPage("pages/index/index");
//模板消息id
tem.setTemplate_id("-UBAuupYlK2RAbxYvhk6UvK48ujQD72RpEOdkF-sJ2s");
//给谁推送 用户的openid (可以调用根据code换openid接口)
tem.setToUser(openId);
//==========================================创建一个参数集合========================================================
List<wxsmallTemplateParam> paras = new ArrayList<wxsmallTemplateParam>();
//这个是满参构造 keyword1代表的第一个提示 红包已到账这是提示 #DC143C这是色值不过废弃了
wxsmallTemplateParam templateParam = new wxsmallTemplateParam(
"thing2", "红包已到账", "#DC143C");
paras.add(templateParam);
paras.add(new wxsmallTemplateParam("phrase3", "刘骞", ""));
tem.setData(paras);
//模板需要放大的关键词,不填则默认无放大
tem.setToken(getAccessToken());
//=========================================封装参数集合完毕========================================================
try {
//进行推送
//获取微信小程序配置:
if(sendTemplateMsg1(getAccess_token(APPID1,AppSecret1), tem)){
return "推送成功";
}else{
JSONObject jsonObject = new JSONObject(); //返回JSON格式数据
jsonObject.put("buTie",tem);
return jsonObject;
}
} catch (Exception e) {
e.printStackTrace();
}
return "推送失败";
}
public static boolean sendTemplateMsg1(String token,wxsmallTemplate template) {
System.err.println("token:"+token);
boolean flag = false;
String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
// String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
requestUrl = requestUrl.replace("ACCESS_TOKEN", token);
JSONObject jsonResult =JSON.parseObject(post(JSON.parseObject(template.toJSON()) ,requestUrl)) ;
if (jsonResult != null) {
Integer errorCode = jsonResult.getInteger("errcode");
String errorMessage = jsonResult.getString("errmsg");
if (errorCode == 0) {
flag = true;
} else {
System.out.println("模板消息发送失败:" + errorCode + "," + errorMessage);
flag = false;
}
}
return flag;
}
public String getAccess_token(String appid, String appsecret) {
String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appsecret;
// https://api.weixin.qq.com/cgi-bin/token.
JSONObject jsonObject = doGet1(url);
System.out.println(jsonObject.toString());
String errCode = jsonObject.getString("expires_in");
if (!StringUtils.isEmpty(errCode) && !StringUtils.isEmpty(jsonObject.getString("access_token").toString())) {
String token = jsonObject.get("access_token").toString();
return token;
} else {
return null;
}
}
public static JSONObject doGet1(String url) {
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = null;
try {
HttpResponse httpResponse = client.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, "UTF-8");
jsonObject = JSONObject.parseObject(result);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放连接
httpGet.releaseConnection();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return jsonObject;
}
//post请求
public static String post(JSONObject json,String URL) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
post.setHeader("Content-Type", "application/json");
post.addHeader("Authorization", "Basic YWRtaW46");
String result = "";
try {
StringEntity s = new StringEntity(json.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(s);
// 发送请求
HttpResponse httpResponse = client.execute(post);
// 获取响应输入流
InputStream inStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();
result = strber.toString();
System.out.println(result);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
System.out.println("请求服务器成功,做相应处理");
} else {
System.out.println("请求服务端失败");
}
} catch (Exception e) {
System.out.println("请求异常");
throw new RuntimeException(e);
}
return result;
}
So far, this is the end of the WeChat applet subscription message push, is it super simple?
Let me share with you a solution that only prompts the user once and can always send notifications without prompting next time: WeChat is set to always keep the above selections, not the inquiry button, just click the tick. The next time you click the notification function, the user will not be prompted. I clicked the button, and now I haven't found where to open this prompt.