微信小程序是支持消息推送的瞻凤,但是推送有個限制荞彼,只有form表單開啟report-submit,用戶點擊提交這樣表單的時候才可以獲得一個formid昂羡,推送時需要使用這個formid進(jìn)行推送。所以小程序消息推送需要解決formid的存儲摔踱,小程序內(nèi)部接口調(diào)用是AccessToken認(rèn)證兩大問題虐先。消息模板申請這里就不細(xì)說了。
1.獲取formid并儲存
在小程序上 表單form上添加一個report-submit <form bindsubmit='commitForm' report-submit='true'>
這樣在在提交表單的時候就可以獲得到這個formid派敷。
commitForm:function(e){
//獲取formid
var fromId = e.detail.formId;
}
獲取到formid后只需要在提交這個表單的時候把formid一起帶到后臺然后進(jìn)行使用數(shù)據(jù)庫進(jìn)行保存就可以了蛹批。保存formid是最好把插入時間一起加上,這樣可以方便刪除已經(jīng)過了七天失效的formid篮愉。
這里需要注意的是每一個formid只能使用一次腐芍,且只有七天的時效。
所以我們需要使用Quartz任務(wù)調(diào)度定時清理掉超過七天失效的formid试躏。
/**
* 微信小程序刪除過期formid 每天執(zhí)行一次
*/
@Scheduled(cron = "0 00 0 * * ?")
@Transactional
public void clearTimeoutFormId() {
//執(zhí)行sql清理過期未用的formId
miniprogramFormIdMapper.deleteFormIdByTimeout();
}
2. 獲取小程序AccessToken
官方說明:access_token
是小程序全局唯一后臺接口調(diào)用憑據(jù)猪勇,調(diào)用絕大多數(shù)后臺接口時都需使用。開發(fā)者可以通過 getAccessToken
接口獲取并進(jìn)行妥善保存颠蕴。
也就是服務(wù)端需要小程序的接口必須攜帶微信官方派發(fā)的accessToken
令牌作為身份驗證泣刹。這個accessToken
只有2小時的時效性助析,每獲取一次上次的的accessToken
就會失效,為了保證效率需要使用定時器90分鐘自動更新一次椅您,每次需要使用accessToken
就直接從數(shù)據(jù)庫去獲取即可外冀,不用在請求微信小程序接口獲取。
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
/**
* 獲取小程序全局唯一后臺接口調(diào)用憑據(jù) access_token 每90分鐘執(zhí)行一次
*/
@Scheduled(cron = "0 */90 * * * ?")
@Transactional
public void getWechatMiniprogramAccessToken() {
//發(fā)送GET請求
String result = "";
BufferedReader in = null;
try {
String urlNameString = "https://api.weixin.qq.com/cgi-bin/token?" + "grant_type=client_credential&secret=123123&appid=456456";
URL realUrl = new URL(urlNameString);
// 打開和URL之間的連接
URLConnection connection = realUrl.openConnection();
// 設(shè)置通用的請求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立實際的連接
connection.connect();
// 定義 BufferedReader輸入流來讀取URL的響應(yīng)
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
}
// 使用finally塊來關(guān)閉輸入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
// 解析相應(yīng)內(nèi)容(轉(zhuǎn)換成json對象)
JSONObject resultJson = JSON.parseObject(result);
//拿到accesstoken
String accesstoken = (String) resultJson.get("access_token");
//保存accesstoken到數(shù)據(jù)庫
miniprogramFormIdMapper.insertAccessToken(accesstoken);
}
3.發(fā)送消息模板
有了formid和accessToken之后我們就可以發(fā)送消息推送了掀泳。
為了方便我們對消息模板的內(nèi)容進(jìn)行設(shè)置雪隧,最好聲明對象進(jìn)行儲存,然后直接用過fastJson將對象轉(zhuǎn)成json發(fā)送給小程序消息推送接口就可以完成消息推送员舵。
發(fā)送消息模板對象
import java.util.Map;
public class WeiXinTeamplateMsg {
private String touser;//用戶openid
private String template_id;//模版id
private String page = "index";//默認(rèn)跳到小程序首頁
private String form_id;//收集到的用戶formid
private String emphasis_keyword = "keyword1.DATA";//放到那個推送字段
private Map<String, TemplateData> data;//推送文字
//getter and setter
//.....
}
消息內(nèi)容對象
public class TemplateData {
private String value;
//getter and setter
//.....
}
以小程序消息模版庫中模版編號為模板ID:AT1633 標(biāo)題:客服回復(fù)通知的模板為例膀跌。
發(fā)送消息的方法
import model.TemplateData;
import model.WeiXinTeamplateMsg;
import util.*;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
/**
* 微信小程序推送單個用戶
*
* @param access_token 令牌
* @param openId 小程序用戶openId
* @param formid 推送formid
* @param value1 客服類型
* @param value2 回復(fù)時間
* @param value3 回復(fù)內(nèi)容
* @param value4 詢問時間
* @param value5 詢問事項
* @param value6 溫馨提示
* @return
*/
public static String pushTicketReplyMsgToUser(String access_token, String openId, String formid, String value1, String value2, String value3, String value4, String value5, String value6) {
String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + access_token;
//拼接推送的模版
WeiXinTeamplateMsg weiXinTeamplateMsg = new WeiXinTeamplateMsg();
weiXinTeamplateMsg.setTouser(openId);//用戶openid
weiXinTeamplateMsg.setTemplate_id("Xs1515168sdaddd15aDASda6");//申請的消息模版id
weiXinTeamplateMsg.setForm_id(formid);//formid
weiXinTeamplateMsg.setPage("index");//跳轉(zhuǎn)的頁面
Map<String, TemplateData> msgMap = new HashMap<>(5);
TemplateData keyword1 = new TemplateData();
keyword1.setValue(value1);
msgMap.put("keyword1", keyword1);
TemplateData keyword2 = new TemplateData();
keyword2.setValue(value2);
msgMap.put("keyword2", keyword2);
weiXinTeamplateMsg.setData(msgMap);
TemplateData keyword3 = new TemplateData();
keyword3.setValue(value3);
msgMap.put("keyword3", keyword3);
weiXinTeamplateMsg.setData(msgMap);
TemplateData keyword4 = new TemplateData();
keyword4.setValue(value4);
msgMap.put("keyword4", keyword4);
weiXinTeamplateMsg.setData(msgMap);
TemplateData keyword5 = new TemplateData();
keyword5.setValue(value5);
msgMap.put("keyword5", keyword5);
weiXinTeamplateMsg.setData(msgMap);
TemplateData keyword6 = new TemplateData();
keyword6.setValue(value6);
msgMap.put("keyword6", keyword6);
weiXinTeamplateMsg.setData(msgMap);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity =
restTemplate.postForEntity(url, weiXinTeamplateMsg, String.class);
return responseEntity.getBody();
}
記住要將用過的formid給刪除掉。