微信小程序订阅消息开发指南(java)

打印 上一主题 下一主题

主题 942|帖子 942|积分 2826

微信小程序订阅消息开发指南(java)

第一步 准备阶段

1、你得有一个小程序并且认证了个人的也行
2、开通订阅消息
小程序后台->功能->订阅消息

3、公共模板库选择一个模板
选择的时候,选择你需要的字段,因为字段有限制

4、我的模板点击详情
详情内容,模板 id 都是需要提供个服务端开发人员的

第二步 编码阶段

小程序端

小程序消息订阅,需要用户确认
1、首先小程序授权登陆获取 code
官网示例:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
  1. wx.login({
  2.   success (res) {
  3.     if (res.code) {
  4.       //发起网络请求
  5.       wx.request({
  6.         url: 'https://example.com/onLogin',
  7.         data: {
  8.           code: res.code
  9.         }
  10.       })
  11.     } else {
  12.       console.log('登录失败!' + res.errMsg)
  13.     }
  14.   }
  15. })
  16. // 结果 {errMsg: "login:ok", code: "0a3kK4Ga10Gk3F0oBAHa1mGyRl3kK4Gd"}
复制代码
uni-App 示例:https://uniapp.dcloud.net.cn/api/plugins/login.html#login
  1. uni.login({
  2.     provider: 'weixin', //使用微信登录
  3.     success: function (loginRes) {
  4.         console.log(loginRes)
  5.     }
  6. });
  7. // 结果 {errMsg: "login:ok", code: "0a3kK4Ga10Gk3F0oBAHa1mGyRl3kK4Gd"}
复制代码
2、将 code 传给服务端 获取用户唯一标识 openId
3、通过代码起小程序消息订阅界面、用户点击确定ok,小程序工作结束
官方示例:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/subscribe-message/wx.requestSubscribeMessage.html
tmplIds 填写模板 id 即可,最多三个
  1. wx.requestSubscribeMessage({
  2.   tmplIds: [''],
  3.   success (res) {
  4.       console.log(res)
  5.   }
  6. })
复制代码
4、注意事项:
避免重复拉起用户订阅通知,可以通过微信提供的 getSetting 判断用户是否订阅了,如果没有就拉起。
注意下面是用uniapp写的,方法前缀是uni 如果你小程序代码记得修改 wx 以及提示组件
到此小程序工作结束
  1. getSetting() {
  2.     uni.getSetting({
  3.         withSubscriptions: true, // 获取用户订阅状态
  4.         success(res) {
  5.             // false 表示用户未订阅改消息
  6.             if (!res.subscriptionsSetting.mainSwitch) {
  7.                 this.subscribeMessage();
  8.             } else {
  9.                 uni.showToast({
  10.                     title: '已订阅',
  11.                     icon: 'none'
  12.                 })
  13.             }
  14.         }
  15.     })
  16. },
  17. subscribeMessage() {
  18.     uni.requestSubscribeMessage({
  19.         tmplIds: ['模板id'],
  20.         success(res) {
  21.             if (res.errMsg === 'requestSubscribeMessage:ok') {
  22.                 uni.showToast({
  23.                     title: '订阅成功',
  24.                     icon: 'none'
  25.                 })
  26.             }
  27.         }
  28.     })
  29. }   
复制代码
服务端

微信小程序的 appid 和  secret 小程序后台->开发->开发管理->开发设置->开发者 ID
注意事项

  • http 请求这里使用 apache 的工具类,你也可以使用别的
  • 微信消息模板字段 thing 字段有长度限制20,超过会失败
  • 以下演示代码,生产环境还需进行优化
1、通过 code 获取用户 open id 官网文档
  1. public String getOpenId(String code) throws IOException {
  2.         CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  3.         Map<String, Object> params = new HashMap<>();
  4.         params.put("appid", Constants.APPLET_APP_ID);
  5.         params.put("secret", Constants.APPLET_SECRET);
  6.         params.put("js_code", code);
  7.         params.put("grant_type", "authorization_code");
  8.         String url = handleParams("https://api.weixin.qq.com/sns/jscode2session", params);
  9.         HttpGet httpGet = new HttpGet(url);
  10.         CloseableHttpResponse response = httpClient.execute(httpGet);
  11.         HttpEntity entity = response.getEntity(); // 响应结果
  12.         return EntityUtils.toString(entity, CharSetType.UTF8.getType());
  13. }
  14. public static void main(String[] args) throws IOException {
  15.         HttpUtils httpUtils = new HttpUtils();
  16.         String token = httpUtils.getToken();
  17.         System.out.println(token);
  18. }
复制代码
响应结果:
  1. {"access_token":"67_u22CQaWq22222222Q4griDE6kiT5hwg7jVxedn8J9te17Az1oWGGxPgB22222229Y4Wm6h_Yzci7-FSDjeH8YG6DsCOYrQXJCWsPXhT6nWbKIWCXfABACID","expires_in":7200}
