凡星
凡星
  • 发布:2021-04-27 12:40
  • 更新:2021-04-27 12:40
  • 阅读:617

公众号开发(七)uni-id自动注册和登录

分类:uni-app

在上一节我们得到openid之后,就可以在uni-id绑定用户,实现注册和登录功能了。

前端比较简单,只需要把openid提交给后端,由后端操作uni-id实现注册和登录,得到用户ID后缓存起来供后面的使用

完整的代码请在官方插件市场下载:https://ext.dcloud.net.cn/plugin?id=4829

async getUid() {  
                //如果缓存存在,则直接返回  
                let user = uniCloud.getCurrentUserInfo()  
                console.log('user', user);  
                if (user.uid) return user.uid  

                //如果openid不存在,自动先去获取openid  
                let openid = await this.getOpenid()  
                console.log('openid', openid);  
                if (!openid) return false  

                //后端使用openid实现自动注册和登录功能  
                let res = await this.bctosCommon('loginOrRegister', {  
                    openid  
                })  
                console.log('get res', res)  
                if (res.result.code === 0) {  
                    //返回成功,缓存uni-id相关信息  
                    uni.setStorageSync('uni_id_token', res.result.token)  
                    uni.setStorageSync('uni_id_token_expired', res.result.tokenExpired)  
                    uni.setStorageSync('uid', res.result.uid)  
                    return res.result.uid  
                } else {  
                    this.error(res.result.message)  
                    return false  
                }  
            }

后面的实现代码,直接使用openid作为用户名和密码进行注册,当然这个开发者也可以加点其它信息让密码复杂些。

            let param = {  
                username: event.openid,  
                password: event.openid  
            }  
            res = await uniID.login({  
                ...param,  
                queryField: ['username']  
            })  
            if (res.code == 10101 || res.code == 10002) {  
                console.log('need register')  
                param.wx_openid = event.openid  
                if (typeof(event.unionid) != "undefined") param.wx_unionid = event.unionid  
                res = await uniID.register(param)  
            }

它先使用uniID.login登录,如果错误提示码为10101或10002表示用户不存在,就先使用uniID.register完成注册和登录

这就是openid与用户ID实现绑定的逻辑,比较简单。

1 关注 分享
DCloud_uniCloud_JSON

要回复文章请先登录注册