当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 微信小程序登录态和检验注册过没的app.js写法

微信小程序登录态和检验注册过没的app.js写法

2019年07月20日  | 移动技术网IT编程  | 我要评论

0、可参考的官方页面

获取登录凭证:
检查登录态是否过期: https://developers.weixin.qq.com/miniprogram/dev/api/wx.checksession.html

备注:你要明白什么是登录态:这里的登录态是微信小程序自己的登录态,我们可以再自己写个登录页面作为自己的登录态,不过为了用户体验良好我直接以微信登录态做为自己的登录态。所以我的整个小程序是直接自动登录的

 注意:微信小程序缓存很容易被清除,所以你必须时刻提防小程序缓存被清除的状态下怎么处理。

备注:我从后台返回来给小程序的对象格式为:

 public resultcode resultcode; // 业务响应码
 public string resultmsg = ""; // 返回信息描述
 public string errcode; // 错误代码
 public string errcodedes = ""; // 错误描述
 public object data; // 返回业务数据
  public enum resultcode {
  success, // 业务处理成功
  fail; // 业务处理失败
 }

1、流程

(1)调用wx.checksession检查用户登录态是否过期,如果没有过期就检查用户注册没注册①,如果过期了就去重新执行登录流程②

(2)②的流程为:调用wx.login来获取登录凭证(code),然后把code发给后台,后台调用 auth.code2session,使用 code 换取 openid 等信息来获取openid , 把openid返回给小程序, 然后把openid放到小程序缓存里面,然后检查用户注册没注册①

(3)①的流程为:先从缓存查该用户注册没注册过(通过检查缓存变量registered存不存在),有就是老用户,没有就去后台通过openid查有没有这个用户,把结果返回给小程序,如果后台有这个用户,说明已经注册过,就把在缓存里加个registered并赋值true。

 (4)然后我们就可以在其他页面通过registered来判断用户注册没注册过,从而跳转进入注册页面或者是主页

2、app.js代码

app({
   globaldata: {
    serverhost: 'http://localhost:8080', //服务器域名
   },
   onlaunch: function() {
    var that = this;
    //检查登录态是否过期
    wx.checksession({
     success() {
      // session_key 未过期,并且在本生命周期一直有效
      console.log("【用户小程序登录态未过期】");
      that.isregister();
     },
     fail() {
      // session_key 已经失效,需要重新执行登录流程
      that.wxlogin();
     }
    })
   },
   //查看当前用户是否已经注册过
   isregister: function() {
    var that = this;
    var host = this.globaldata.serverhost;
    // (先从缓存查该用户,有就是老用户,没有就后台查有没有这个用户,后台查到有这个用户就放缓存,没有就是新用户)
    wx.getstorage({
     key: 'registered',
     success(res) {
      console.log("【通过缓存查询到该用户是已经注册过的】");
      console.log("【当前用户的openid为:】" + wx.getstoragesync('openid'));
     },
     fail(res) {
      var openid;
      openid = wx.getstoragesync('openid');
      wx.request({
       url: host + '写自己的后台请求检查用户存不存在的url',
       method: 'post',
       data: {
        openid: openid,
       },
       header: {
        "content-type": "application/x-www-form-urlencoded"
       },
       success: (res) => {
        if (后台返回注册过") {
         if (res.data.data) {
          console.log("【通过后台查询到该用户已经注册过】");
          wx.setstorage({
           key: "registered",
           data: true
          });
         } else {
          console.log("【通过后台查询到该用户还没注册过】");
         }
        }
       }
      })
     },
    })
   },
   //该函数用来登录的
   wxlogin: function() {
    var that = this;
    //设置后台host
    var host = this.globaldata.serverhost;
    console.log("【用户重新执行小程序登录流程】");
    wx.login({
     success(res) {
      // 发起网络请求,发送 res.code 到后台换取 openid
      if (res.code) {
       var code = res.code;
       wx.request({
        url: host + '写自己后台用code换取openid的请求url',
        method: 'post',
        data: {
         code: code,
        },
        header: {
         "content-type": "application/x-www-form-urlencoded"
        },
        success: (res) => {
         console.log("【获取用户openid成功】");
         console.log("【从后台获取到用户openid为】" + res.data.data.openid)
         let openid = res.data.data.openid;
         wx.setstorage({
          key: "openid",
          data: res.data.data.openid
         });
         console.log("【用户openid放入缓存成功】");
         that.isregister();
        }
       })
      }
     }
    })
   },
 },
})

3、java后台怎么通过code获取openid

import net.sf.json.jsonobject;
/**
 * @author niqinhua
 * @date 2019/3/8 9:19
 */
public class wxutil {
  public static jsonobject getopenidandsessionkey(string code) {
    string url = "https://api.weixin.qq.com/sns/jscode2session";
    string param = "appid=写自己的appid&secret=写自己的密钥&js_code=" +
         code + "&grant_type=authorization_code";
    string wxreturnresult = sendget(url, param);
    jsonobject wxreturnresultobject = jsonobject.fromobject(wxreturnresult);
    return wxreturnresultobject;
  }
 /**
   * 从规范上,建议把这个方法抽出来放到httputil类里面
   * 向指定url发送get方法的请求
   * @param url 发送请求的url
   * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
   * @return url 所代表远程资源的响应结果
   */
  public static string sendget(string url, string param) {
    string result = "";
    bufferedreader in = null;
    try {
      string urlnamestring = url + "?" + param;
      url realurl = new url(urlnamestring);
      // 打开和url之间的连接
      urlconnection connection = realurl.openconnection();
      // 设置通用的请求属性
      connection.setrequestproperty("accept", "*/*");
      connection.setrequestproperty("connection", "keep-alive");
      connection.setrequestproperty("user-agent", "mozilla/4.0 (compatible; msie 6.0; windows nt 5.1;sv1)");
      // 建立实际的连接
      connection.connect();
      // 定义 bufferedreader输入流来读取url的响应
      in = new bufferedreader(new inputstreamreader(
          connection.getinputstream()));
      string line;
      while ((line = in.readline()) != null) {
        result += line;
      }
    } catch (exception e) {
      system.out.println("【http发送get请求出现异常】:访问url:"+url+",错误:"+e.getmessage());
    }
    // 使用finally块来关闭输入流
    finally {
      try {
        if (in != null) {
          in.close();
        }
      } catch (exception e2) {
        system.out.println("【http请求关闭输入流异常】:访问url:"+url+",错误:"+e2.getmessage());
      }
    }
    return result;
  }
}

上面只是工具类直接拿就行,真正业务逻辑要自己写,我只给出重点部分

jsonobject wxreturnjson = wxutil.getopenidandsessionkey(code);
if (wxreturnjson.get("errcode")!=null) {
  //log.error("【获取用户的openid】【失败】【传递参数code无效】");
} else {
  //log.info("【获取用户的openid】【成功】【传递参数code无效】");
}

总结

以上所述是小编给大家介绍的微信小程序登录态和检验注册过没的app.js写法,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网