本文實(shí)例講述了微信小程序?qū)W習(xí)筆記之登錄API與獲取用戶信息操作。分享給大家供大家參考,具體如下:
前面介紹了微信小程序跳轉(zhuǎn)頁面、傳遞參數(shù)獲得數(shù)據(jù),這里來分析一下登錄API與獲取用戶信息操作方法。
【小程序登錄】wx.login()
app.js:
App({ onLaunch: function () {  // 登錄  wx.login({   success: function (res) {    if (res.code) {     //發(fā)起網(wǎng)絡(luò)請(qǐng)求     wx.request({      url: 'https://www.msllws.top/delcode.php',      data: {       code: res.code      }     })    } else {     console.log('登錄失?。? + res.errMsg)    }   }  }); }})初始化后得到了臨時(shí)登錄憑證code,使用wx.request()發(fā)送code,請(qǐng)求后臺(tái)接口獲取【會(huì)話密鑰session_key】和【用戶唯一標(biāo)識(shí)openid】,滿足UnionID下發(fā)條件時(shí)還可以獲得【用戶在開放平臺(tái)的唯一標(biāo)識(shí)符unionid】。
后臺(tái)接收code的接口delcode.php:
<?php $code = $_GET['code']; $appid = 'wx1aebd07bdcf596b8'; $secret = '9ee8211007b81efd8c11d7d82d3b8658'; $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code'; $res = file_get_contents($url); //(省略業(yè)務(wù)邏輯:保存返回結(jié)果中的openid與用戶userid關(guān)聯(lián)......) echo $res;
請(qǐng)求返回結(jié)果:

(unionid需要小程序綁定已認(rèn)證的微信開放平臺(tái)才可以獲得)
【獲取用戶信息】wx.getUserInfo()
首先借助button來授權(quán)登錄,login.wxml:
<open-data type="userAvatarUrl"></open-data><open-data type="userNickName"></open-data><button wx:if="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">授權(quán)登錄</button><view wx:else>請(qǐng)升級(jí)微信版本</view>login.js如下:
Page({ data: {  //判斷getUserInfo是否在當(dāng)前版本可用  canIUse: wx.canIUse('button.open-type.getUserInfo') }, bindGetUserInfo(e) {  console.log(e.detail.userInfo) }})首次點(diǎn)擊button按鈕提示微信授權(quán),允許后調(diào)用bindGetUserInfo函數(shù)打印獲得的用戶信息


此時(shí)修改login.js如下,使用wx.getSetting()獲得用戶信息 
(調(diào)用wx.getUserInfo()之前需要調(diào)用wx.getSetting()獲取用戶當(dāng)前的授權(quán)狀態(tài),返回結(jié)果中如果包含【scope.userInfo】,說明用戶已對(duì)用戶信息進(jìn)行授權(quán),可以直接調(diào)用wx.getUserInfo()獲取用戶信息)
Page({ data: {  //判斷getUserInfo是否在當(dāng)前版本可用  canIUse: wx.canIUse('button.open-type.getUserInfo') }, onLoad: function () {  // 查看是否授權(quán)  wx.getSetting({   success(res) {    if (res.authSetting['scope.userInfo']) {     // 已經(jīng)授權(quán),直接調(diào)用getUserInfo獲取用戶信息     wx.getUserInfo({      success: function (res) {       console.log(res.userInfo)      }     })    }   }  }) }, bindGetUserInfo(e) {  console.log(e.detail.userInfo) }})重新編譯,頁面加載獲得同上用戶信息:

此時(shí)再點(diǎn)擊button按鈕不再提示授權(quán)確認(rèn)信息。
希望本文所述對(duì)大家微信小程序開發(fā)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注