首先,获取微信小程序的配置信息
1. 登录微信公众平台:点击小程序,开发配置,查看APPID,appsecret
2. 小程序模板消息 send 官方文档
1. 获取微信的access_token,传入APPID,appsecret
/**
* @Description: 获取access_token
* @author: Hanweihu
* @date: 2019/7/12 11:14
* @param: [appid, appsecret]
* @return: java.lang.String
*/
public String getAccess_token(String appid, String appsecret) {
// 先判断redis中是否存在
String token = redisTemplate.opsForValue().get(自定义key);
if (StringUtils.isBlank(token) == false) {
// token还未过期,获取后直接返回,无需重新获取
return token;
}
// token已过期或不存在,需重新获取
redisTemplate.delete(自定义key);
String access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" + "&appid=" + appid + "&secret=" + appsecret;
String message = "";
try {
URL url = new URL(access_url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
//获取返回的字符
InputStream inputStream = connection.getInputStream();
int size = inputStream.available();
byte[] bs = new byte[size];
inputStream.read(bs);
message = new String(bs, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
//获取access_token
JSONObject jsonObject = JSONObject.fromObject(message);
log.info("======获取公众号平台的access_token:" + jsonObject.toString());
String accessToken = jsonObject.getString("access_token");
String expires_in = jsonObject.getString("expires_in");
// 防止代码运行超时,提前1分钟让微信token失效
redisTemplate.opsForValue().set(自定义key, accessToken, Integer.valueOf(expires_in) - 60, TimeUnit.SECONDS);
return accessToken;
}
2. 成功获取到access_token后,就可以根据文档来推送模板消息了
/**
* @Description: 微信--小程序推送模板消息
* @author: Hanweihu
* @date: 2019/7/15 14:28
* @param: [unionid]
* @return: void
*/
@RequestMapping(value = "/pushWxAdmin", method = RequestMethod.POST)
@ApiOperation("微信--小程序推送模板消息")
public void pushWxAdmin(String unionid) {
if (StringUtils.isBlank(unionid)) {
return;
}
// 调用上面的方法,获取AccessToken,传入APPID,appsecret
String wxAccessToken = getAccess_token(APPID, appsecret);
if (StringUtils.isBlank(wxAccessToken)) {
return;
}
// 查询用户下单信息
// ==省略查数据库代码,CustomerSignUp为数据实体类,你们自定义
CustomerSignUp customerSignUp = customerSignUpList.get(0);
Map<String, Object> dataMap = new HashMap<>();
JSONObject wxTemplateData1 = new JSONObject();
wxTemplateData1.put("value", customerSignUp.getCustomerName());// 报名人
JSONObject wxTemplateData2 = new JSONObject();
wxTemplateData2.put("value", customerSignUp.getCustomerPhone());// 联系方式
JSONObject wxTemplateData3 = new JSONObject();
wxTemplateData3.put("value", customerSignUp.getCustomerIdCard()); // 身份证号
JSONObject wxTemplateData4 = new JSONObject();
wxTemplateData4.put("value", customerSignUp.getCustomerCompanyName()); // 客户公司
JSONObject wxTemplateData5 = new JSONObject();
wxTemplateData5.put("value", customerSignUp.getPayStatus() == 2 ? "已支付" : "未支付"); // 支付情况
JSONObject wxTemplateData6 = new JSONObject();
wxTemplateData6.put("value", customerSignUp.getHelpTeachName()); // 推荐人
JSONObject wxTemplateData7 = new JSONObject();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
wxTemplateData7.put("value", sdf.format(customerSignUp.getCreateDate())); // 提交时间
dataMap.put("keyword1", wxTemplateData1);
dataMap.put("keyword2", wxTemplateData2);
dataMap.put("keyword3", wxTemplateData3);
dataMap.put("keyword4", wxTemplateData4);
dataMap.put("keyword5", wxTemplateData5);
dataMap.put("keyword6", wxTemplateData6);
dataMap.put("keyword7", wxTemplateData7);
// 获取admin的openID
CustomerSignUpOrder customerSignUpOrder = customerSignUpOrderMapper.selectById(signUpOrderId);
String admin_openid = customerSignUpOrder.getAdminOpenid();
if (StringUtils.isBlank(admin_openid) == false) {
String[] openidArr = admin_openid.split(",");
for (int i = 0; i < openidArr.length; i++) {
String s = openidArr[i];
wxProPushMessage(s, wxAccessToken, customerSignUp.getPrepayId(), dataMap);
}
}
}
/**
* @Description: 只给管理员发送客户报名成功消息
* @author: Hanweihu
* @date: 2019/7/12 11:25
* @param: [prepay_id, data]
* @return: void
*/
public void wxProPushMessage(String touser, String accesstoken, String prepay_id, Object data) {
StringBuilder requestUrl = new StringBuilder("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=");
requestUrl.append(accesstoken);
JSONObject json = new JSONObject();
json.put("touser", touser);// 接收人的openid
json.put("template_id", 微信后台设置的模板id);//设置模板id
json.put("form_id", prepay_id);// 设置formid
json.put("data", data);// 设置模板消息内容
json.put("page", "pages/index/main");// 跳转微信小程序页面路径(非必须)
log.info("推送消息:" + json.toString());
Map<String, Object> map = null;
try {
HttpClient client = HttpClientBuilder.create().build();//构建一个Client
HttpPost post = new HttpPost(requestUrl.toString());//构建一个POST请求
StringEntity s = new StringEntity(json.toString(), "UTF-8");
s.setContentEncoding("UTF-8");
s.setContentType("application/json; charset=UTF-8");
post.setEntity(s);//设置编码,不然模板内容会乱码
HttpResponse response = client.execute(post);//提交POST请求
HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
String content = EntityUtils.toString(result);
System.out.println(content);//打印返回的消息
JSONObject res = JSONObject.fromObject(content);//转为json格式
if (res != null && "ok".equals(res.get("errmsg"))) {
System.out.println("模版消息发送成功");
} else {
//封装一个异常
StringBuilder sb = new StringBuilder("模版消息发送失败\n");
sb.append(map.toString());
throw new Exception(sb.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
格式要与文档保持一致,且为json格式
{
"touser": "OPENID",
"template_id": "TEMPLATE_ID",
"page": "index",
"form_id": "FORMID",
"data": {
"keyword1": {
"value": ""
},
"keyword2": {
"value": ""
},
"keyword3": {
"value": ""
} ,
"keyword4": {
"value": ""
}
},
"emphasis_keyword": "keyword1.DATA"
}