微信小程序获取用户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

 

posted @ 2018-01-20 17:47  Model-Zachary  阅读(72)  评论(0编辑  收藏  举报