Skip to content Skip to footer

小程序最新标准授权登录流程+逻辑

小程序自上线以来,官方一直在调整API,因此也出现了一批被废弃的接口,作为程序员的我们,此时此刻千万不能为这不断的变化而感到头疼,应当与时俱进,不断的更新自己的知识储备和应用技

新旧对比:旧的方法:旧方法wx.getUserInfo按照用户登录时,弹出需要授权的弹窗,用户点击授权后才能使用。

新方法:Open-data的灵活使用方法,不会让你直接获得用户信息,而是小程序点击登录按钮获取用户头像,就是使用 button 组件,并将 open-type 指定为 getUserInfo 类型,获取用户基本信息。

最终登录流程如下:(其实简单的说就是多了一个button 组件步骤)

5640239-3c8f08f58a8a3645.png5640239-16fe8206bdbc49ba.png写个demowxml

代码语言:javascript复制

请升级微信版本js:

代码语言:javascript复制Page({

data: {

canIUse: wx.canIUse('button.open-type.getUserInfo')

},

onLoad: function () {

// 查看是否授权

wx.getSetting({

success(res) {

if (res.authSetting['scope.userInfo']) {

// 已经授权,可以直接调用 getUserInfo 获取头像昵称

wx.getUserInfo({

success: function (res) {

console.log(res.userInfo)

}

})

}

}

})

},

bindGetUserInfo(e) {

console.log(e.detail.userInfo)

}

})实现效果:获得用户授权的信息,头像和昵称

5640239-388ed965acf0c419.gif来一份默认的demo:(复制黏贴的~)

index.wxml

代码语言:javascript复制

{{userInfo.nickName}}

{{motto}}

index.wxss

代码语言:javascript复制/**index.wxss**/

.userinfo {

display: flex;

flex-direction: column;

align-items: center;

}

.userinfo-avatar {

width: 128rpx;

height: 128rpx;

margin: 20rpx;

border-radius: 50%;

}

.userinfo-nickname {

color: #aaa;

}

.usermotto {

margin-top: 200px;

}index.js

代码语言:javascript复制//index.js

//获取应用实例

const app = getApp()

Page({

data: {

motto: 'Hello World',

userInfo: {},

hasUserInfo: false,

canIUse: wx.canIUse('button.open-type.getUserInfo')

},

//事件处理函数

bindViewTap: function() {

wx.navigateTo({

url: '../logs/logs'

})

},

onLoad: function () {

if (app.globalData.userInfo) {

this.setData({

userInfo: app.globalData.userInfo,

hasUserInfo: true

})

} else if (this.data.canIUse){

// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回

// 所以此处加入 callback 以防止这种情况

app.userInfoReadyCallback = res => {

this.setData({

userInfo: res.userInfo,

hasUserInfo: true

})

}

} else {

// 在没有 open-type=getUserInfo 版本的兼容处理

wx.getUserInfo({

success: res => {

app.globalData.userInfo = res.userInfo

this.setData({

userInfo: res.userInfo,

hasUserInfo: true

})

}

})

}

},

getUserInfo: function(e) {

console.log(e)

app.globalData.userInfo = e.detail.userInfo

this.setData({

userInfo: e.detail.userInfo,

hasUserInfo: true

})

}

})附上wx.getUserInfo(Object object)文档:

https://developers.weixin.qq.com/miniprogram/dev/api/wx.getUserInfo.html

其实这些都不需要写代码的,新建一个普通的项目里面,都已经默认写好了哦。

原文作者:祈澈姑娘。 技术博客:https://www.jianshu.com/u/05f416aefbe1

90后前端妹子一枚,爱编程,爱运营,爱折腾。长期坚持总结工作中遇到的技术问题。

Copyright © 2088 易化太极武侠游戏活动平台 All Rights Reserved.
友情链接