1.先看文档
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/subscribe-message.html
第一步:先创建一个自己想要的模版
第二步:先看文档 ,在微信小程序写一个按钮触发函数里加入
wx.requestSubscribeMessage({
tmplIds: [‘你的模版id’], //可以是多个
success (res) { }
})
每次订阅都会询问你一次。
<button bindtap="bindMsg">订阅消息</button>
bindMsg:function(){
wx.requestSubscribeMessage({
tmplIds: ['p2BH6d6YQb9u7lm8lyZEw2Unn_MIcLFKna7hWaC65S4'],
success (res) {
console.log(res)
}
})
}
第三步:文档 https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html
我们需要传入四个必填参数给微信平台,注意data必须是json格式数据,且满足如下格式:
如果不按要求来会出现如下报错
按照以上顺序要求,编写后台代码
@RestController
@RequestMapping("/wx/message")
public class TemplateMessageController {
@Autowired
private RestTemplate restTemplate;
@Value("${wechat.mp.appid}")
private String appid;
@Value("${wechat.mp.secret}")
private String secret;
private String openId = "自己获取自己的";
@RequestMapping(value="/sendMsg")
@ResponseBody
protected String sendMsg(){
//获取access_token
String requestAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
String jsonData = this.restTemplate.getForObject(requestAccessTokenUrl, String.class);
String accessToken = (String) JSON.parseObject(jsonData).get("access_token");
String sendMsgUrl ="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+accessToken;
Map<String,Object> map = new HashMap<>();
map.put("touser",openId);//传入openid
map.put("template_id","p2BH6d6YQb9u7lm8lyZEw2Unn_MIcLFKna7hWaC65S4");
map.put("page","pages/TemplateMessage/TemplateMessage");
Map<String,Object> data = new HashMap<>();
Map<String,Object> key1 = new HashMap<>();
key1.put("value","1234567");
Map<String,Object> key2 = new HashMap<>();
key2.put("value","ppp");
Map<String,Object> key3 = new HashMap<>();
key3.put("value","testy");
Map<String,Object> key4 = new HashMap<>();
key4.put("value","10.00");
Map<String,Object> key5 = new HashMap<>();
key5.put("value","2020-11-30");
map.put("data",data);
data.put("character_string5",key1);
data.put("thing4",key2);
data.put("thing3",key3);
data.put("amount1",key4);
data.put("date6",key5);
String resultString = this.restTemplate.postForObject(sendMsgUrl, JSON.toJSON(map), String.class);
return resultString;
}
}
请求接口返回{“errcode”:0,“errmsg”:“ok”}
小程序服务通知中会出现
这样就很简单的实现了订阅消息。
有帮到你的话就扫扫吧