首先第一步(html部分):
<template>
<view class="authorizing-page">
<view class="msg-box">
<p class="title">申請(qǐng)獲得以下權(quán)限</p>
<p class="info">獲得你的公開(kāi)信息(昵稱(chēng)、頭像等)</p>
</view>
<button v-if="canIUse" class="btn" open-type="getUserInfo" @click="bindGetUserInfo">授權(quán)登錄</button>
<view v-else class="txt">請(qǐng)升級(jí)微信版本</view>
</view>
</template>
第二步:
data() {
return {
canIUse: wx.canIUse('button.open-type.getUserInfo'),
codeErrorNum: 0,
code: '',
}
},
onLoad() {
uni.login({
success: (res) => {
this.code = res.code
}
})
},
// 取出code,iv,encryptedData
bindGetUserInfo() {
uni.getUserProfile({
desc: '用于完善資料', // 聲明獲取用戶(hù)個(gè)人信息后的用途,后續(xù)會(huì)展示在彈窗中,請(qǐng)謹(jǐn)慎填寫(xiě)
success: (res1) => {
// console.log(res,123)
if (!res1.encryptedData || !res1.iv) return false;
this.getOpenIdAndSessionKey({
appid: 'wxa3ab0b1d7acd86fd',
code: this.code,
callback: (res2) => {
if (res2.data) this.transmitData(
res2.data.openid,
res1.iv,
res1.encryptedData,
res2.data.session_key,
'wxa3ab0b1d7acd86fd',
)
}
})
},
fail:(res)=>{
uni.showToast({
icon:"none",
title:'用戶(hù)拒絕獲取'
})
}
})
}
,
// 傳遞code,iv,encryptedData
transmitData(openid, iv, encryptedData, sessionKey, appid) {
this.login({
openid,
iv,
encryptedData,
sessionKey,
appid,
callback: res => {
console.log(res, '哈哈哈哈')
// code不可用,重新獲取code
if (!res.success) {
if (this.codeErrorNum < 3) {
// 重新獲取code
uni.login({
success: res => {
this.transmitData(res.code, e.target.iv, e.target.encryptedData)
}
})
// code無(wú)效次數(shù)加一
this.codeErrorNum++
} else {
this.$tools.showModal(res.message, false)
}
return
}
this.$tools['metadata'] = Object.assign(this.$tools['metadata'], res.data.metadata)
// this.initSocket(res.data.id)
uni.navigateBack({delta: 1})
}
})
}
,