添加配置类信息
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.cetcnav.operations.util.constant.OperationsConstant;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
@Configuration
public class WxConfig {
@Bean
public WxMpService wxMpService() {
WxMpService wxMpService = new WxMpServiceImpl();
// wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
// 公众号appId
configStorage.setAppId(OperationsConstant.WECHAT_APPID);
// 公众号appSecret
configStorage.setSecret(OperationsConstant.WECHAT_SECRET);
// 公众号Token
configStorage.setToken(OperationsConstant.WECHAT_TOKEN);
// 公众号EncodingAESKey
configStorage.setAesKey(OperationsConstant.WECHAT_AESKEY);
wxMpService.setWxMpConfigStorage(configStorage);
return wxMpService;
}
}
工具方法
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
/**
*
* @author wp 2020年9月28日
*
*/
@Component
public class WxMsgPush {
private static Logger log = LoggerFactory.getLogger(WxMsgPush.class);
/**
* 微信公众号API的Service
*/
public final WxMpService wxMpService;
/**
* 构造注入
*/
public WxMsgPush(WxMpService wxMpService) {
this.wxMpService = wxMpService;
}
public Boolean SendWxMsgShipmentRemind(String openId, Order order) {
// 发送模板消息接口
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
// 接收者openid
.toUser(openId)
// 模板id
.templateId("474za5bfVDaUUCLhWtL2eqweqwqpaZXrVukLUAYU").build();
// 添加模板数据
templateMessage.addData(new WxMpTemplateData("first", "您好!####", "#A9A9A9"))
.addData(new WxMpTemplateData("keyword1", String.valueOf(order.getId()), "#000000"))
.addData(new WxMpTemplateData("keyword2", String.valueOf(order.getName()), "#000000"))
.addData(new WxMpTemplateData("keyword3", String.valueOf(order.getRealname()), "#000000"))
.addData(new WxMpTemplateData("keyword4", String.valueOf(order.getContact()), "#000000"))
.addData(new WxMpTemplateData("keyword5", String.valueOf(order.getAddress()), "#000000"))
.addData(new WxMpTemplateData("remark", "欢迎下次光临", "#A9A9A9"));
String msgId = null;
try {
// 发送模板消息
msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
} catch (WxErrorException e) {
e.printStackTrace();
}
log.info("·==++--·推送微信模板信息:{}·--++==·", msgId != null ? "成功" : "失败");
return msgId != null;
}