uniapp小程序授權(quán)登錄

首先第一步(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})
          }
        })
      }
      ,
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容