【微信小程序开发】使用button标签的open-type="getUserInfo"引导用户去授权


一、 前言

小程序官方文档,上面说明

> wx.getUserInfo(OBJECT) 注意:此接口有调整,使用该接口将不再出现授权弹窗,请使用

<button open-type="getUserInfo"></button>

> 引导用户主动进行授权操作 > 当用户未授权过,调用该接口将直接报错 当用户授权过,可以使用该接口获取用户信息

如上文,之前用户未授权过时,调用wx.getUserInfo会调出授权框;但现在在用户未授权过时调用该接口,会直接走fail方法。

所以我们要使用上述button来请求用户授权。

## 二、主体 ##

index页面作为展示授权按钮的页面,并且在app.json中将index作为首页。在判断用户授权之后跳转到其他页面。

index.wxml

1
2
3
4
5
6
< button
     wx:if="{{canIUse}}"
     open-type="getUserInfo"
     bindgetuserinfo="bindGetUserInfo"
>授权登录</ button >
< view  wx:else>请升级微信版本</ view >

  index.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
Page({
   data: {
      //判断小程序的API,回调,参数,组件等是否在当前版本可用。
     canIUse: wx.canIUse( 'button.open-type.getUserInfo' )
   },
   onLoad:  function () {
     // 查看是否授权
     wx.getSetting({
       success:  function (res){
         if  (res.authSetting[ 'scope.userInfo' ]) {
           wx.getUserInfo({
             success:  function (res) {
               console.log(res.userInfo)
               //用户已经授权过
             }
           })
         }
       }
     })
   },
   bindGetUserInfo:  function (e) {
     console.log(e.detail.userInfo)
     if  (e.detail.userInfo){
       //用户按了允许授权按钮
     else  {
       //用户按了拒绝按钮
     }
   }
})


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM