/** 核心
* 消息模板工具类
*/
@Component
public class TemplateUtil {
private static DictItemFacade itemFacade;
@Autowired
public void setItemFacade(DictItemFacade itemFacade) {
TemplateUtil.itemFacade = itemFacade;
}
private static String freshToken(PageData pageData) throws Exception{
String access_token;
//刷新token
AccessToken globalToken = HttpUtil.getGlobalToken(Constant.APP_ID, Constant.APP_SECRET);
access_token = globalToken.getAccess_token();
//将token存入数据库
pageData.clear();
pageData.put("itemCode",access_token);
pageData.put("itemName","global_access_token");
itemFacade.updateItemCodeByItemName(pageData);
return access_token;
}
/**
* 获取模板信息,0--成功, 1--失败
* @return
*/
public static int sendTemplateMessage(String wxOpenId,String title,String question,String answer,
String betCredit,String winCredit,String betTime) throws Exception{
PageData pageData = new PageData();
pageData.put("dicCode","WX_TOKEN");
pageData.put("itemName","global_access_token");
PageData resPd = itemFacade.findItemCodeByItemName2(pageData);
//获取全局token
String updateTime = resPd.get("updateDate").toString();
String token = resPd.get("itemCode").toString();
boolean outOfDate = SysUtil.isOutOfDate(updateTime, 3600);
String access_token = null;
if(token != null && token != "") {
if (outOfDate) {//超时
access_token = freshToken(pageData);
} else {//未超时
access_token = token;
}
}else{
access_token = freshToken(pageData);
}
String appId = Constant.APP_ID;
String appSecret = Constant.APP_SECRET;
//设置模板信息
Map js = new HashMap<>();
js.put("touser",wxOpenId);
js.put("template_id",Constant.Template_Id);
js.put("url",Constant.DOMAIN+"wxEntry/webAuthorize");
js.put("data",getJsonObject(title,question,answer,betCredit,winCredit,betTime));
String url = Constant.SEND_TEMPLATE_MESSAGE.replace("ACCESS_TOKEN",access_token);
JSONObject post = HttpUtil.httpsConnect(url, "POST", JSON.toJSONString(js));
if("0".equals(post.get("errcode").toString())){
return 0;
}else{
return -1;
}
}
/**
* 设置竞猜通知模板消息的一些信息
* @param title 模板消息的标题
* @param question 本次竞猜的题目
* @param answer 本次竞猜的答案
* @param betCredit 本次竞猜的押注萝卜
* @param winCredit 本次竞猜赢或者输的罗
* @param betTime 本次竞猜开始时间
* @return
*/
public static Map getJsonObject(String title,String question,String answer,
String betCredit,String winCredit,String betTime){
Map json = new HashMap();
//Map tem = new HashMap();
//添加标题
TemplateParam tem = null;
tem = new TemplateParam(title,"#FF3300");
/*tem.put("value",title);
tem.put("color","#173173");//红色*/
json.put("title",tem);
//添加题目
tem = new TemplateParam(question,"#173173");
/*tem.put("value",question);
tem.put("color","#173173");*/
json.put("question",tem);
//添加我的竞猜
tem = new TemplateParam(answer,"#173173");
/*tem.put("value",answer);
tem.put("color","#FF3300");*/
json.put("answer",tem);
//添加竞猜的萝卜数量
tem = new TemplateParam(betCredit,"#173173");
/*tem.put("value",betCredit);
tem.put("color","#FF3300");*/
json.put("betCredit",tem);
//添加赢或者输的萝卜数量
tem = new TemplateParam(winCredit,"#173173");
/*tem.put("value",winCredit);
tem.put("color","#FF3300");*/
json.put("winCredit",tem);
//添加竞猜时间
tem = new TemplateParam(betTime,"#173173");
/*tem.put("value",betTime);
tem.put("color","#FF3300");*/
json.put("betTime",tem);
//tem.clear();
return json;
}
}
@Override
public PageData findItemCodeByItemName2(PageData pd) throws Exception {
Object forObject = dao.findForObject("DicItemsMapper.findCodeByName2", pd);
if(forObject != null){
return (PageData)forObject;
}else{
return null;
}
}
@Override
public int updateItemCodeByItemName(PageData pd) throws Exception {
int res = 0;
pd.put("updateDate",DateUtil.getTime());
res = (int)dao.update("DicItemsMapper.updateByName",pd);
return res;
}
<!-- 修改 -->
<update id="updateByName" parameterType="pd">
update
T_SYS_DIC_ITEMS
<set>
<if test="itemCode != null and itemCode != ''">
ITEM_CODE = #{itemCode},
</if>
<if test="updateDate != null and updateDate!= ''">
update_date = #{updateDate},
</if>
</set>
where 1=1
<if test="itemName != null and itemName != ''">
and ITEM_NAME = #{itemName}
</if>
</update>
<select id="findCodeByName2" parameterType="pd" resultType="pd">
SELECT
item_name as itemName,
item_code as itemCode,
dic_code as dicCode,
update_date as updateDate
FROM
t_sys_dic_items
WHERE 1=1
<if test="itemName != null and itemName != ''">
and item_name = #{itemName}
</if>
<if test="dicCode != null and dicCode != ''">
and dic_code = #{dicCode}
</if>
</select>
/**相关方法
* 判断是否超时,true超时,false未超时
*
* @param timeStample
* @param time
* @return
*/
public static boolean isOutOfDate(String timeStample, int time) throws Exception {
long pre = sdf.parse(timeStample).getTime();
long current = System.currentTimeMillis();
if ((current - pre) >= time * 1000) {
return true;
} else {
return false;
}
}
/**相关方法
* 创建菜单
* @param url 请求的url
* @param method 请求的方法(post/get)
* @param content 请求的内容
* @return
*/
public static JSONObject httpsConnect(String url, String method, String content) throws ConnectException{
JSONObject json = null;
StringBuffer sb = new StringBuffer();
try {
//创建SLLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MytrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL","SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
//从上面的SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL u = new URL(url);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) u.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
//设置请求方式
httpUrlConn.setRequestMethod(method);
if("GET".equalsIgnoreCase(method)) {
httpUrlConn.connect();
}
// 当有数据需要提交时
if (null != content) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(content.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
sb.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
json = JSONObject.parseObject(sb.toString());
}catch (ConnectException ce) {
logger.error("Weixin server connection timed out.");
} catch (Exception e) {
logger.error("https request error:{}", e);
}
return json;
}
/** controller层
* 模板消息
*/
@RequestMapping(value="/GuessManagerController_templateMessage")
@ResponseBody
public Object templateMessage(Page page) throws Exception {
PageData pd = new PageData();
pd = this.getPageData();
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
WxUser tempUser = (WxUser) session.getAttribute(Constant.WX_LOGIN_SESSION);
pd.put("WxOpenId", tempUser.getWxOpenId());
List<PageData> list = guessFacade.lookResult(pd);//查询是否有人下注
List<PageData> resultList= guessFacade.findUserInterlocution(pd);//查询用户所填的题目信息
if(Integer.parseInt(list.get(0).get("answerA").toString())!=0||Integer.parseInt(list.get(0).get("answerB").toString())!=0){
if(resultList!=null && resultList.size()>0){
String betCredit = resultList.get(0).get("integrationNum").toString();
String betT = resultList.get(0).get("betTime").toString();
String betTime = betT.substring(0, 19);
int bcdt = Integer.parseInt(betCredit)*2;
String beat = String.valueOf(bcdt);
String Lose ="0";
String AnswerTitle = "恭喜你猜对了!快去收获萝卜吧!";
String AnswerTitle2 = "不小心种错了?再接再厉吧!";
String Singular = "单数";
String EvenNumbers = "双数";
if(resultList.get(0).get("answers").toString().equals(pd.get("correctAnswer").toString()) && resultList.get(0).get("answers").toString().equals("A")){
sendTemplateMessage = TemplateUtil.sendTemplateMessage(pd.get("WxOpenId").toString(), AnswerTitle,pd.get("question").toString(),Singular, betCredit, beat, betTime);
}else if(resultList.get(0).get("answers").toString().equals(pd.get("correctAnswer").toString()) && resultList.get(0).get("answers").toString().equals("B")){
sendTemplateMessage = TemplateUtil.sendTemplateMessage(pd.get("WxOpenId").toString(), AnswerTitle,pd.get("question").toString(), EvenNumbers, betCredit, beat, betTime);
}else if(!resultList.get(0).get("answers").toString().equals(pd.get("correctAnswer").toString()) && resultList.get(0).get("answers").toString().toString().equals("A")){
sendTemplateMessage = TemplateUtil.sendTemplateMessage(pd.get("WxOpenId").toString(), AnswerTitle2,pd.get("question").toString(),Singular, betCredit, Lose, betTime);
}else if(!resultList.get(0).get("answers").toString().equals(pd.get("correctAnswer").toString()) && resultList.get(0).get("answers").toString().equals("B")){
sendTemplateMessage = TemplateUtil.sendTemplateMessage(pd.get("WxOpenId").toString(), AnswerTitle2,pd.get("question").toString(), EvenNumbers, betCredit, Lose, betTime);
}
}
if(sendTemplateMessage==0){
pd.put("result", "模板正常");
}else{
pd.put("result", "模板异常");
}
}
return pd;
}
JSP页面指定地方调用触发
//模板消息,传递所需参数
var question = data.info.question;
var correctAnswer =data.info.correctAnswer;
var questionNo = $("#questionNo").val();
var postData = {
"question":question,
"correctAnswer":correctAnswer,
"questionNo":questionNo
};
//发送请求调用接口
$.post("<%=path %>/mobile/GuessManagerController/GuessManagerController_templateMessage.do", postData, function (date) {
console.log(date.result);
})
最后一步需要去微信公众平台进行设置,如图
最终效果如下: