本文實例講述了微信小程序學習筆記之登錄API與獲取用戶信息操作。分享給大家供大家參考,具體如下:
前面介紹了微信小程序跳轉頁面、傳遞參數獲得數據,這里來分析一下登錄API與獲取用戶信息操作方法。
【小程序登錄】wx.login()
app.js:
App({ onLaunch: function () { // 登錄 wx.login({ success: function (res) { if (res.code) { //發起網絡請求 wx.request({ url: 'https://www.msllws.top/delcode.php', data: { code: res.code } }) } else { console.log('登錄失敗!' + res.errMsg) } } }); }})初始化后得到了臨時登錄憑證code,使用wx.request()發送code,請求后臺接口獲取【會話密鑰session_key】和【用戶唯一標識openid】,滿足UnionID下發條件時還可以獲得【用戶在開放平臺的唯一標識符unionid】。
后臺接收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); //(省略業務邏輯:保存返回結果中的openid與用戶userid關聯......) echo $res;
請求返回結果:

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


此時修改login.js如下,使用wx.getSetting()獲得用戶信息
(調用wx.getUserInfo()之前需要調用wx.getSetting()獲取用戶當前的授權狀態,返回結果中如果包含【scope.userInfo】,說明用戶已對用戶信息進行授權,可以直接調用wx.getUserInfo()獲取用戶信息)
新聞熱點
疑難解答