uni-app微信小程序登錄授權


微信小程序授權是非常簡單和常用的功能,但為了方便,還是在此記錄一下要點:

 

 

首先是需要用到一個授權按鈕來觸發獲取用戶信息授權: 關鍵在於 open-type 為 getUserInfo , 然后有個@getuserinfo的事件,把獲取授權接口寫到該事件里面去

<button class="sys_btn" open-type="getUserInfo" lang="zh_CN" @getuserinfo="appLoginWx">小程序登錄授權</button>

方法如下:

 appLoginWx(){ // #ifdef MP-WEIXIN
 uni.getProvider({ service: 'oauth', success: function (res) { if (~res.provider.indexOf('weixin')) { uni.login({ provider: 'weixin', success: (res2) => {  uni.getUserInfo({ provider: 'weixin', success: (info) => {//這里請求接口
 console.log(res2); console.log(info); }, fail: () => { uni.showToast({title:"微信登錄授權失敗",icon:"none"}); } }) }, fail: () => { uni.showToast({title:"微信登錄授權失敗",icon:"none"}); } }) }else{ uni.showToast({ title: '請先安裝微信或升級版本', icon:"none" }); } } }); //#endif
            }

 

在 uni.login 和 uni.getUserInfo 被調用后,你可以獲取到以下值用於繼續請求后端給你的接口:

常用的值大概有:code 、iv 、encryptedData 和 個人基本信息,這些可以傳給后端交換得到openid。

 

 

如果需要知道用戶當前是否已經授權,則可以使用如下代碼:

uniapp的授權文檔,可以判斷不同的授權類型:https://uniapp.dcloud.io/api/other/authorize?id=authorize

            // #ifdef MP-WEIXIN
 uni.getSetting({ success(res) { console.log("授權:",res); if (!res.authSetting['scope.userInfo']) { //這里調用授權
                    console.log("當前未授權"); } else { //用戶已經授權過了
                    console.log("當前已授權"); } } }) //#endif

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM