小程序:

wxml:

 <form bind:submit="testSubmit" report-submit="true">
<button formType="submit" class='modelButton'>发送模板消息</button>
</form>

wxss:

.modelButton{
margin-top:50%;
width: 50%;
}

js前端发送模板消息:

注意:每个小程序的openid都是不一样的,这里使用的是我的小程序的openid,应替换为自己小程序的openid。


    testSubmit: function(e) {
console.log(e);
var self = this;
let method = 'GET';
let openid = 'obk-W5Fq76sHfAnnC_8L_6xEew0M';
let _access_token = '14_Z_mmRqZ8F0LSoYphxhXLcY1qYQbiArASnTyRChBQtKnWDL3co46eXwQsL8Qr58yZ01XmE6shkLGNGkz1zhX0zqPNNsXJlGljdLejCR_qerPP76H-4ZodZT4XTPqEAywHtNB_m-djIzoN3AyHZZJjAFASSC';
let url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + _access_token;

let _jsonData = {
access_token: _access_token,
touser: 'oK_7b4mGyt6L9DRXWINxjEeCb_no',
template_id: 'PZ-QULr4atCAgBacoMjh09u0bAVA_St-lNCp5jV7Pcs',
form_id: e.detail.formId,
page: "pages/index/index",
data: {
"keyword1": {
"value": "测试数据一",
"color": "#173177"
},
"keyword2": {
"value": "测试数据二",
"color": "#173177"
},
"keyword3": {
"value": "测试数据三",
"color": "#173177"
},
"keyword4": {
"value": "测试数据四",
"color": "#173177"
},
"keyword5": {
"value": "测试数据五",
"color": "#173177"
},
"keyword6": {
"value": "测试数据六",
"color": "#173177"
}
}
};

wx.request({
url: "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+_access_token,
data: _jsonData,
method: method,
success: function(res) {
console.log(res)
wx.showToast({
title: '发送成功',
})
},
fail: function(err) {
console.log('request fail ', err);
},
complete: function(res) {
console.log("request completed!");
}

})

}

java代码后台发送模板消息:

后端发送模板消息需要获取前端表单提交的formid

controller:

    @GetMapping("/publishModelMessage")
public String publishModelMessage(@RequestParam(required = false) String formId,@RequestParam(required = false) String openId,HttpServletResponse response){
openId = "oK_7b4mGyt6L9DRXWINxjEeCb_no";
Token token = CommonUtil.getToken("你的小程序appid","你的小程序密钥");
System.out.println(token.getAccessToken());
WxMssVo wxMssVo = new WxMssVo();
wxMssVo.setTemplate_id("PZ-QULr4atCAgBacoMjh09u0bAVA_St-lNCp5jV7Pcs");
wxMssVo.setTouser(openId);
wxMssVo.setPage("pages/index/index");
wxMssVo.setRequest_url("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + token.getAccessToken());
wxMssVo.setForm_id(formId);
List<TemplateData> list = new ArrayList<>();
list.add(new TemplateData("通知","#ffffff"));
list.add(new TemplateData("李银龙","#ffffff"));
list.add(new TemplateData("发布成功","#ffffff"));
list.add(new TemplateData(new Date().toString(),"#ffffff"));
list.add(new TemplateData("日常加班","#ffffff"));
list.add(new TemplateData("深圳市方寸科技服务有限公司","#ffffff"));
wxMssVo.setParams(list);
CommonUtil.sendTemplateMessage(wxMssVo);
return null;
}

工具类CommonUtil:

public class CommonUtil {
public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
//获取小程序token
public static Token getToken(String appid, String appsecret) {
Token token = null;
String requestUrl = token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
// 发起GET请求获取凭证
JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);

if (null != jsonObject) {
try {
token = new Token();
token.setAccessToken(jsonObject.getString("access_token"));
token.setExpiresIn(jsonObject.getInteger("expires_in"));
} catch (JSONException e) {
token = null;
// 获取token失败
e.printStackTrace();
}
}
return token;
}
//发送模板消息
public static String sendTemplateMessage(WxMssVo wxMssVo) {
String info = "";
try {
//创建连接
URL url = new URL(wxMssVo.getRequest_url());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Type", "utf-8");
connection.connect();
//POST请求
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
JSONObject obj = new JSONObject();

obj.put("access_token", wxMssVo.getAccess_token());
obj.put("touser", wxMssVo.getTouser());
obj.put("template_id", wxMssVo.getTemplate_id());
obj.put("form_id", wxMssVo.getForm_id());
obj.put("page", wxMssVo.getPage());

JSONObject jsonObject = new JSONObject();

for (int i = 0; i < wxMssVo.getParams().size(); i++) {
JSONObject dataInfo = new JSONObject();
dataInfo.put("value", wxMssVo.getParams().get(i).getValue());
dataInfo.put("color", wxMssVo.getParams().get(i).getColor());
jsonObject.put("keyword" + (i + 1), dataInfo);
}

obj.put("data", jsonObject);
out.write(obj.toString().getBytes());
out.flush();
out.close();

//读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
info = sb.toString();
System.out.println(sb);
reader.close();
// 断开连接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return info;
}

public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {

JSONObject jsonObject = null;

try {
// 创建 SSLContext 对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述 SSLContext 对象中得到 SSLSocketFactory 对象
SSLSocketFactory ssf = sslContext.getSocketFactory();

URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);

conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);

// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);

// 当 outputStr 不为 null 时,向输出流写数据
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();

// 注意编码格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}

// 从输入流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();

while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}

// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
jsonObject = JSONObject.parseObject(buffer.toString());
} catch (ConnectException ce) {
ce.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

return jsonObject;
}

}

Token类:

public class Token {
//接口访问凭证
private String accessToken;
//接口有效期,单位:秒
private int expiresIn;

public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
}

模板消息请求参数封装类WxMssVo :

public class WxMssVo {
private String touser;
private String template_id;
private String page;
private String form_id;
private String access_token;
private String request_url;
private List<TemplateData> params = new ArrayList<>();
}

模板消息详细参数封装TemplateData :

public class TemplateData {
private String key;
private String value;
private String color;

public TemplateData(String value, String color) {
this.value = value;
this.color = color;
}
}

最终效果:

Java微信小程序发送服务通知_模板消息

关注公众号回复091可获取项目源码

Java微信小程序发送服务通知_json_02