PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

微信小程序开发之用户授权登录

coldplay.xixi
coldplay.xixi 转载
2021-03-25 10:22:02 2680浏览

准备:

微信开发者工具下载地址:https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html

微信小程序开发文档:https://developers.weixin.qq.com/miniprogram/dev/index.html

开发:

在开发之初,我们需要先明确微信方已经制定好的授权登陆流程,参看 官方API - 登陆接口。

你会看到微信方为开发者制定好的登陆授权流程:

 

 

如图,即为一个顺向的用户登陆授权的流程。

为什么说它是一个顺向的流程呢?因为在真正的小程序开发中,我们并不确定用户何时需要起调如上的登陆流程(如:用户在某些特定场景下的凭证丢失,但Ta并没有退出小程序而是在小程序内部做跳转等相关操作,即有可能导致一些预期之外的异常),所以,我们需要在这个顺向的流程之外,加一层检测机制,来解决这些异常场景,而官方API中,wx.checkSession 刚好可以一定程度上解决这个问题。

那么,我们的认证流程其实应该是:

- 小程序 wx.checkSession 校验登陆态为失效

    - success :接口调用成功的回调函数,session_key未过期,流程结束;    

    - fail :接口调用失败的回调函数,session_key已过期

        -》 小程序端 wx.login 获取code 并 wx.request 提交code给己方服务器

        -》 己方服务器 提交Appid + appSecret + code 到微信方服务器 获取 session_key & openid

        -》 己方服务器 根据 session_key & openid  生成 3rd_session(微信方提出的基于安全性的考虑,建议开发者不要将openid等关键性信息进行数据传输) 并返回 3rd_session 到小程序端

        -》 小程序端 wx.setStorage 存储 3rd_session ( 在后续用户操作需要凭证时 附带该参数 )

        -》 小程序端 wx.getUserInfo 获取用户信息 + wx.getStorage 获取 3rd_session 数据后,一并 wx.request 提交给己方服务器

         -》 己方服务器 SQL用户数据信息更新,流程结束;

思路整理完毕,接下来实现流程

小程序端:

在小程序中,新建一个通用的JS做基础支持

并在一些需要引用的页面进行引用

var common = require("../Common/Common.js")

接着,在Common.js 中实现逻辑

//用户登陆
function userLogin() {
  wx.checkSession({
    success: function () {
      //存在登陆态
    },
    fail: function () {
      //不存在登陆态
      onLogin()
    }
  })
}

function onLogin() {
  wx.login({
    success: function (res) {
      if (res.code) {
        //发起网络请求
        wx.request({
          url: 'Our Server ApiUrl',
          data: {
            code: res.code
          },
          success: function (res) {
            const self = this
            if (逻辑成功) {
              //获取到用户凭证 存儲 3rd_session 
              var json = JSON.parse(res.data.Data)
              wx.setStorage({
                key: "third_Session", 
                data: json.third_Session
              })
              getUserInfo()
            }
            else {

            }
          },
          fail: function (res) {

          }
        })
      }
    },
    fail: function (res) {
  
    }
  })

}

function getUserInfo() {
  wx.getUserInfo({
    success: function (res) {
      var userInfo = res.userInfo
      userInfoSetInSQL(userInfo)
    },
    fail: function () {
      userAccess()
    }
  })
}

function userInfoSetInSQL(userInfo) {
  wx.getStorage({
    key: 'third_Session',
    success: function (res) {
      wx.request({
        url: 'Our Server ApiUrl',
        data: {
          third_Session: res.data,
          nickName: userInfo.nickName,
          avatarUrl: userInfo.avatarUrl,
          gender: userInfo.gender,
          province: userInfo.province,
          city: userInfo.city,
          country: userInfo.country
        },
        success: function (res) {
          if (逻辑成功) {
            //SQL更新用户数据成功
          }
          else {
            //SQL更新用户数据失败
          }
        }
      })
    }
  })
}

至此,小程序端的流程基本实现完毕,接着实现己方服务API

Login 接口逻辑范例

 if (dicRequestData.ContainsKey("CODE"))
        {
            string apiUrl = string.Format("https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", ProUtil.SmartAppID, ProUtil.SmartSecret, dicRequestData["CODE"]);
        
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(apiUrl);
            myRequest.Method = "GET";
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            string content = reader.ReadToEnd();
            myResponse.Close();
            reader.Close();
            reader.Dispose();

            //解析
            userModel ReMsg = JSONUtil.JsonDeserialize<userModel>(content); //解析
            if ((!string.IsNullOrWhiteSpace(ReMsg.openid)) && (!string.IsNullOrWhiteSpace(ReMsg.session_key)))
            {
                // 成功 自定义生成3rd_session与openid&session_key绑定并返回3rd_session

            }
            else
            {
                // 错误 未获取到用户openid 或 session
            }
        }
        else
        {
            // 错误 未获取到用户凭证code
        }

UserInfoUpdate 接口在此不加赘述,用户根据自身情况对数据进行操作即可,微信方调用成功时返回的相关参数信息如下

至此,完成了小程序基本的授权登陆及用户信息的获取。

声明:本文转载于:CSDN,如有侵犯,请联系admin@php.cn删除