微信小程序获取用户openId以及用户授权状态
我使用mpvue写的小程序 写法和写vue一样 最后转换成小程序 里面的逻辑都一样 vue的钩子和小程序的都可以用
现在假设一个场景 通过用户点击授权登录 拿取到小程序提供的code 之后把这个code给后端 之后就可以拿到openid了 这里温馨提醒下 小程序获取用户信息 不再提供用 wx.getUserInfo({ // 2021年4月份已经废弃 建议使用getUserProfile 最后图解说明 success (res) { console.log(res.userInfo) } }) 的弹窗形式调用 转而用下面的 button 标签 加 open-type="getUserInfo" 配合 @getuserinfo="onGotUserInfo" 来获取 利用 @getuserinfo="onGotUserInfo" 回调 拿到用户信息
这个有调用顺序 先调用 getUserProfile 获取用户信息 ,再调用wx.login换取code
获取用户授权状态
getSetting
html部分
<div class='accreditBox'> <img :src="accreditImg" alt=""> <h2>中港通智慧出行</h2> <div clsss='accreditHint'>请点击“授权登录”,以便您正常使用购票功能</div> <div class='accreditBtn'> <button :withCredentials="true" open-type="getUserInfo" lang="zh_CN" @getuserinfo="onGotUserInfo" >授权登录 </button> </div> </div>
js部分
async onGotUserInfo (data) { // 利用 @getuserinfo="onGotUserInfo" 回调 拿到用户信息 console.log('data', data) // 获取code await this.$getLoginCode() //封装调用 封装 方法我写下面了 this.$post('https://devapi.isouth.com/userinfo/miniProgramOauth', { code: wx.getStorageSync('userCode') } ).then(data => { // 获取到了 openid 用户唯一标识 然后用 wx.setStorageSync 存起来 wx.setStorageSync('userOpenid', data) }).catch(err => { console.log('获取失败', err) }) }
上面调用this.$getLoginCode()说明
上面拿取code的封装 新建一个js 文件 例如命名 util /** * 拿取 code * @param {code} */ function getLoginCode () { return new Promise(resolve => { wx.login({ success (res) { wx.setStorageSync('userCode', res.code) resolve(res.code) } }) }) } // 暴露出来 如果想取别名 则可以用as来代理 getLoginCode as getCode export { getLoginCode }
上面这个util 文件弄好后 将这个文件引入到main.js中
import {getLoginCode} from './utils/index'
//注入到原型 Vue.prototype.$getLoginCode = getLoginCode
之后就可以愉快地玩耍了
在页面中直接 this.$getLoginCode() 引用即可
用了Promise 防止拿不到 可以像上面一样用async 与 await
getUserInfo接口变更说明
第一步:替换原有的 <button open-type="getUserInfo"/> 标签为普通标签,例如:
<button bindtap="getUserInfo"> 获取头像昵称 </button>
在页面的 .js 文件中创建一个对应的方法 getUserInfo(如果以前就有可以直接修改):
getUserInfo: function (e) { //... }
第二步:在 getUserInfo 代码中调用 wx.getUserProfile 接口:
getUserProfile(e) { // 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认 // 开发者妥善保管用户快速填写的头像昵称,避免重复弹窗 wx.getUserProfile({ desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写 success: (res) => { this.setData({ userInfo: res.userInfo, hasUserInfo: true }) } }) }
具体参考 https://www.cnblogs.com/szw/p/14632314.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示