模板消息推送功能仅限于微信服务号才行。
1、准备:微信公众号 appId,app密钥(这俩没啥好说的,都知道在哪拿)。
模板Id,添加之后就能看到,如果没有合适的模板可以自定义模板(需要审核7-15天)。
用户openId,这个需要用户登录公众号之后才能获取到。
2、添加IP白名单, 不然没法推送。(当前网络的IP)
4、pom依赖
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>2.7.0</version>
</dependency>
4、java代码。你的模板里面有几个内容,你就写几个keyword。
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.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
/**
* @Auther:Tiancong Zou
* @Date: 2023/5/11 17:10
* @Description:
*/
@Component
@Configuration
public class WechatTemplateMessage {
public static void main(String[] args) {
WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
wxStorage.setAppId("***"); //appID
wxStorage.setSecret("***");//app密钥
WxMpService wxMpService = new WxMpServiceImpl();
wxMpService.setWxMpConfigStorage(wxStorage);
//数据
List<WxMpTemplateData> data = Arrays.asList(
new WxMpTemplateData("first", "测试11"),
new WxMpTemplateData("keyword1", "这是一个测试文字"),
new WxMpTemplateData("keyword2", "我要来访"),
new WxMpTemplateData("keyword3", "18584888888"),
new WxMpTemplateData("keyword4", "今天"),
new WxMpTemplateData("remark", "我发出来了")
);
//2,推送消息
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
.toUser("***")//要推送的用户openid
.data(data) //数据
.templateId("***")//模版id
.url("http://www.baidu.com") // 点击详情跳转地址
.build();
//发起推送
try {
String msg = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
System.out.println("推送成功:" + msg);
} catch (Exception e) {
System.out.println("推送失败:" + e.getMessage());
e.printStackTrace();
}
}
}
5、推送成功预览