微信给关注公众号的用户推送模板消息
1.在公众号后台获取消息模板(本例使用微信测试账号),观看微信官方文档:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html#5
测试账号需自己定义消息模板:
{{first.DATA}}
商家名称:{{keyword1.DATA}}
商家电话:{{keyword2.DATA}}
订单号:{{keyword3.DATA}}
状态:{{keyword4.DATA}}
总价:{{keyword5.DATA}}
{{remark.DATA}}
2.使用sdk,编写微信推送模板消息的service
@Service @Slf4j public class PushMessageServiceImpl implements PushMessageService { @Autowired private WxMpService wxMpService; @Autowired private WechatAccountConfig accountConfig; @Override public void pushMessage(OrderDTO orderDTO) { //新建模板消息类 WxMpTemplateMessage wxMpTemplateMessage=new WxMpTemplateMessage(); //编写模板消息需推送的用户,该用户必须关注了公众号 wxMpTemplateMessage.setToUser("owRHRv5J3oiMbb8D7_YYSvXvngiw"); //配置推送消息模板id wxMpTemplateMessage.setTemplateId(accountConfig.getTemplateId().get("orderStatus")); //配置推送消息的内容 List<WxMpTemplateData> data= Arrays.asList( new WxMpTemplateData("first","用餐愉快哦"), new WxMpTemplateData("keyword1","微信点餐"), new WxMpTemplateData("keyword2","13826913333"), new WxMpTemplateData("keyword3",orderDTO.getOrderId()), new WxMpTemplateData("keyword4",orderDTO.getOrderStatusEnum().getMsg()), new WxMpTemplateData("keyword5","¥"+orderDTO.getOrderAmount()), new WxMpTemplateData("remark","用餐愉快哦") ); wxMpTemplateMessage.setData(data); try { //使用sdk发送模板消息 String msg = wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage); log.info("发送模板消息返回的信息为:{}",msg); } catch (WxErrorException e) { e.printStackTrace(); } } }
3.结果如下: