微信小程序最近要彻底关掉模板消息,新增了订阅消息,根据之前的模板消息,写了一个订阅消息的实现,需要的可以参考下:
1、WxaSubscribeMessageTemplate.class
public class WxaSubscribeMessageTemplate { private static final long serialVersionUID = 2634554747304038112L; private String touser; private String template_id; private String page; private WxaSubscribeMessageTemplate.TemplateItem data = new WxaSubscribeMessageTemplate.TemplateItem(); public WxaSubscribeMessageTemplate() { } public String getTouser() { return this.touser; } public WxaSubscribeMessageTemplate setTouser(String touser) { this.touser = touser; return this; } public String getTemplate_id() { return this.template_id; } public WxaSubscribeMessageTemplate setTemplate_id(String template_id) { this.template_id = template_id; return this; } public String getPage() { return this.page; } public WxaSubscribeMessageTemplate setPage(String page) { this.page = page; return this; } public WxaSubscribeMessageTemplate.TemplateItem getData() { return this.data; } public WxaSubscribeMessageTemplate add(String key, String value) { this.data.put(key, new WxaSubscribeMessageTemplate.Item(value)); return this; } public String build() { return JsonUtils.toJson(this); } public class Item { private Object value; public Object getValue() { return this.value; } public void setValue(Object value) { this.value = value; } public Item(Object value) { this.value = value; } } public class TemplateItem extends HashMap<String, WxaSubscribeMessageTemplate.Item> { private static final long serialVersionUID = -3728490424738325020L; public TemplateItem() { } public TemplateItem(String key, WxaSubscribeMessageTemplate.Item item) { this.put(key, item); } } }
2、SubscribeMessageApi.class
public class SubscribeMessageApi { private static String sendApiUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="; public SubscribeMessageApi() { } public ApiResult send(String jsonStr) { System.out.println(jsonStr); String jsonResult = HttpUtils.post(sendApiUrl + WxaAccessTokenApi.getAccessTokenStr(), jsonStr); System.out.println(jsonResult); return new ApiResult(jsonResult); } public ApiResult send(WxaSubscribeMessageTemplate template) { return this.send(template.build()); } }
3、使用方法:
SubscribeMessageApi subscribeMessageApi = Duang.duang(SubscribeMessageApi.class);
WxaSubscribeMessageTemplate template = new WxaSubscribeMessageTemplate();
template.setPage("跳转的页面");
template.setTemplate_id("模板ID");
template.setTouser("用户的openId");
template.add("key", "value");
template.add("key2", "value2");
ApiResult apiResult = subscribeMessageApi.send(template);
if(apiResult.isSucceed()){
return true;
}
return false;