复制代码
2、通过 appid 和  secret 获取 token 超时 7200 秒 可 redis 缓存 官方文档
  1. public String getToken() throws IOException {
  2.         CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  3.         Map<String, Object> params = new HashMap<>();
  4.         params.put("appid", Constants.APPLET_APP_ID);
  5.         params.put("secret", Constants.APPLET_SECRET);
  6.         params.put("grant_type", "client_credential");
  7.         String url = handleParams("https://api.weixin.qq.com/cgi-bin/token", params);
  8.         HttpGet httpGet = new HttpGet(url);
  9.         CloseableHttpResponse response = httpClient.execute(httpGet);
  10.         HttpEntity entity = response.getEntity(); // 响应结果
  11.         return EntityUtils.toString(entity, CharSetType.UTF8.getType());
  12. }
复制代码
3、指定用户推送消息结束 官方文档
  1. public String pushMsg(String token) throws IOException {
  2.         CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  3.         Map<String, Object> params = new HashMap<>();
  4.         // 处理微信推送数据结构
  5.         JSONObject mapData = new JSONObject();
  6.         Map<String, Object> map1 = new HashMap<>();
  7.         map1.put("value", "任务名称");
  8.         mapData.put("thing2", map1);
  9.         Map<String, Object> map2 = new HashMap<>();
  10.         map2.put("value", "2022-04-03 10:00:00");
  11.         mapData.put("time3", map2);
  12.         Map<String, Object> map3 = new HashMap<>();
  13.         map3.put("value", "描述信息");
  14.         mapData.put("thing4", map3);
  15.         Map<String, Object> map4 = new HashMap<>();
  16.         map4.put("value", "备注信息");
  17.         mapData.put("thing10", map4);
  18.         Map<String, Object> map5 = new HashMap<>();
  19.         map5.put("value", "任务来源");
  20.         mapData.put("thing11", map5);
  21.         params.put("template_id", "templateId");// 模板 id
  22.         params.put("touser", "openId"); // open id
  23.         params.put("data", mapData); // 数据
  24.         params.put("page", "page"); // 点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转
  25.         params.put("miniprogram_state", "trial"); //developer为开发版;trial为体验版;formal为正式版;默认为正式版
  26.         params.put("lang", "zh_CN"); //
  27.         HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token);
  28.         httpPost.addHeader("ContentTyp", "application/json");
  29.         // 参数转 JSON 格式
  30.         String json = objToStr(params);
  31.         StringEntity stringEntity = new StringEntity(json, CharSetType.UTF8.getType());
  32.         stringEntity.setContentEncoding(CharSetType.UTF8.getType());
  33.         httpPost.setEntity(stringEntity);
  34.         CloseableHttpResponse response = httpClient.execute(httpPost);
  35.         HttpEntity entity = response.getEntity(); // 响应结果
  36.         return EntityUtils.toString(entity, CharSetType.UTF8.getType());
  37.     }
