一、微信公眾平臺小程序開通消息訂閱并設置模板
這邊的模板id和詳細內容后續前后端需要使用
二、uniapp前端
需要是一個button觸發
js:
wx.getSetting({success(res){console.log(res)if(res.authSetting['scope.subscribeMessage']){// 業務邏輯}else{uni.requestSubscribeMessage({tmplIds: [_config.TEMPLATE_ID],success (res) {console.log("訂閱成功!")// 業務邏輯},fail(res) {// 即使用戶拒絕訂閱也要繼續原來的業務邏輯}})}}
})
三、java后端
@Component
@Slf4j
public class WxAccessTokenUtil {@Value("${WX_APPID}")String APP_ID;@Value("${WX_SECREAT}")String SECREAT;@Value("${WX_TEMPLATE_ID}")String TEMPLATE_ID;public String getWxAccessToken(){String res = HttpClient.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APP_ID+"&secret="+SECREAT);JSONObject jsonObject = JSON.parseObject(res);return jsonObject.getString("access_token");}public void sendReservationSubscribeMsg(String touser,String id,String apparatusName,String state){String token = getWxAccessToken();JSONObject jsonObject2 = new JSONObject();jsonObject2.put("access_token",token);jsonObject2.put("touser",touser);jsonObject2.put("template_id",TEMPLATE_ID);jsonObject2.put("page","/pages/appointment_detail/appointment_detail?id="+id);JSONObject data = new JSONObject();JSONObject thing2 = new JSONObject();thing2.put("value",apparatusName);data.put("thing2",thing2);JSONObject phrase3 = new JSONObject();phrase3.put("value",state);data.put("phrase3",phrase3);jsonObject2.put("data",data);String res = HttpClient.doPost("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+token,jsonObject2.toString());log.warn("微信小程序訂閱消息:{}",res);}
}
其中thing2、phrase3是模板的字段名,根據自己模板去修改即可
HttpClient.java
public class HttpClient {public static void main(String[] args) {String APP_ID = "xxx";String SECREAT = "xxx";String res = HttpClient.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APP_ID+"&secret="+SECREAT);com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(res);String token = jsonObject.getString("access_token");JSONObject jsonObject2 = new JSONObject();jsonObject2.put("access_token",token);jsonObject2.put("touser","xxxxx");jsonObject2.put("template_id","xxxx");jsonObject2.put("page","/pages/tabbar/mine/mine");JSONObject data = new JSONObject();JSONObject phrase1 = new JSONObject();phrase1.put("value","待審核");data.put("phrase1",phrase1);JSONObject thing2 = new JSONObject();thing2.put("value","已成功提交預約申請,請耐心等待審核。");data.put("thing2",thing2);jsonObject2.put("data",data);jsonObject2.put("miniprogram_state","trial");System.out.println(HttpClient.doPost("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+token,jsonObject2.toString()));}public static String doGet(String httpurl) {HttpURLConnection connection = null;InputStream is = null;BufferedReader br = null;String result = null;// 返回結果字符串try {// 創建遠程url連接對象URL url = new URL(httpurl);// 通過遠程url連接對象打開一個連接,強轉成httpURLConnection類connection = (HttpURLConnection) url.openConnection();// 設置連接方式:getconnection.setRequestMethod("GET");// 設置連接主機服務器的超時時間:15000毫秒connection.setConnectTimeout(15000);// 設置讀取遠程返回的數據時間:60000毫秒connection.setReadTimeout(60000);// 發送請求connection.connect();// 通過connection連接,獲取輸入流if (connection.getResponseCode() == 200) {is = connection.getInputStream();// 封裝輸入流is,并指定字符集br = new BufferedReader(new InputStreamReader(is, "UTF-8"));// 存放數據StringBuffer sbf = new StringBuffer();String temp = null;while ((temp = br.readLine()) != null) {sbf.append(temp);sbf.append("\r\n");}result = sbf.toString();}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {// 關閉資源if (null != br) {try {br.close();} catch (IOException e) {e.printStackTrace();}}if (null != is) {try {is.close();} catch (IOException e) {e.printStackTrace();}}connection.disconnect();// 關閉遠程連接}return result;}public static String doPost(String httpUrl, String param) {HttpURLConnection connection = null;InputStream is = null;OutputStream os = null;BufferedReader br = null;String result = null;try {URL url = new URL(httpUrl);// 通過遠程url連接對象打開連接connection = (HttpURLConnection) url.openConnection();// 設置連接請求方式connection.setRequestMethod("POST");// 設置連接主機服務器超時時間:15000毫秒connection.setConnectTimeout(15000);// 設置讀取主機服務器返回數據超時時間:60000毫秒connection.setReadTimeout(60000);// 默認值為:false,當向遠程服務器傳送數據/寫數據時,需要設置為trueconnection.setDoOutput(true);// 默認值為:true,當前向遠程服務讀取數據時,設置為true,該參數可有可無connection.setDoInput(true);// 設置傳入參數的格式:請求參數應該是 name1=value1&name2=value2 的形式。connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 設置鑒權信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");// 通過連接對象獲取一個輸出流os = connection.getOutputStream();// 通過輸出流對象將參數寫出去/傳輸出去,它是通過字節數組寫出的os.write(param.getBytes());// 通過連接對象獲取一個輸入流,向遠程讀取if (connection.getResponseCode() == 200) {is = connection.getInputStream();// 對輸入流對象進行包裝:charset根據工作項目組的要求來設置br = new BufferedReader(new InputStreamReader(is, "UTF-8"));StringBuffer sbf = new StringBuffer();String temp = null;// 循環遍歷一行一行讀取數據while ((temp = br.readLine()) != null) {sbf.append(temp);sbf.append("\r\n");}result = sbf.toString();}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {// 關閉資源if (null != br) {try {br.close();} catch (IOException e) {e.printStackTrace();}}if (null != os) {try {os.close();} catch (IOException e) {e.printStackTrace();}}if (null != is) {try {is.close();} catch (IOException e) {e.printStackTrace();}}// 斷開與遠程地址url的連接connection.disconnect();}return result;}
}