直接上代码:
1.首先引入maven依赖:
com.github.binarywang
weixin-java-miniapp
3.8.0
2.工具类:
/**
* description: 微信小程序推送
* create by: YangLinWei
* create time: 2020/7/28 2:24 下午
*/
@Slf4j
public class SendMiniApp {
private WxMaMsgService msgService;
/**
* description: 构造函数(初始化配置)
* param: wxMpConfig 配置内容
*/
public SendMiniApp(String appId, String appSercret) {
if (StringUtils.isEmpty(appId)) {
throw new RuntimeException("appId不能为空");
}
if (StringUtils.isEmpty(appSercret)) {
throw new RuntimeException("secret不能为空");
}
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
config.setAppid(appId);
config.setSecret(appSercret);
WxMaServiceImpl wxMaService = new WxMaServiceImpl();
wxMaService.setWxMaConfig(config);
msgService = wxMaService.getMsgService();
}
/**
* description: 发送订阅消息
* param: openId 用户的openid
* param: templateId 模板id
* param: dataParam 参数内容
*/
public void sendSubscribeMsg(String openId, String templateId, List dataParam) throws WxErrorException {
// 3.8.0版本使用的使用WxMaSubscribeMessage
WxMaSubscribeMessage.WxMaSubscribeMessageBuilder builder = WxMaSubscribeMessage.builder();
builder.toUser(openId);//推送消息的目标对象openId
builder.templateId(templateId); //这里填写的就是在后台申请添加的模板ID
builder.data(dataParam);//添加请求参数
WxMaSubscribeMessage msg = builder.build();
msgService.sendSubscribeMsg(msg);
}
/**
* description: 发送订阅消息
* param: openId 用户的openid
* param: templateId 模板id
* param: dataParam 参数内容
* param: page 跳转链接
*/
public void sendSubscribeMsg(String openId, String templateId, List dataParam, String page) throws WxErrorException {
// 3.8.0版本使用的使用WxMaSubscribeMessage
WxMaSubscribeMessage.WxMaSubscribeMessageBuilder builder = WxMaSubscribeMessage.builder();
builder.toUser(openId);//推送消息的目标对象openId
builder.templateId(templateId); //这里填写的就是在后台申请添加的模板ID
builder.data(dataParam);//添加请求参数
builder.page(page); //添加跳转链接,如果目标用户点击了推送的消息,则会跳转到小程序主页
WxMaSubscribeMessage msg = builder.build();
msgService.sendSubscribeMsg(msg);
}
}