复制代码
4、完整代码
  1. import com.alibaba.fastjson.JSONObject;
  2. import com.fasterxml.jackson.core.JsonProcessingException;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import com.github.chenlijia1111.utils.core.enums.CharSetType;
  5. import org.apache.http.HttpEntity;
  6. import org.apache.http.client.methods.CloseableHttpResponse;
  7. import org.apache.http.client.methods.HttpGet;
  8. import org.apache.http.client.methods.HttpPost;
  9. import org.apache.http.entity.StringEntity;
  10. import org.apache.http.impl.client.CloseableHttpClient;
  11. import org.apache.http.impl.client.HttpClientBuilder;
  12. import org.apache.http.util.EntityUtils;
  13. import org.jeecg.modules.video.utitls.Constants;
  14. import java.io.IOException;
  15. import java.io.UnsupportedEncodingException;
  16. import java.net.URLEncoder;
  17. import java.util.HashMap;
  18. import java.util.Map;
  19. import java.util.Objects;
  20. import java.util.Set;
  21. import java.util.stream.Collectors;
  22. /**
  23. * @description:
  24. * @author: Mr.Fang
  25. * @create: 2023-04-03 17:06
  26. **/
  27. public class HttpUtils {
  28.     /**
  29.      * description: 获取token,返回结果为 JSON 自行转 map
  30.      * create by: Mr.Fang
  31.      *
  32.      * @return: java.lang.String
  33.      * @date: 2023/4/3 17:46
  34.      */
  35.     public String getToken() throws IOException {
  36.         CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  37.         Map<String, Object> params = new HashMap<>();
  38.         params.put("appid", Constants.APPLET_APP_ID);
  39.         params.put("secret", Constants.APPLET_SECRET);
  40.         params.put("grant_type", "client_credential");
  41.         String url = handleParams("https://api.weixin.qq.com/cgi-bin/token", params);
  42.         HttpGet httpGet = new HttpGet(url);
  43.         CloseableHttpResponse response = httpClient.execute(httpGet);
  44.         HttpEntity entity = response.getEntity(); // 响应结果
  45.         return EntityUtils.toString(entity, CharSetType.UTF8.getType());
  46.     }
  47.     /**
  48.      * description: 获取 open id,返回结果为 JSON 自行转 map
  49.      * create by: Mr.Fang
  50.      *
  51.      * @param: [code]
  52.      * @return: java.lang.String
  53.      * @date: 2023/4/3 17:46
  54.      */
  55.     public String getOpenId(String code) throws IOException {
  56.         CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  57.         Map<String, Object> params = new HashMap<>();
  58.         params.put("appid", Constants.APPLET_APP_ID);
  59.         params.put("secret", Constants.APPLET_SECRET);
  60.         params.put("js_code", code);
  61.         params.put("grant_type", "authorization_code");
  62.         String url = handleParams("https://api.weixin.qq.com/sns/jscode2session", params);
  63.         HttpGet httpGet = new HttpGet(url);
  64.         CloseableHttpResponse response = httpClient.execute(httpGet);
  65.         HttpEntity entity = response.getEntity(); // 响应结果
  66.         return EntityUtils.toString(entity, CharSetType.UTF8.getType());
  67.     }
  68.     /**
  69.      * description: 消息推送 返回结果为 JSON 自行转 map;token 调用 getToken获取
  70.      * create by: Mr.Fang
  71.      *
  72.      * @param: [token]
  73.      * @return: java.lang.String
  74.      * @date: 2023/4/3 17:46
  75.      */
  76.     public String pushMsg(String token) throws IOException {
  77.         CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  78.         Map<String, Object> params = new HashMap<>();
  79.         // 处理微信推送数据结构
  80.         JSONObject mapData = new JSONObject();
  81.         Map<String, Object> map1 = new HashMap<>();
  82.         map1.put("value", "任务名称");
  83.         mapData.put("thing2", map1);
  84.         Map<String, Object> map2 = new HashMap<>();
  85.         map2.put("value", "2023-04-03 12:00:00");
  86.         mapData.put("time3", map2);
  87.         Map<String, Object> map3 = new HashMap<>();
  88.         map3.put("value", "描述信息");
  89.         mapData.put("thing4", map3);
  90.         Map<String, Object> map4 = new HashMap<>();
  91.         map4.put("value", "备注系信息");
  92.         mapData.put("thing10", map4);
  93.         Map<String, Object> map5 = new HashMap<>();
  94.         map5.put("value", "抖音");
  95.         mapData.put("thing11", map5);
  96.         params.put("template_id", "templateId");// 模板 id
  97.         params.put("touser", "openId"); // open id
  98.         params.put("data", mapData); // 数据
  99.         params.put("page", "page"); // 点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转
  100.         params.put("miniprogram_state", "trial"); //developer为开发版;trial为体验版;formal为正式版;默认为正式版
  101.         params.put("lang", "zh_CN"); //
  102.         HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token);
  103.         httpPost.addHeader("ContentTyp", "application/json");
  104.         // 参数转 JSON 格式
  105.         String json = objToStr(params);
  106.         StringEntity stringEntity = new StringEntity(json, CharSetType.UTF8.getType());
  107.         stringEntity.setContentEncoding(CharSetType.UTF8.getType());
  108.         httpPost.setEntity(stringEntity);
  109.         CloseableHttpResponse response = httpClient.execute(httpPost);
  110.         HttpEntity entity = response.getEntity(); // 响应结果
  111.         return EntityUtils.toString(entity, CharSetType.UTF8.getType());
  112.     }
  113.     /**
  114.      * description: 对象转 字符串
  115.      * create by: Mr.Fang
  116.      *
  117.      * @param: [obj]
  118.      * @return: java.lang.String
  119.      * @date: 2023/4/3 17:45
  120.      */
  121.     public static String objToStr(Object obj) {
  122.         ObjectMapper objectMapper = new ObjectMapper();
  123.         if (Objects.nonNull(obj)) {
  124.             try {
  125.                 String jsonStr = objectMapper.writeValueAsString(obj);
  126.                 return jsonStr;
  127.             } catch (JsonProcessingException var2) {
  128.                 var2.printStackTrace();
  129.             }
  130.         }
  131.         return null;
  132.     }
  133.     /**
  134.      * description: map 转 URL 地址拼接
  135.      * create by: Mr.Fang
  136.      *
  137.      * @param: [url, params]
  138.      * @return: java.lang.String
  139.      * @date: 2023/4/3 17:45
  140.      */
  141.     public String handleParams(String url, Map<String, Object> params) {
  142.         if (params.size() != 0) {
  143.             Set<Map.Entry<String, Object>> entries = params.entrySet();
  144.             String paramsString = entries.stream().map((e) -> {
  145.                 try {
  146.                     StringBuilder sb = new StringBuilder();
  147.                     sb.append(URLEncoder.encode(e.getKey(), CharSetType.UTF8.getType()));
  148.                     sb.append("=");
  149.                     if (Objects.nonNull(e.getValue())) {
  150.                         sb.append(URLEncoder.encode(e.getValue().toString(), CharSetType.UTF8.getType()));
  151.                     }
  152.                     return sb.toString();
  153.                 } catch (UnsupportedEncodingException var2) {
  154.                     var2.printStackTrace();
  155.                     return null;
  156.                 }
  157.             }).collect(Collectors.joining("&"));
  158.             return url + "?" + paramsString;
  159.         }
  160.         return url;
  161.     }
  162. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

用户国营

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表