TemplateData
@Getter
@Setter
public class TemplateData {
/**
* 依次排下去
*/
private String value;
}
WxMssVo
@Data
public class WxMssVo {
/**
* 用户openid
*/
private String touser;
/**
* 模版id
*/
private String template_id;
/**
* 默认跳到小程序首页
*/
private String page = "/pages/index/index";
/**
* 小程序表单提交时的formId
*/
private String form_id;
/**
* 放大那个推送字段
*/
private String emphasis_keyword = "keyword1.DATA";
/**
* 推送文字内容
*/
private Map<String, TemplateData> data;
}
编写实现方法
public String messagePush(OrderVO orderVO) {
RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
String access_token = getAccessToken();
String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send" + "?access_token=" + access_token;
WxMssVo wxMssVo = new WxMssVo();
wxMssVo.setTouser(orderVO.getOpenId());//用户openId
wxMssVo.setTemplate_id("iSV_2FOh8B0xIOKZMhP874sCcXBgcSQT_2ZAzsvfhtM");//模版id
wxMssVo.setForm_id(orderVO.getFormId());//小程序表单提交时的formId
Map<String, TemplateData> m = new HashMap<>(1);
TemplateData keyword1 = new TemplateData();
keyword1.setValue("恭喜您申请成功");
m.put("keyword1", keyword1);
String requestBody = JSON.toJSONString(wxMssVo);
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
HttpEntity<String> httpEntity = new HttpEntity<String>(requestBody, headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
return responseEntity.getBody();
}
public String getAccessToken() {
String access_token = "";
try {
URL url = new URL("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
"&appid=" + "appid" + "&secret=" + "secret");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String str = "";
while ((str = br.readLine()) != null) {
str = new String(str.getBytes(), "UTF-8");
JSONObject json = new JSONObject(str);
access_token = String.valueOf(json.get("access_token"));
}
is.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return access_token;
}