【微信小程序開發】使用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