####创建service层接口
com\imooc\service\PushMessage.java
package com.imooc.service;
import com.imooc.dto.OrderDTO;
/**
* Created by Administrator on 2020/2/27.
* 微信模板消息推送
*/
public interface PushMessage {
/*订单状态变更消息*/
public void orderStatus(OrderDTO orderDTO);
}
####创建service层实现类
com\imooc\service\imp\PushMessageImp.java
package com.imooc.service.imp;
import com.imooc.config.WechatAccountConfig;
import com.imooc.dto.OrderDTO;
import com.imooc.service.PushMessage;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
/**
* @author: menghaibin
* @create: 2020-02-27 13:41
* @description: 微信模板消息推送
**/
Service
Slf4j
public class PushMessageImp implements PushMessage{
@Autowired
private WxMpService wxMpService;
@Autowired
private WechatAccountConfig accountConfig;
/*订单完结时调用*/
@Override
public void orderStatus(OrderDTO orderDTO) {
/*服务号才会有模板消息 还要服务器加入微信白名单*/
WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
templateMessage.setTemplateId(accountConfig.getTemplateId().get("orderstatus"));/*模板id*/
templateMessage.setToUser(orderDTO.getBuyerOpenid());/*目标用户的openid*/
List<WxMpTemplateData> wxMpTemplateDataList = Arrays.asList(
new WxMpTemplateData("first","亲 请记得收货哦!"),
new WxMpTemplateData("keyword1","微信点餐"),
new WxMpTemplateData("keyword2","17600800548"),
new WxMpTemplateData("keyword3",orderDTO.getOrderId()),
new WxMpTemplateData("keyword4",orderDTO.getOrderStatus().toString()),
new WxMpTemplateData("keyword5","¥"+orderDTO.getOrderAmount()),
new WxMpTemplateData("remark","欢迎再次光临")
);
templateMessage.setData(wxMpTemplateDataList);
try{
wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
}catch (WxErrorException e){
log.error("[微信模板异常]");
}
}
}
####把模板id配置到application.yml文件中,并在WechatAccountConfig类中追加属性
wechat:
templateId: #模板消息id
orderstatus: ewur430280238203843
/*微信模板id*/
private Map<String,String> templateId;
####订单完结时调用
在OrderServiceImp的finish方法中调用消息推送的方法