这几天做的微信小程序模板消息练习,在此总结。
这个是service层的
//这个代码是根据订单id来动态返回data中的数据,可根据自己情况来具体修改,注意添加json依赖
/*
* <dependency>
* <groupId>org.json</groupId>
* <artifactId>json</artifactId>
* <version>20180813</version>
* </dependency>
*
**/
public void getWechatMould(String orderId) {
List<WechatMould> list = shopperDao.getMould(orderId);
if(!list.isEmpty()){
JSONObject data = new JSONObject(); //这个只是模板中的data属性,因为他是嵌套型的所以把他单独拿出来,这个data也是一个单独的类,具体的属性就是下面的这些
try {
JSONObject data1 = new JSONObject();
data1.put("value", list.get(0).getData().getOrderId());
JSONObject data2 = new JSONObject();
data2.put("value", "商品");
JSONObject data5 = new JSONObject();
data3.put("value", "取货时核对商品明细数量");
data.put("keyword1", data1);
data.put("keyword2", data2);
data.put("keyword3", data3);
} catch (JSONException e) {
throw new ApplicationException(HttpStatus.INTERNAL_SERVER_ERROR, "json数据出错");
}
wechatMouldUtil.sendWechatmsgToUser(list.get(0),data);
}else{
throw new ApplicationException(HttpStatus.INTERNAL_SERVER_ERROR, "订单未找到");
}
}
这个是工具类,这里的传输参考了https://blog.youkuaiyun.com/walkcode/article/details/78147217
@Component
public class WechatMouldUtil {
private static final Log logger = LogFactory.getLog(WechatMouldUtil.class);
private static final String TEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN";
@Autowired
private IPropertyUtil propertyUtil;
//这里我把模板消息的参数封装在了WechatMould中,data为上段代码的json数据,我的WechatMould中的data属性是MouldData data,data也是一个对象
public String sendWechatmsgToUser(WechatMould mould, JSONObject data){
String token = wechatTokenUtil.getWechatToken(); //微信凭证,access_token
String url = TEMPLATE_URL.replace("ACCESS_TOKEN", token);
JSONObject json = new JSONObject();
try {
json.put("touser", mould.getTouser());
json.put("template_id","");
json.put("form_id", mould.getPrepayId());
json.put("data", data);
} catch (JSONException e) {
throw new ApplicationException(HttpStatus.INTERNAL_SERVER_ERROR, "json数据出错");
}
String result = httpsRequest(url, "POST", json.toString());
try {
JSONObject resultJson = new JSONObject(result);
String errmsg = (String) resultJson.get("errmsg");
if(!"ok".equals(errmsg)){//如果为errmsg为ok,则代表发送成功。
logger.error("发送失败");
return "error";
}
} catch (JSONException e) {
throw new ApplicationException(HttpStatus.INTERNAL_SERVER_ERROR, "json数据出错");
}
return "success";
}
public String httpsRequest(String requestUrl, String requestMethod, String outputStr){
try {
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
// 当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();
conn.disconnect();
return buffer.toString();
} catch (ConnectException ce) {
logger.error("连接超时:{}");
} catch (Exception e) {
logger.error("https请求异常:{}");
}
return null;
}
}
wechatTokenUtil.getWechatToken()获取ACCESS_TOKEN的方法,这并没有用的线程,而是把生成的ACCESS_TOKEN同失效时间 放在数据库里,当当前时间超过失效时间就重新生成ACCESS_TOKEN。
*主要是记录http方法和json数据的java格式