<output id="qn6qe"></output>

    1. <output id="qn6qe"><tt id="qn6qe"></tt></output>
    2. <strike id="qn6qe"></strike>

      亚洲 日本 欧洲 欧美 视频,日韩中文字幕有码av,一本一道av中文字幕无码,国产线播放免费人成视频播放,人妻少妇偷人无码视频,日夜啪啪一区二区三区,国产尤物精品自在拍视频首页,久热这里只有精品12

      微信小程序訂閱消息開發(fā)指南(java)

      微信小程序訂閱消息開發(fā)指南(java)

      第一步 準備階段

      1、你得有一個小程序并且認證了個人的也行

      2、開通訂閱消息

      小程序后臺->功能->訂閱消息

      image

      3、公共模板庫選擇一個模板

      選擇的時候,選擇你需要的字段,因為字段有限制

      image

      4、我的模板點擊詳情

      詳情內容,模板 id 都是需要提供個服務端開發(fā)人員的

      image

      第二步 編碼階段

      小程序端

      小程序消息訂閱,需要用戶確認

      1、首先小程序授權登陸獲取 code

      官網示例:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html

      wx.login({
        success (res) {
          if (res.code) {
            //發(fā)起網絡請求
            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,小程序工作結束

      官方示例:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/subscribe-message/wx.requestSubscribeMessage.html

      tmplIds 填寫模板 id 即可,最多三個

      wx.requestSubscribeMessage({
        tmplIds: [''],
        success (res) {
            console.log(res)
        }
      })
      

      4、注意事項:

      避免重復拉起用戶訂閱通知,可以通過微信提供的 getSetting 判斷用戶是否訂閱了,如果沒有就拉起。

      注意下面是用uniapp寫的,方法前綴是uni 如果你小程序代碼記得修改 wx 以及提示組件

      到此小程序工作結束

      getSetting() {
          uni.getSetting({
              withSubscriptions: true, // 獲取用戶訂閱狀態(tài)
              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'
                      })
                  }
              }
          })
      }    
      

      服務端

      微信小程序的 appidsecret 小程序后臺->開發(fā)->開發(fā)管理->開發(fā)設置->開發(fā)者 ID

      注意事項

      1. http 請求這里使用 apache 的工具類,你也可以使用別的
      2. 微信消息模板字段 thing 字段有長度限制20,超過會失敗
      3. 以下演示代碼,生產環(huán)境還需進行優(yōu)化

      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、通過 appidsecret 獲取 token 超時 7200 秒 可 redis 緩存 官方文檔

      public String getToken() 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("grant_type", "client_credential");
      
              String url = handleParams("https://api.weixin.qq.com/cgi-bin/token", params);
              HttpGet httpGet = new HttpGet(url);
      
              CloseableHttpResponse response = httpClient.execute(httpGet);
              HttpEntity entity = response.getEntity(); // 響應結果
      
              return EntityUtils.toString(entity, CharSetType.UTF8.getType());
      }
      

      3、指定用戶推送消息結束 官方文檔

      public String pushMsg(String token) throws IOException {
      
              CloseableHttpClient httpClient = HttpClientBuilder.create().build();
              Map<String, Object> params = new HashMap<>();
      
              // 處理微信推送數(shù)據(jù)結構
              JSONObject mapData = new JSONObject();
              Map<String, Object> map1 = new HashMap<>();
              map1.put("value", "任務名稱");
              mapData.put("thing2", map1);
      
              Map<String, Object> map2 = new HashMap<>();
              map2.put("value", "2022-04-03 10:00:00");
              mapData.put("time3", map2);
      
              Map<String, Object> map3 = new HashMap<>();
              map3.put("value", "描述信息");
              mapData.put("thing4", map3);
      
              Map<String, Object> map4 = new HashMap<>();
              map4.put("value", "備注信息");
              mapData.put("thing10", map4);
      
              Map<String, Object> map5 = new HashMap<>();
              map5.put("value", "任務來源");
              mapData.put("thing11", map5);
      
              params.put("template_id", "templateId");// 模板 id
              params.put("touser", "openId"); // open id
              params.put("data", mapData); // 數(shù)據(jù)
              params.put("page", "page"); // 點擊模板卡片后的跳轉頁面,僅限本小程序內的頁面。支持帶參數(shù),(示例index?foo=bar)。該字段不填則模板無跳轉
              params.put("miniprogram_state", "trial"); //developer為開發(fā)版;trial為體驗版;formal為正式版;默認為正式版
              params.put("lang", "zh_CN"); //
      
              HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token);
              httpPost.addHeader("ContentTyp", "application/json");
      
              // 參數(shù)轉 JSON 格式
              String json = objToStr(params);
              StringEntity stringEntity = new StringEntity(json, CharSetType.UTF8.getType());
              stringEntity.setContentEncoding(CharSetType.UTF8.getType());
              httpPost.setEntity(stringEntity);
      
              CloseableHttpResponse response = httpClient.execute(httpPost);
              HttpEntity entity = response.getEntity(); // 響應結果
              return EntityUtils.toString(entity, CharSetType.UTF8.getType());
          }
      

      4、完整代碼

      import com.alibaba.fastjson.JSONObject;
      import com.fasterxml.jackson.core.JsonProcessingException;
      import com.fasterxml.jackson.databind.ObjectMapper;
      import com.github.chenlijia1111.utils.core.enums.CharSetType;
      import org.apache.http.HttpEntity;
      import org.apache.http.client.methods.CloseableHttpResponse;
      import org.apache.http.client.methods.HttpGet;
      import org.apache.http.client.methods.HttpPost;
      import org.apache.http.entity.StringEntity;
      import org.apache.http.impl.client.CloseableHttpClient;
      import org.apache.http.impl.client.HttpClientBuilder;
      import org.apache.http.util.EntityUtils;
      import org.jeecg.modules.video.utitls.Constants;
      
      import java.io.IOException;
      import java.io.UnsupportedEncodingException;
      import java.net.URLEncoder;
      import java.util.HashMap;
      import java.util.Map;
      import java.util.Objects;
      import java.util.Set;
      import java.util.stream.Collectors;
      
      /**
       * @description:
       * @author: Mr.Fang
       * @create: 2023-04-03 17:06
       **/
      
      public class HttpUtils {
      
          /**
           * description: 獲取token,返回結果為 JSON 自行轉 map
           * create by: Mr.Fang
           *
           * @return: java.lang.String
           * @date: 2023/4/3 17:46
           */
          public String getToken() 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("grant_type", "client_credential");
      
              String url = handleParams("https://api.weixin.qq.com/cgi-bin/token", params);
              HttpGet httpGet = new HttpGet(url);
      
              CloseableHttpResponse response = httpClient.execute(httpGet);
              HttpEntity entity = response.getEntity(); // 響應結果
      
              return EntityUtils.toString(entity, CharSetType.UTF8.getType());
          }
      
          /**
           * description: 獲取 open id,返回結果為 JSON 自行轉 map
           * create by: Mr.Fang
           *
           * @param: [code]
           * @return: java.lang.String
           * @date: 2023/4/3 17:46
           */
          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());
          }
      
          /**
           * description: 消息推送 返回結果為 JSON 自行轉 map;token 調用 getToken獲取
           * create by: Mr.Fang
           *
           * @param: [token]
           * @return: java.lang.String
           * @date: 2023/4/3 17:46
           */
          public String pushMsg(String token) throws IOException {
      
              CloseableHttpClient httpClient = HttpClientBuilder.create().build();
              Map<String, Object> params = new HashMap<>();
      
              // 處理微信推送數(shù)據(jù)結構
              JSONObject mapData = new JSONObject();
              Map<String, Object> map1 = new HashMap<>();
              map1.put("value", "任務名稱");
              mapData.put("thing2", map1);
      
              Map<String, Object> map2 = new HashMap<>();
              map2.put("value", "2023-04-03 12:00:00");
              mapData.put("time3", map2);
      
              Map<String, Object> map3 = new HashMap<>();
              map3.put("value", "描述信息");
              mapData.put("thing4", map3);
      
              Map<String, Object> map4 = new HashMap<>();
              map4.put("value", "備注系信息");
              mapData.put("thing10", map4);
      
              Map<String, Object> map5 = new HashMap<>();
              map5.put("value", "抖音");
              mapData.put("thing11", map5);
      
              params.put("template_id", "templateId");// 模板 id
              params.put("touser", "openId"); // open id
              params.put("data", mapData); // 數(shù)據(jù)
              params.put("page", "page"); // 點擊模板卡片后的跳轉頁面,僅限本小程序內的頁面。支持帶參數(shù),(示例index?foo=bar)。該字段不填則模板無跳轉
              params.put("miniprogram_state", "trial"); //developer為開發(fā)版;trial為體驗版;formal為正式版;默認為正式版
              params.put("lang", "zh_CN"); //
      
              HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token);
              httpPost.addHeader("ContentTyp", "application/json");
      
              // 參數(shù)轉 JSON 格式
              String json = objToStr(params);
              StringEntity stringEntity = new StringEntity(json, CharSetType.UTF8.getType());
              stringEntity.setContentEncoding(CharSetType.UTF8.getType());
              httpPost.setEntity(stringEntity);
      
              CloseableHttpResponse response = httpClient.execute(httpPost);
              HttpEntity entity = response.getEntity(); // 響應結果
              return EntityUtils.toString(entity, CharSetType.UTF8.getType());
          }
      
      
          /**
           * description: 對象轉 字符串
           * create by: Mr.Fang
           *
           * @param: [obj]
           * @return: java.lang.String
           * @date: 2023/4/3 17:45
           */
          public static String objToStr(Object obj) {
      
              ObjectMapper objectMapper = new ObjectMapper();
              if (Objects.nonNull(obj)) {
                  try {
                      String jsonStr = objectMapper.writeValueAsString(obj);
                      return jsonStr;
                  } catch (JsonProcessingException var2) {
                      var2.printStackTrace();
                  }
              }
      
              return null;
          }
      
          /**
           * description: map 轉 URL 地址拼接
           * create by: Mr.Fang
           *
           * @param: [url, params]
           * @return: java.lang.String
           * @date: 2023/4/3 17:45
           */
          public String handleParams(String url, Map<String, Object> params) {
              if (params.size() != 0) {
                  Set<Map.Entry<String, Object>> entries = params.entrySet();
                  String paramsString = entries.stream().map((e) -> {
                      try {
                          StringBuilder sb = new StringBuilder();
                          sb.append(URLEncoder.encode(e.getKey(), CharSetType.UTF8.getType()));
                          sb.append("=");
                          if (Objects.nonNull(e.getValue())) {
                              sb.append(URLEncoder.encode(e.getValue().toString(), CharSetType.UTF8.getType()));
                          }
      
                          return sb.toString();
                      } catch (UnsupportedEncodingException var2) {
                          var2.printStackTrace();
                          return null;
                      }
                  }).collect(Collectors.joining("&"));
                  return url + "?" + paramsString;
              }
              return url;
          }
      
      
      }
      
      
      posted @ 2023-04-03 18:06  天葬  閱讀(1933)  評論(0)    收藏  舉報
      主站蜘蛛池模板: 祁东县| 国99久9在线 | 免费| 巨熟乳波霸若妻在线播放| 老司机午夜精品视频资源| 一个人在线观看免费中文www| 国产精品亚洲国际在线看| 色悠悠在线观看入口一区| 亚洲综合伊人久久大杳蕉| 欧美老熟妇乱子伦牲交视频| 日韩一区国产二区欧美三区| 日韩午夜一区二区福利视频| 无极县| 人妻少妇偷人作爱av| 高清免费毛片| 国产福利高颜值在线观看| 高清国产一区二区无遮挡| 国产18禁黄网站禁片免费视频| 玩弄放荡人妻少妇系列| 成人无码午夜在线观看| 色婷婷五月综合亚洲小说| 国产综合久久久久鬼色| 日韩精品卡一卡二卡三卡四| 男女激情一区二区三区| 日产中文字幕在线精品一区| 亚洲欧美中文日韩V日本| 午夜国产理论大片高清| 欧美人与动交视频在线观看 | 亚洲人成在线播放网站| 国产精品呻吟一区二区三区| 亚洲色欲色欱WWW在线| 胶州市| 涩涩爱狼人亚洲一区在线| 日本一区不卡高清更新二区| 国产熟妇久久777777| 久久国产精品老女人| 久久天天躁夜夜躁狠狠ds005| 午夜福利国产精品视频| 日韩精品理论片一区二区| 色婷婷综合久久久中文字幕| 日本一区二区三区四区黄色| 人妻一区二区三区三区|