美文网首页前端开发那些事儿
微信小程序 前端静默登录 获取openid和session_ke

微信小程序 前端静默登录 获取openid和session_ke

作者: 安徒生1997 | 来源:发表于2021-02-19 16:59 被阅读0次

    1.app.js

    // 登录

    globalData: {

        userInfo: null

      },

    onLaunch() {

     var that=this;

        wx.login({

          success: res => {

            var code = res.code,appId = 'xxxxxxxxxxxxxxxxx',secret = 'xxxxxxxxxxxxxxxxx';

            // 发送 res.code 到后台换取 openId, sessionKey, unionId

            wx.request({

              url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appId + '&secret=' + secret + '&js_code=' + code + '&grant_type=authorization_code',

              data: {},

              header: {

                'content-type': 'json'

              },

              success: function (res) {

                // var openid = res.data.openid //返回openid

                that.globalData.userInfo=res.data;

                //由于这里是网络请求,可能会在 Page.onLoad 之后才返回  所以此处加入 userInfoReadyCallback 以防止这种情况

                if (that.userInfoReadyCallback) {

                  that.userInfoReadyCallback(res.data)

                }

              }

            })

          }

        })

    }

    2.index.js

    onLoad() {

        app.userInfoReadyCallback=res=>{

          this.setData({

            userInfo:app.globalData.userInfo

          });

        }

      },

    相关文章

      网友评论

        本文标题:微信小程序 前端静默登录 获取openid和session_ke

        本文链接:https://www.haomeiwen.com/subject/okiaxltx.html