首先,獲取微信小程序的配置信息
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"
}