• 要做小程序的订阅推送 本篇 从小程序到后端!!!


    小程序模板消息即将被废弃掉,于是有了新接口wx.requestSubscribeMessage ----订阅消息推送

    本篇将带你感受一下订阅推送的坑坑洼洼

    前期准备工作申请订阅消息模板 id appid 等自行准备

    话不多说直接上代码!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    小程序端

    app.js

    //app.js
    App({
      onLaunch: function () {
        // 展示本地存储能力
        var logs = wx.getStorageSync('logs') || []
        logs.unshift(Date.now())
        wx.setStorageSync('logs', logs)
       
        var that = this
        var user = wx.getStorageSync('user') || {};
        var userInfo = wx.getStorageSync('userInfo') || {};
      
        // 登录
        wx.login({
          success: res => {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            //获取openid___________________________________________开始
            that.globalData.code = res.code
                if (res.code) {
                 
                  wx.getUserInfo({
                    success: function (res) {
                    
                      var objz = {};
                      objz.avatarUrl = res.userInfo.avatarUrl;
                      objz.nickName = res.userInfo.nickName;
    
                      wx.setStorageSync('userInfo', objz);//存储userInfo
                    
                    },
                    fail: function (e) {
                    
                    }
                  });
    
                  var d = that.globalData;//这里存储了appid、secret、token串  
                 
                  var l = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + d.appid + '&secret=' + d.secret + '&js_code=' + res.code + '&grant_type=authorization_code';
                  wx.request({
                    url: l,
                    data: {},
                    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT  
                    // header: {}, // 设置请求的 header  
                    success: function (res) {
                   
                      var obj = {};
                      obj.openid = res.data.openid;
                      obj.expires_in = Date.now() + res.data.expires_in;
                      console.log(obj.openid);
                      wx.setStorageSync('userop', obj);//存储openid  
                    }
                  });
                } else {
                  console.log('获取用户登录态失败!' + res.errMsg)
                }
                //获取openid___________________________________________结束
          }
        })
        // 获取用户信息
        wx.getSetting({
          success: res => {
            if (res.authSetting['scope.userInfo']) {
              // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
              wx.getUserInfo({
                success: res => {
                  // 可以将 res 发送给后台解码出 unionId
                  this.globalData.userInfo = res.userInfo
    
                  // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
                  // 所以此处加入 callback 以防止这种情况
                  if (this.userInfoReadyCallback) {
                    this.userInfoReadyCallback(res)
                  }
                }
              })
            }
          }
        })
      },
      globalData: {
           url:"http://192.168.0.199:8888/app",
           appid: '微信appid',//微信appid
           secret: '秘钥',//秘钥
           userInfo: null
      }
    })

    index.js

    //登录
      login:function(){
        if(!this.data.userName){
          wx.showToast({
            title: '用户名不能为空',
            icon:'none'
          })
          return;
        }
        if (!this.data.pwd) {
          wx.showToast({
            title: '密码不能为空',
            icon: 'none'
          })
          return;
        }
        wx.showLoading({});
        wx.setStorageSync("cid",this.guid());
        wx.request({
          url: app.globalData.url + '/Login/appLogin',
          data:{
            username: this.data.userName,
            password: this.data.pwd,
            clientId: wx.getStorageSync("cid"),
            openid: wx.getStorageSync('userop').openid
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded',
            'X-Requested-With':'XMLHttpRequest'
          },
          method:"POST",
          success:function(res){
            if(res.data.status == 200){
              wx.setStorageSync("user", res.data.user);
              wx.removeStorageSync('sessionid');
              wx.setStorageSync("sessionid", res.cookies[1]);
              wx.switchTab({
                url: '/pages/main/main'
              });
              return;
            }else{
              wx.showToast({
                title: '用户名或密码错误',
                icon: 'none'
              })
            }
          }
        });

    获取到openid之后直接就从你的登录方法往后端传就行 后端接收后存到相应的表里 下次登录给挂个标识 表里对应的useid有就不存了 没有就存 如果有redis可以做缓存 避免给数据库造成太大的压力

    当然这只是小程序获取openi的第一步

    后端代码给您您

    微信个推的工具类 自己写的用的话可以根据自己的需求改改

     1 package com.jeesite.modules.sys.utils;
     2 
     3 import com.alibaba.fastjson.JSONObject;
     4 import com.jeesite.common.wx.TemplateDataVo;
     5 import com.jeesite.common.wx.WxMssVo;
     6 import lombok.extern.slf4j.Slf4j;
     7 import org.springframework.http.ResponseEntity;
     8 import org.springframework.stereotype.Component;
     9 import org.springframework.web.client.RestTemplate;
    10 import java.util.HashMap;
    11 import java.util.Map;
    12 
    13 /**
    14  * @Author wm
    15  * @Description wx小程序发送工具
    16  * @Date 2020/4/278:22
    17  **/
    18 
    19 @Slf4j
    20 @Component
    21 public class WeChatPushUtils {
    22 
    23 
    24 
    25     /**
    26      *
    27      * @param openid 用户openid
    28      * @param templateDataVo 模板消息
    29      * @return
    30      */
    31     public static String pushOneUser( String openid,TemplateDataVo templateDataVo) {
    32         RestTemplate restTemplate = new RestTemplate();
    33         //自动获取token
    34         String access_token = getAccess_token();
    35         String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + access_token; //微信请求接口
    36         //封装模板数据
    37         WxMssVo wxMssVo = new WxMssVo();
    38         //用户openid
    39         wxMssVo.setTouser(openid);
    40         Map<String,Object> data = new HashMap<>();
    41         data.put("number2",templateDataVo.getNumber2());
    42         data.put("name1",templateDataVo.getName1());
    43         wxMssVo.setData(data);
    44         ResponseEntity<String> responseEntity = restTemplate.postForEntity(url,JSONObject.toJSON(wxMssVo).toString(),String.class);
    45         log.info("小程序推送结果={}", responseEntity.getBody());
    46         return responseEntity.getBody();
    47     }
    48 
    49     /**
    50      * 获取access_token
    51      * appid和appsecret到小程序后台获取,当然也可以让小程序开发人员给你传过来
    52      * */
    53     public static   String getAccess_token() {
    54         RestTemplate restTemplate = new RestTemplate();
    55         //获取access_token
    56         String appid = "微信appid";
    57         String appsecret = "密钥";
    58         String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
    59                 "&appid=" + appid + "&secret=" + appsecret; //获取token
    60         if(restTemplate==null){
    61             restTemplate = new RestTemplate();
    62         }
    63         String json = restTemplate.getForObject(url, String.class);
    64         JSONObject myJson = JSONObject.parseObject(json);
    65         return myJson.get("access_token").toString();
    66     }
    67 }

    这里面不得不说的几个坑  我的天那选的模板 一定一定要根据微信公众平台提供的例子去封装 一定一定一定 别自己随便去封装什么实体 最底层的key就是value

    不解释了我截个图去

     也别说了 看图宝贝 接口很隐秘网址先po出来https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html

    看右边大红框里面的data值 就是你申请的模板对应的相关字段 data 比如你申请的字段是 thing1 name你写的方式就是

    data{
    thing1:{
    value:"thing1的值"
    }
    }
    

     对没错 value 就是每个字段值的key

    这就是那个坑封装的坑 如果想实体封装太麻烦 建议JSONOBJECT简单粗暴

    但是!!!!但是 到了这一步即使你传进去了模板id openid 想发请求 不好意思  不行行!!!!!!!!

    下面我们来看看原因

    还是看图 步骤一的数据都有了  详情网址:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/subscribe-message.html

    那步骤二呢  用户没订阅发个XX............

    下面就得让openid这个用户订阅一下  

    上!!!代!!!!码!!!!!

    我是这样做的

     加了一个按钮 ,用户点了就是这样的

     虽然有点丑 功能是有了

    代码标签

    1 <button bindtap="subTap"   type="defaults" style=" background-color:#98F898;95%;margin:20px 10px;">订阅消息<text>{{textcontent}}</text></button>

    函数

     1 //订阅消息开启
     2 data: {
     3   textcontent: '提示:未开启'
     4 },
     5 
     6 // 检测是否开启  更新提示
     7 testingTap: function() {
     8   let that = this;
     9   wx.getSetting({
    10     withSubscriptions: true,
    11     success(res) {
    12       console.log(res)
    13       if (res.subscriptionsSetting.mainSwitch) {
    14         if (res.subscriptionsSetting.itemSettings != null) {
    15           let item = res.subscriptionsSetting.itemSettings.模板id
    16           console.log(item)
    17           if (item == "reject") {
    18             that.setData({
    19               textcontent: '提示:您已经拒绝订阅消息'
    20             })
    21           } else if (item == "accept") {
    22             that.setData({
    23               textcontent: '提示:您已经开启订阅消息'
    24             })
    25           } else if (item == "ban") {
    26             that.setData({
    27               textcontent: '提示:您已经被后台封禁'
    28             })
    29           }
    30         }
    31       } else {
    32         that.setData({
    33           textcontent: '提示:订阅消息未开启'
    34         })
    35       }
    36     }
    37   })
    38 },
    39 
    40 //授权
    41 subTap: function() {
    42   let that = this;
    43   wx.requestSubscribeMessage({
    44     tmplIds: ['模板id'],
    45     success(res) {
    46       if(res.模板id=="accept"){
    47         that.setData({
    48           textcontent: '提示:授权成功'
    49         })
    50       }else{
    51         that.setData({
    52           textcontent: '提示:未授权'
    53         })
    54       }
    55     },
    56     fail(res) {
    57   
    58       that.setData({
    59         textcontent: '提示:授权失败'
    60       })
    61     }
    62   })
    63 }

    这样用户订阅了之后才能发送 .........快去试试吧

    本文为原创当然写的时候太草率 有诸多问题没有说明 但是代码你只要有点基础 放对地方了绝对 下面附成功图

     如果有什么问题加QQ:592322684 我乐于助人 有啥不会的咱俩一块不会.........嘿嘿

    离开电脑之后整个人都是清醒的
  • 相关阅读:
    App案例分析——XBMC
    四则运算题目生成程序(基于控制台)
    第一次结对编程
    第二次作业--摩拜单车
    第0次作业
    团队编程作业1-团队展示与选题
    结对编程1-模块化
    APP案例分析
    第1次作业
    第0道作业
  • 原文地址:https://www.cnblogs.com/C1own/p/12801087.html
Copyright © 2020-2023  润新知