小程序授权

//wxml
<view wx:if="{{isHide}}">
    <view wx:if="{{canIUse}}" >
        <view class='header'>
            <image src='/images/1.png'></image>
        </view>
        <view class='content'>
            <view>申请获取以下权限</view>
            <text>获得你的公开信息(昵称,头像等)</text>
        </view>

        <button class='bottom' type='primary' open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="bindGetUserInfo">
            授权登录
        </button>
    </view>
    <view wx:else>请升级微信版本</view>
</view>
//js
const util = require('../../utils/util.js')
const app = getApp()
Page({
  data: {
    //判断小程序的API,回调,参数,组件等是否在当前版本可用。
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    isHide: true,
  },

  onLoad: function () {
   
  },

  bindGetUserInfo: function (e) {
    var that = this
    console.log(e)
    if (e.detail.errMsg == 'getUserInfo:ok') {
      //检查登录是否过期
      if (e.detail.userInfo) {
        //用户按了允许授权按钮
        var that = this;
        //授权成功后,通过改变 isHide 的值,让实现页面显示出来,把授权页面隐藏起来
        wx.getUserInfo({
          success: function (res) {
            wx.login({
              success: res => {
                // 获取到用户的 code 之后:res.code
                wx.request({
                  // 自行补上自己的 APPID 和 SECRET
                  url: app.globalData.url + "/key",
                  method: 'GET',
                  data: {
                    js_code: res.code
                  },
                  success: res => {
                    // 获取到用户的 openid
                    wx.setStorage({
                      key: "sessionKey",
                      data: res.data
                    })
                    //跳转页面
                    wx.navigateBack({
                      // url: '../index/index'
                    })
                  }
                })
              }
            });
          }
        });
      } else {
        //用户按了拒绝按钮
        wx.showModal({
          title: '警告',
          content: '您点击了拒绝授权,将无法进入小程序,请授权之后再进入!!!',
          showCancel: false,
          confirmText: '返回授权',
          success: function (res) {
            // 用户没有授权成功,不需要改变 isHide 的值
            if (res.confirm) {
              console.log('用户点击了“返回授权”');
            }
          }
        });
      }
    }
  }
})
原文地址:https://www.cnblogs.com/minghan/p/13273152.html