小程序授权
一、小程序在使用用户的个人信息的时候需要授权方法如下
1、WXML
1 2 3 4 5 6 | <!--index.wxml--> < view class="container"> < view class="userinfo"> < button open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取用户信息 </ button > </ view > </ view > |
2、js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | //index.js //获取应用实例 const app = getApp() Page({ data: { userInfo: {}, // 判断当前版本button.open-type.getUserInfo方法是否可用 canIUse: wx.canIUse( 'button.open-type.getUserInfo' ) }, 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) { // 点击允许返回用户信息 // 点击拒绝返回undefined console.log(e) app.globalData.userInfo = e.detail.userInfo this .setData({ userInfo: e.detail.userInfo, hasUserInfo: true }) } }) |
3、app.js(这里的判断哪些授权可根据需要选择是否需要)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | //app.js App({ onLaunch: function () { // 登录 wx.login({ success: res => { // 发送 res.code 到后台换取 openId, sessionKey, unionId } }) // 获取用户信息 wx.getSetting({ success: res => { if (res.authSetting[ 'scope.userInfo' ]) { // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框 wx.getUserInfo({ success: res => { // 可以将 res 发送给后台解码出 unionId this .globalData.userInfo = res.userInfo // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回 // 所以此处加入 callback 以防止这种情况 if ( this .userInfoReadyCallback) { this .userInfoReadyCallback(res) } } }) } } }) }, globalData: { userInfo: null } }) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类