微信小程式訂閱消息開髮指南(java) 第一步 準備階段 1、你得有一個小程式,並且認證了,個人的也行 2、開通訂閱消息 小程式後臺->功能->訂閱消息 3、公共模板庫選擇一個模板 選擇的時候,選擇你需要的欄位,因為欄位有限制 4、我的模板點擊詳情 詳情內容,模板 id 都是需要提供個服務端開發人員 ...
微信小程式訂閱消息開髮指南(java)
第一步 準備階段
1、你得有一個小程式,並且認證了,個人的也行
2、開通訂閱消息
小程式後臺
->功能
->訂閱消息
3、公共模板庫選擇一個模板
選擇的時候,選擇你需要的欄位,因為欄位有限制
4、我的模板點擊詳情
詳情內容,模板 id 都是需要提供個服務端開發人員的
第二步 編碼階段
小程式端
小程式消息訂閱,需要用戶確認
1、首先小程式授權登陸獲取 code
官網示例:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
wx.login({
success (res) {
if (res.code) {
//發起網路請求
wx.request({
url: 'https://example.com/onLogin',
data: {
code: res.code
}
})
} else {
console.log('登錄失敗!' + res.errMsg)
}
}
})
// 結果 {errMsg: "login:ok", code: "0a3kK4Ga10Gk3F0oBAHa1mGyRl3kK4Gd"}
uni-App 示例:https://uniapp.dcloud.net.cn/api/plugins/login.html#login
uni.login({
provider: 'weixin', //使用微信登錄
success: function (loginRes) {
console.log(loginRes)
}
});
// 結果 {errMsg: "login:ok", code: "0a3kK4Ga10Gk3F0oBAHa1mGyRl3kK4Gd"}
2、將 code
傳給服務端 獲取用戶唯一標識 openId
3、通過代碼起小程式消息訂閱界面、用戶點擊確定ok,小程式工作結束
tmplIds
填寫模板 id 即可,最多三個
wx.requestSubscribeMessage({
tmplIds: [''],
success (res) {
console.log(res)
}
})
4、註意事項:
避免重覆拉起用戶訂閱通知,可以通過微信提供的
getSetting
判斷用戶是否訂閱了,如果沒有就拉起。註意下麵是用
uniapp
寫的,方法首碼是uni
如果你小程式代碼記得修改wx
以及提示組件到此小程式工作結束
getSetting() {
uni.getSetting({
withSubscriptions: true, // 獲取用戶訂閱狀態
success(res) {
// false 表示用戶未訂閱改消息
if (!res.subscriptionsSetting.mainSwitch) {
this.subscribeMessage();
} else {
uni.showToast({
title: '已訂閱',
icon: 'none'
})
}
}
})
},
subscribeMessage() {
uni.requestSubscribeMessage({
tmplIds: ['模板id'],
success(res) {
if (res.errMsg === 'requestSubscribeMessage:ok') {
uni.showToast({
title: '訂閱成功',
icon: 'none'
})
}
}
})
}
服務端
微信小程式的
appid
和secret
小程式後臺
->開發
->開發管理
->開發設置
->開發者 ID
註意事項:
http
請求這裡使用 apache 的工具類,你也可以使用別的- 微信消息模板欄位
thing
欄位有長度限制20,超過會失敗 - 以下演示代碼,生產環境還需進行優化
1、通過 code 獲取用戶 open id 官網文檔
public String getOpenId(String code) throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
Map<String, Object> params = new HashMap<>();
params.put("appid", Constants.APPLET_APP_ID);
params.put("secret", Constants.APPLET_SECRET);
params.put("js_code", code);
params.put("grant_type", "authorization_code");
String url = handleParams("https://api.weixin.qq.com/sns/jscode2session", params);
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity(); // 響應結果
return EntityUtils.toString(entity, CharSetType.UTF8.getType());
}
public static void main(String[] args) throws IOException {
HttpUtils httpUtils = new HttpUtils();
String token = httpUtils.getToken();
System.out.println(token);
}
響應結果:
{"access_token":"67_u22CQaWq22222222Q4griDE6kiT5hwg7jVxedn8J9te17Az1oWGGxPgB22222229Y4Wm6h_Yzci7-FSDjeH8YG6DsCOYrQXJCWsPXhT6nWbKIWCXfABACID","expires_in":7200}
2、通過 appid
和 secret
獲取 token 超時 7200 秒 可 redis 緩存 官方文檔
public String getToken() throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
Map<String, Object> params = new HashMap<>();
params.put("appid", Constants.APPLET_APP_ID);
params.put("secret", Constants.APPLET_SECRET);
params.put("grant_type", "client_credential");
String url = handleParams("https://api.weixin.qq.com/cgi-bin/token", params);
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity(); // 響應結果
return EntityUtils.toString(entity, CharSetType.UTF8.getType());
}
3、指定用戶推送消息結束 官方文檔
public String pushMsg(String token) throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
Map<String, Object> params = new HashMap<>();
// 處理微信推送數據結構
JSONObject mapData = new JSONObject();
Map<String, Object> map1 = new HashMap<>();
map1.put("value", "任務名稱");
mapData.put("thing2", map1);
Map<String, Object> map2 = new HashMap<>();
map2.put("value", "2022-04-03 10:00:00");
mapData.put("time3", map2);
Map<String, Object> map3 = new HashMap<>();
map3.put("value", "描述信息");
mapData.put("thing4", map3);
Map<String, Object> map4 = new HashMap<>();
map4.put("value", "備註信息");
mapData.put("thing10", map4);
Map<String, Object> map5 = new HashMap<>();
map5.put("value", "任務來源");
mapData.put("thing11", map5);
params.put("template_id", "templateId");// 模板 id
params.put("touser", "openId"); // open id
params.put("data", mapData); // 數據
params.put("page", "page"); // 點擊模板卡片後的跳轉頁面,僅限本小程式內的頁面。支持帶參數,(示例index?foo=bar)。該欄位不填則模板無跳轉
params.put("miniprogram_state", "trial"); //developer為開發版;trial為體驗版;formal為正式版;預設為正式版
params.put("lang", "zh_CN"); //
HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token);
httpPost.addHeader("ContentTyp", "application/json");
// 參數轉 JSON 格式
String json = objToStr(params);
StringEntity stringEntity = new StringEntity(json, CharSetType.UTF8.getType());
stringEntity.setContentEncoding(CharSetType.UTF8.getType());
httpPost.setEntity(stringEntity);
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity(); // 響應結果
return EntityUtils.toString(entity, CharSetType.UTF8.getType());
}
4、完整代碼
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.chenlijia1111.utils.core.enums.CharSetType;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.jeecg.modules.video.utitls.Constants;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @description:
* @author: Mr.Fang
* @create: 2023-04-03 17:06
**/
public class HttpUtils {
/**
* description: 獲取token,返回結果為 JSON 自行轉 map
* create by: Mr.Fang
*
* @return: java.lang.String
* @date: 2023/4/3 17:46
*/
public String getToken() throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
Map<String, Object> params = new HashMap<>();
params.put("appid", Constants.APPLET_APP_ID);
params.put("secret", Constants.APPLET_SECRET);
params.put("grant_type", "client_credential");
String url = handleParams("https://api.weixin.qq.com/cgi-bin/token", params);
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity(); // 響應結果
return EntityUtils.toString(entity, CharSetType.UTF8.getType());
}
/**
* description: 獲取 open id,返回結果為 JSON 自行轉 map
* create by: Mr.Fang
*
* @param: [code]
* @return: java.lang.String
* @date: 2023/4/3 17:46
*/
public String getOpenId(String code) throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
Map<String, Object> params = new HashMap<>();
params.put("appid", Constants.APPLET_APP_ID);
params.put("secret", Constants.APPLET_SECRET);
params.put("js_code", code);
params.put("grant_type", "authorization_code");
String url = handleParams("https://api.weixin.qq.com/sns/jscode2session", params);
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity(); // 響應結果
return EntityUtils.toString(entity, CharSetType.UTF8.getType());
}
/**
* description: 消息推送 返回結果為 JSON 自行轉 map;token 調用 getToken獲取
* create by: Mr.Fang
*
* @param: [token]
* @return: java.lang.String
* @date: 2023/4/3 17:46
*/
public String pushMsg(String token) throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
Map<String, Object> params = new HashMap<>();
// 處理微信推送數據結構
JSONObject mapData = new JSONObject();
Map<String, Object> map1 = new HashMap<>();
map1.put("value", "任務名稱");
mapData.put("thing2", map1);
Map<String, Object> map2 = new HashMap<>();
map2.put("value", "2023-04-03 12:00:00");
mapData.put("time3", map2);
Map<String, Object> map3 = new HashMap<>();
map3.put("value", "描述信息");
mapData.put("thing4", map3);
Map<String, Object> map4 = new HashMap<>();
map4.put("value", "備註系信息");
mapData.put("thing10", map4);
Map<String, Object> map5 = new HashMap<>();
map5.put("value", "抖音");
mapData.put("thing11", map5);
params.put("template_id", "templateId");// 模板 id
params.put("touser", "openId"); // open id
params.put("data", mapData); // 數據
params.put("page", "page"); // 點擊模板卡片後的跳轉頁面,僅限本小程式內的頁面。支持帶參數,(示例index?foo=bar)。該欄位不填則模板無跳轉
params.put("miniprogram_state", "trial"); //developer為開發版;trial為體驗版;formal為正式版;預設為正式版
params.put("lang", "zh_CN"); //
HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token);
httpPost.addHeader("ContentTyp", "application/json");
// 參數轉 JSON 格式
String json = objToStr(params);
StringEntity stringEntity = new StringEntity(json, CharSetType.UTF8.getType());
stringEntity.setContentEncoding(CharSetType.UTF8.getType());
httpPost.setEntity(stringEntity);
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity(); // 響應結果
return EntityUtils.toString(entity, CharSetType.UTF8.getType());
}
/**
* description: 對象轉 字元串
* create by: Mr.Fang
*
* @param: [obj]
* @return: java.lang.String
* @date: 2023/4/3 17:45
*/
public static String objToStr(Object obj) {
ObjectMapper objectMapper = new ObjectMapper();
if (Objects.nonNull(obj)) {
try {
String jsonStr = objectMapper.writeValueAsString(obj);
return jsonStr;
} catch (JsonProcessingException var2) {
var2.printStackTrace();
}
}
return null;
}
/**
* description: map 轉 URL 地址拼接
* create by: Mr.Fang
*
* @param: [url, params]
* @return: java.lang.String
* @date: 2023/4/3 17:45
*/
public String handleParams(String url, Map<String, Object> params) {
if (params.size() != 0) {
Set<Map.Entry<String, Object>> entries = params.entrySet();
String paramsString = entries.stream().map((e) -> {
try {
StringBuilder sb = new StringBuilder();
sb.append(URLEncoder.encode(e.getKey(), CharSetType.UTF8.getType()));
sb.append("=");
if (Objects.nonNull(e.getValue())) {
sb.append(URLEncoder.encode(e.getValue().toString(), CharSetType.UTF8.getType()));
}
return sb.toString();
} catch (UnsupportedEncodingException var2) {
var2.printStackTrace();
return null;
}
}).collect(Collectors.joining("&"));
return url + "?" + paramsString;
}
return url;
}
}
本文來自博客園,作者:天葬,轉載請註明原文鏈接:https://www.cnblogs.com/bxmm/p/17283908.html