小程序登录操作

 

 

小程序中提供了内部接口wx.login,可参考官方文档

但是login接口只是获取登录凭证code。

真正算登录需要获取到openid,session_key,openid是小程序对外开发的身份的唯一标识,相当于用户id,这个获取过程一般都是在服务器中进行,获取成功后传给小程序保存到本地。

服务器通过请求地址: https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

appid:是小程序的开发id
secret:
js_code:wx.login的返回值code
grant_type:官方示例只需要写authorization_code

对于有需要登录的小程序,此过程需要在app.js中使用,app相当于初始调用

在使用小程序时,先判断当前Session是否过去,wx.checkSession,官方文档,如果过期在调用登录接口

App({
  onLaunch: function () {
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        traceUser: true,
      })
    }
    this.globalData = {}

    wx.checkSession({
      success: (res) => {
        console.log("未过期")
      },
      fail:(res)=>{
        console.log("已过期")
        wx.login({
          timeout: 3000,
          success:(res)=>{
            console.log(res.code)
            if(res.code){
              wx.request({
                url: 'url',
                data:{
                  "code":res.code
                },
                success:(res)=>{
                  console.log("服务器请求接口成功")
            wx.setStorageSync('session_key', res.data.session_key)
                    wx.setStorageSync('openid', res.data.openid) 
 
            
                },
                fail:(res)=>{
                  console.log("服务器请求错误")
                }
              })
            }
          },
          fail:(res)=>{
            console.log("login登录失败")
          }
        })
      }
    })
    }
})

 

 

 

 

posted @ 2020-09-23 19:28  TestingShare  阅读(192)  评论(0编辑  收藏  举报