今天写了一个商品到货提醒的job任务,具体效果如下
这里用到了微信的发送订阅消息,主要代码是这一块的,最后我把发送了消息的订单存到表里,因为是定时任务,大家可不存
发送订阅消息 | 微信开放文档
/*** 微信平台-商品到货通知*/public String uploadArrival(WxOrderArrivalDTO wxOrderArrivalDTO) throws ParseException {String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + wechatManager.getaccessToken();JSONObject body = new JSONObject();JSONObject data = new JSONObject();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String date = sdf.format(DateUtil.now());data.put("time4",new JSONObject().fluentPut("value",date));data.put("character_string5", new JSONObject().fluentPut("value",wxOrderArrivalDTO.getPickupCode()));data.put("amount6",new JSONObject().fluentPut("value",wxOrderArrivalDTO.getOrderAmount() + "元"));data.put("thing7",new JSONObject().fluentPut("value",wxOrderArrivalDTO.getShopName()) );data.put("short_thing8", new JSONObject().fluentPut("value","自提"));body.put("data", data);body.put("touser", wxOrderArrivalDTO.getOpenId());body.put("miniprogram_state", "formal");body.put("lang", "zh_CN");body.put("template_id", "这里填模板id");String result = null;try {result = HttpUtil.createPost(url).body(body.toJSONString()).execute().body();log.info("通知微信平台 订单到货接口返回:" + result);OrderPushMsgDTO orderPushMsgDTO = new OrderPushMsgDTO();orderPushMsgDTO.setPushMsgId(UUIDUtils.getUUID());orderPushMsgDTO.setOrderId(wxOrderArrivalDTO.getOrderId());orderPushMsgDTO.setOrderType(CommonKey.CONSTANT_1);JSONObject jsonObject = JSON.parseObject(result);int errcode = jsonObject.getInteger("errcode");orderPushMsgDTO.setErrCode(String.valueOf(errcode));orderPushMsgBO.save(orderPushMsgDTO);} catch (Exception e) {throw new BizException(e.getMessage());}return result;}
这是微信公众号平台申请的模板,其中模板id填到上图中的template_id后面
这是微信官方文档的请求参数示例,主要是data里面的数据key是上图详细内容里的time4,thing7...
然后遇到一个问题,就是给data塞值的时候刚开始采用的是第二种方法,发现没塞进去,用下图框中的写法就可以了
后面又写了个公众号的,效果如下
这个用法的是微信的模板消息,大致写法都一样,就是tocken要用公众号的tocken,用小程序的tocken会报错48001,还有如果不是一个模板id代码里记得换,不然会报错40037。模板有数据是枚举的,拼接返回消息的时候要对应上
模板消息 | 微信开放文档
public String uploadArrivalOfficialAccountPush(WxOrderArrivalDTO wxOrderArrivalDTO){WechatInfoDTO weChatAccessToken = authUtil.getWeChatAccessToken();String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + weChatAccessToken.getAccessToken();List<OrderItemDTO> itemList= orderItemDao.queryListOrderItemByOrderIdList(Arrays.asList(wxOrderArrivalDTO.getOrderId()));List<ShopGoodsDTO> shopGoodsDTOS = this.shopGoodsBo.queryGoodsByIdList(itemList.stream().map(OrderItemDTO::getGoodsId).collect(Collectors.toList()));if (ObjectUtil.isNull(shopGoodsDTOS)) {return null;}Map<String, ShopGoodsDTO> shopGoodsDTOMap = shopGoodsDTOS.stream().distinct().collect(Collectors.toMap(ShopGoodsDTO::getGoodsId, Function.identity(), (oldValue, newValue) -> oldValue));List<ShopGoodsSpeciInfoDTO> speciInfoList= shopGoodsSpeciInfoBO.queryGoodsSpeciInfoByIdList(itemList.stream().map(OrderItemDTO::getGoodsSpeciId).collect(Collectors.toList()));StringBuffer goodNames=new StringBuffer();int size = speciInfoList.size();for (int i = 0; i < size; i++) {ShopGoodsSpeciInfoDTO temp = speciInfoList.get(i);String goodsName = shopGoodsDTOMap.get(temp.getGoodsId()).getGoodsName();goodNames.append(goodsName);if (i < size - 1) {goodNames.append("、");}}if(goodNames.toString().length()>20){wxOrderArrivalDTO.setItemDesc(goodNames.toString().substring(0,10)+ELLIPSIS_3);}else{wxOrderArrivalDTO.setItemDesc(goodNames.toString());}JSONObject body = new JSONObject();JSONObject data = new JSONObject();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String date = sdf.format(DateUtil.now());data.put("time1",new JSONObject().fluentPut("value",date));data.put("thing2",new JSONObject().fluentPut("value",wxOrderArrivalDTO.getItemDesc()));data.put("amount3",new JSONObject().fluentPut("value",wxOrderArrivalDTO.getOrderAmount() + "元"));data.put("thing4",new JSONObject().fluentPut("value",wxOrderArrivalDTO.getShopName()) );data.put("const5", new JSONObject().fluentPut("value",CommonKey.CONSTANT_3.equals(wxOrderArrivalDTO.getDeliveryMethod()) ? "用户自提" : "商家配送"));body.put("data", data);body.put("url", officialAccountPushUrl);body.put("touser", wxOrderArrivalDTO.getOpenId());body.put("template_id", "这里填模板id");String result = null;try {result = HttpUtil.createPost(url).body(body.toJSONString()).execute().body();log.info("通知微信平台 订单到货接口返回:" + result);OrderPushMsgDTO orderPushMsgDTO = new OrderPushMsgDTO();orderPushMsgDTO.setPushMsgId(UUIDUtils.getUUID());orderPushMsgDTO.setOrderId(wxOrderArrivalDTO.getOrderId());orderPushMsgDTO.setOrderType(CommonKey.CONSTANT_1);JSONObject jsonObject = JSON.parseObject(result);orderPushMsgDTO.setPushType(CommonKey.CONSTANT_2);int errcode = jsonObject.getInteger("errcode");orderPushMsgDTO.setErrCode(String.valueOf(errcode));orderPushMsgBO.save(orderPushMsgDTO);} catch (Exception e) {throw new BizException(e.getMessage());}return result;}
获取公众号的tocken,要注意是url+json的形式
开始开发 / 获取 Stable Access token
public WechatInfoDTO getWeChatAccessToken() {Map<String,Object> requestUrlParam=new HashMap<String,Object>();//appIdrequestUrlParam.put("appid", wechatAppId);//appSecretrequestUrlParam.put("secret", wechatSecret);//默认参数requestUrlParam.put("grant_type", "client_credential");ObjectMapper objectMapper = new ObjectMapper();String json = null;try {json = objectMapper.writeValueAsString(requestUrlParam);} catch (JsonProcessingException e) {e.printStackTrace();}//发送post请求读取调用微信接口获取accessToken信息String result = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/stable_token", json);JSONObject jsonObject = JSONObject.parseObject(result);Integer errcode = jsonObject.getInteger("errcode");if (errcode != null && errcode != 0) {String errmsg = jsonObject.getString("errmsg");log.error(result);throw new BizException(ResultCode.FAIL,errmsg);}return new WechatInfoDTO().setAccessToken(jsonObject.getString("access_token"));}