今天来带大家学习下微信模版消息推送。
先看效果图:
核心代码只有下面几行,即可轻松实现微信模版消息推送
//1,配置 WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage(); wxStorage.setAppId("wx77bb69292323a000"); wxStorage.setSecret("29bd368145806115ad6820133e62806e"); WxMpService wxMpService = new WxMpServiceImpl(); wxMpService.setWxMpConfigStorage(wxStorage); //2,推送消息 WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder() .toUser("o5kho6DgC7SDry8zCmXuvHJGvrgI")//要推送的用户openid .templateId("Tpln-Eue2obJ0B-8JNkgkiRJaDMPgVeIgGxna982xrg")//模版id .url("https://30paotui.com/")//点击模版消息要访问的网址 .build(); try { wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage); } catch (Exception e) { System.out.println("推送失败:" + e.getMessage()); }
所用知识点
- 1, springboot实现java后台
- 2,微信测试账号的申请
- 3,微信模版推送的配置
- 接下来就带领大家来一步步实现微信模版消息推送。
一,springboot创建java后台
至于springboot怎么创建java后台,我这里就不再唠叨了,大家百度一下,一大堆的文章。这里只需要重点讲解下以下几点。
- 1,在pom.xml文件里引入下面类库
com.github.binarywang weixin-java-mp 3.3.0
- 2,写一个推送的controller
package com.qiushi.wxpush;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;import me.chanjar.weixin.mp.api.WxMpService;import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;/** * Created by qcl on 2019-03-28 * 微信:2501902696 * desc: 模版消息推送模拟 */@RestControllerpublic class PushController { /* * 微信测试账号推送 * */ @GetMapping("/push") public void push() { //1,配置 WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage(); wxStorage.setAppId("wx77bb69292323a000"); wxStorage.setSecret("29bd368145806115ad6820133e62806e"); WxMpService wxMpService = new WxMpServiceImpl(); wxMpService.setWxMpConfigStorage(wxStorage); //2,推送消息 WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder() .toUser("o5kho6DgC7SDry8zCmXuvHJGvrgI")//要推送的用户openid .templateId("Tpln-Eue2obJ0B-8JNkgkiRJaDMPgVeIgGxna982xrg")//模版id .url("https://30paotui.com/")//点击模版消息要访问的网址 .build(); //3,如果是正式版发送模版消息,这里需要配置你的信息 // templateMessage.addData(new WxMpTemplateData("name