微信小程序订阅消息开发指南(java)
第一步 准备阶段
1、你得有一个小程序,并且认证了,个人的也行
2、开通订阅消息
小程序后台
->功能
->订阅消息
3、公共模板库选择一个模板
选择的时候,选择你需要的字段,因为字段有限制
4、我的模板点击详情
详情内容,模板 id 都是需要提供个服务端开发人员的
第二步 编码阶段
小程序端
小程序消息订阅,需要用户确认
1、首先小程序授权登陆获取 code
官网示例:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
wx.login({
success (res) {
if (res.code) {
//发起网络请求
wx.request({
url: 'https://example.com/onLogin',
data: {
code: res.code
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
// 结果 {errMsg: "login:ok", code: "0a3kK4Ga10Gk3F0oBAHa1mGyRl3kK4Gd"}
uni-App 示例:https://uniapp.dcloud.net.cn/api/plugins/login.html#login
uni.login({
provider: 'weixin', //使用微信登录
success: function (loginRes) {
console.log(loginRes)
}
});
// 结果 {errMsg: "login:ok", code: "0a3kK4Ga10Gk3F0oBAHa1mGyRl3kK4Gd"}
2、将 code
传给服务端 获取用户唯一标识 openId
3、通过代码起小程序消息订阅界面、用户点击确定ok,小程序工作结束
tmplIds
填写模板 id 即可,最多三个
wx.requestSubscribeMessage({
tmplIds: [''],
success (res) {
console.log(res)
}
})
4、注意事项:
避免重复拉起用户订阅通知,可以通过微信提供的
getSetting
判断用户是否订阅了,如果没有就拉起。注意下面是用
uniapp
写的,方法前缀是uni
如果你小程序代码记得修改wx
以及提示组件到此小程序工作结束
getSetting() {
uni.getSetting({
withSubscriptions: true, // 获取用户订阅状态
success(res) {
// false 表示用户未订阅改消息
if (!res.subscriptionsSetting.mainSwitch) {
this.subscribeMessage();
} else {
uni.showToast({
title: '已订阅',
icon: 'none'
})
}
}
})
},
subscribeMessage() {
uni.requestSubscribeMessage({
tmplIds: ['模板id'],
success(res) {
if (res.errMsg === 'requestSubscribeMessage:ok') {
uni.showToast({
title: '订阅成功',
icon: 'none'
})
}
}
})
}
服务端
微信小程序的
appid
和secret
小程序后台
->开发
->开发管理
->开发设置
->开发者 ID
注意事项:
http
请求这里使用 apache 的工具类,你也可以使用别的- 微信消息模板字段
thing
字段有长度限制20,超过会失败 - 以下演示代码,生产环境还需进行优化
1、通过 code 获取用户 open id 官网文档
public String getOpenId(String code) throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
Map<String, Object> params = new HashMap<>();
params.put("appid", Constants.APPLET_APP_ID);
params.put("secret", Constants.APPLET_SECRET);
params.put("js_code", code);
params.put("grant_type", "authorization_code");
String url = handleParams("https://api.weixin.qq.com/sns/jscode2session", params);
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity(); // 响应结果
return EntityUtils.toString(entity, CharSetType.UTF8.getType());
}
public static void main(String[] args) throws IOException {
HttpUtils httpUtils = new HttpUtils();
String token = httpUtils.getToken();
System.out.println(token);
}
响应结果:
{"access_token":"67_u22CQaWq22222222Q4griDE6kiT5hwg7jVxedn8J9te17Az1oWGGxPgB22222229Y4Wm6h_Yzci7-FSDjeH8YG6DsCOYrQXJCWsPXhT6nWbKIWCXfABACID","expires_in":7200}
2、通过 appid
和 secret
获取 token 超时 7200 秒 可 redis 缓存 官方文档
public String getToken() throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
Map<String, Object> params = new Hash