说明:
通过引入weixin-java-miniapp SDK快速开发,实现小程序推送消息功能。
引入pom.xml依赖
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>4.4.0</version>
</dependency>
源码
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaSubscribeService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 微信通知
*/
@Slf4j
@Service
public class WeChatNotifyService {
@Autowired
private WxMaService wxMaService;
/**
* 发送微信通知
* @param openId
* @param templateId
* @param page
* @param data
* @return
*/
public Boolean sendMiniAppNotification(String openId, String templateId, String page, Map<String,String> data) {
// 转换为List对象
List<WxMaSubscribeMessage.MsgData> list = new ArrayList<>();
for (Map.Entry<String, String> entry : data.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
WxMaSubscribeMessage.MsgData obj = new WxMaSubscribeMessage.MsgData(key, value);
list.add(obj);
}
WxMaSubscribeMessage templateMessage = WxMaSubscribeMessage.builder()
.toUser(openId)
.templateId(templateId)
.page(page)
.data(list)
.build();
try {
WxMaSubscribeService subscribeService = wxMaService.getSubscribeService();
subscribeService.sendSubscribeMsg(templateMessage);
return true;
} catch (WxErrorException e) {
// 处理异常情况
log.error("小程序消息发送失败:{}", e.getMessage());
e.printStackTrace();
return false;
}
}
}
调用示例
import com.kjhd.service.util.WeChatNotifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
/****
*测试消息推送
*****/
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
WeChatNotifyService weChatNotifyService;
@GetMapping()
public void test() {
String page = "pages/index";
String openId="oZVN50VZ5QwKZqx60_83K4Xc0QD";
String templateId = "123456789";
HashMap<String, String> map = new HashMap<>();
map.put("thing1", "111");
map.put("time2", "2024-04-04 12:00:00");
map.put("thing3", "内容");
Boolean boo = weChatNotifyService.sendMiniAppNotification(openId, templateId, page, map);
}
}