准备工作
1.登录微信公众平台进入自己的微信公众号点击广告与服务下的订阅通知,如下图
编辑
2.点击公共模板库,选择一个自己想要的模板(模板只能使用微信提供的模板),按照自己的需求去找一个模板,我这里要做一个访客出场提示。
编辑
3.点击选用,保留自己想要的提示项即可。
编辑
4.点击提交之后即可生成一条模板信息
编辑
Java代码
1.在yaml文件里配置模板id
编辑
2.编写发送微信通知接口
SocialClientService:
void sendWxMPMessage(String openId, String templateId, String page, Map<String, String> dataMap) throws Exception;
参数为:openId,即唯一id,templatedId就是模板id,page可以为null,dataMap就是拼凑好的数据Map集合
实现类SocialClientServiceImpl:
@Override public void sendWxMPMessage(String openId, String templateId, String page, Map<String, String> dataMap) throws Exception { WxMpService wxMpService1 = wxMpServiceCache.get(clientIdMP + ":" + clientSecretMP); WxMpSubscribeMessage wxMpSubscribeMessage = WxMpSubscribeMessage.builder() .toUser(openId) .templateId(templateId) .url(page) .dataMap(dataMap) .build();wxMpService1.getTemplateMsgService().getAllPrivateTemplate(); wxMpService1.getSubscribeMsgService().send(wxMpSubscribeMessage); }
3.调用接口
注入yaml里面配置好的通知模板id:
@Value("${wx.visitor-template-id}")
private String visitorTemplateId;
注意每项字数不得超过20个字。
private void sendWxMessage(VisitorManageDO visitorManage) { //发送微信通知 Map<String,String> data = new HashMap<>(); data.put("name1", visitorManage.getVisitorName()); data.put("thing4", "感谢您访问***,请您在半个小时内离开厂区,谢谢配合,再见"); log.info("send-mp-visitor,id===>{},data===>{}",visitorManage.getId() , data); try { socialClientService.sendWxMPMessage(visitorManage.getOpenId(), visitorTemplateId, null, data); log.info("send-mp-visitor-success,id===>{}",visitorManage.getId()); } catch (Exception e) { log.error("send-mp-visitor-error,id===>{},msg===>{}",visitorManage.getId(),e.getMessage()); } }
前端预约提示框代码:
<wx-open-subscribe class="custom-submit-btn" id="subscribe-btn" template="f33bI1AS9IC5-eiUW0iSnyCm_hm1Xb6Bf,hs6qtokIu1T9oxpPgU08QEY5V4"--模板id,多个模板id用逗号隔开 @success="onSubscribeSuccess" @error="onSubscribeError" @cancel="handleSubscribeCancel" > <component is="script" type="text/wxtag-template" slot="style"> <component is="style"> .subscribe-btn { background: #007aff !important; color: #fff !important; font-size: 18px !important; border-radius:10px; line-height: -28px !important; text-align: center !important; margin: 0px 0 0 33px !important; } </component> </component> <component is="script" type="text/wxtag-template"> <button class="subscribe-btn"> 提交 </button> </component> </wx-open-subscribe>
编辑
如下图所示,因为我们申请的是一次性模板,所有我们点击允许通知才能接收到一条消息,所以需要在前端显示多个是否允许多个模板通知。
编辑