先看一下效果图
一:在官网小程序后台新建模板
图1:
图2:
二:wxml
<form bindsubmit="bindSendMsg" report-submit='ture' >
<button hover-class="plain-hover" form-type="submit" >
name
</button>
</form>
三:收集信息
bindSendMsg: function (e) {
var formId = e.detail.formId;
wx.request({
url: 'https://.../sendMsg',
data: {
formId: formId,
openid: openid,
type: type
},
header: {
'content-type': 'application/json' // 默认值
},
success(res) {
console.log("sendMsg result",res.data)
}
})
},
四:发送信息使用 java
public void sendMsg(String openid,String formId,String templateId){
logger.info("sendMsg start,openid:{},formId:{},templateId:{}",openid,formId,templateId);
String token = getAccessToken();
String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+token;
HashMap para = new HashMap<>();
para.put("touser",openid);
para.put("form_id",formId);
para.put("template_id",templateId);
para.put("page","pages/home/home");
HashMap data = new HashMap();
para.put("data",data);
HashMap keyword1 = new HashMap();
data.put("keyword1",keyword1);
keyword1.put("value","今日的目标完成了多少?\n快来【爱上成长】记录成长的足迹吧!");
HashMap keyword2 = new HashMap();
data.put("keyword2",keyword2);
String date = DateUtils.formatDate(new Date(),"yyyy年MM月dd日");
keyword2.put("value",date);
logger.info("sendMsg start,para:{}",JSON.toJSONString(para));
byte[] bytes = HttpRequest.sendPost(url, JSON.toJSONString(para));
String res = new String(bytes);
logger.info("sendMsg result,para:{},res:{}",JSON.toJSONString(para),res);
JSONObject retj = JSON.parseObject(res);
if("40001".equals(retj.get("errcode").toString())){
logger.info("sendMsg again,openid:{},formId:{},templateId:{}",openid,formId,templateId);
tokenCache.clear();
sendMsg(openid,formId,templateId);
}
logger.info("sendMsg end,openid:{},formId:{},templateId:{},res:{}",openid,formId,templateId,res);
}
五:信息发送效果图