前端开发微信小程序用户登录

 

前端开发金融业务流程外包
前端实际开发流程
前端开发流程

小程序登录逻辑

1. 从缓存中读取token,如果有则说明用户已经登陆过小程序了
2. 如果没有token,则说明用户第一次登录
3. 拿到用户的code,在服务端获取openid,同时生成token,返回前端,保存到本地

小程序代码

App({
    onLaunch: function() {
        //调用api从本地缓存中获取token
        var token = wx.getStorageSync(‘token’) || ”
        console.info(‘从本地缓存中获取token数据’)
        if (token == null || token == ”) {
            var that = this
            console.info(‘token is null’)
            that.login()
        } else {
            console.info(‘token is not null’)
        }
    },
    //登录接口,登陆成功后设置全局用户信息
    login: function() {
        //获取授权码code
        wx.login({
            success: function(res) {
                console.info(‘授权码code’)
                var code = res.code
                console.info(code)
                if (code) {
                    //获取用户信息接口
                    wx.getUserInfo({
                        success: function(res) {
                            var userInfo = res.userInfo
                            var nickName = userInfo.nickName
                            var avatarUrl = userInfo.avatarUrl
                            //调用后端登录接口
                            wx.request({
                                url: ‘http://127.0.0.1:3000/login’,
                                data: {
                                    nickName: nickName,
                                    avatarUrl: avatarUrl,
                                    code: code,
                                },
                                success: function(res) {
                                    console.info(res.data)
                                    wx.setStorageSync(
                                        ‘token’,
                                        res.data.usertoken,
                                    )
                                },
                                fail: function(res) {
                                    console.info(‘获取token失败’)
                                    console.info(res)
                                },
                            })
                        },
                    })
                } else {
                    console.info(‘获取用户登录凭证失败’)
                }
            },
        })
    },
})

后端使用的是Express+Mongodb来实现用户登录

unity前端开发流程
小公司前端开发流程
前端开发的流程

 

» 本文来自:前端开发者 » 《前端开发微信小程序用户登录》
» 本文链接地址:https://www.rokub.com/7850.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!