微信小程序授權登錄適配wx.getUserProfile最新代碼
序言:2021年4月28日起,微信小程序不再支持用戶授權調用wx.getUserInfo,統(tǒng)一改為wx.getUserInfo進行用戶信息獲取,基于這種調整很多開發(fā)者還沒來得及更新代碼,我根據(jù)實際項目整理了一份代碼,讓我們一塊學習一下吧。

案例欣賞



代碼展示
1、點擊登錄按鈕的代碼,這一步是通過openid創(chuàng)建一個賬號,如果這個賬號已經(jīng)存在,則直接登錄,如果不存在然后彈框,再進行下一步的用戶信息更新
wxml
<view bindtap="wxlogin" class='picTxt acea-row row-between-wrapper'>  <view class='pictrue' ><image src='../../images/avatar.png'></image></view>    <view class='text'>      <view class='acea-row row-middle'>        <view class='name line1' >點擊登錄</view>		</view>	</view></view>
js
//彈出登錄框  wxlogin:function(){    var that = this;    wx.showLoading({ title: '正在登錄中' ,'mask' : true });    wx.login({      success:function(res){        wx.request({          url: HTTP_REQUEST_URL '/api/common/login',          data: {            code: res.code,          },          dataType: 'json',          method: 'POST',          header: {            'Accept': 'application/json'          },          success: function (res2) {            wx.hideLoading();            if(res2['data']['status']==200){              that.setData({                is_update_profile:res2['data']['data']['user_info']['is_update_profile'],                hiddenLogin:false,                token:res2['data']['data']['token'],              })            }else{              wx.showToast({                title: res2['data']['msg'],                icon : 'none'              })            }          },          fail(res2){            wx.hideLoading();          }        })      },      fail(){        wx.hideLoading();      }    })  },
php
$code=input("post.code");$s_data=[];$s_data['appid'] = $wechat["appId"];$s_data['secret'] = $wechat["appsecret"];$s_data['js_code'] = $code;$s_data['grant_type']="authorization_code";$session_url = 'https://api.weixin.qq.com/sns/jscode2session?' . http_build_query ( $s_data );$content = file_get_contents($session_url);$content = json_decode ( $content, true );if(!isset($content['openid']) || !isset($content['session_key'])){  return_json("授權失敗",100);}
2、如果第一步的openid不存在,則通過getUserProfile獲取相應的信息,然后傳遞到后臺進行保存。
wxml
<view class="auth-content">        <image class="bg" mode="widthFix" src="../../images/auth-bg.png"></image>        <view class="btn" wx:if="{{canIUse}}">            <view bindtap="close_login" class="close-btn" >暫不登錄</view>            <button class="i-btn" loading="{{btnLoading}}" bindtap="getUserProfile" >立即登錄</button>        </view>        <view class="updateWx" wx:else>請升級微信版本</view>    </view>
js
//授權登錄  getUserProfile(userInfo,isLogin) {    let that = this;    var token = that.data.token;    var is_update_profile = that.data.is_update_profile;    if(is_update_profile-0>0){      wx.request({        url: HTTP_REQUEST_URL '/api/user',        data: {        },        dataType: 'json',        method: 'get',        header: {          'Accept': 'application/json',          'Authori-zation' : 'Bearer '   token,        },        success: function (res2) {          wx.setStorageSync('TOKEN', that.data.token);          that.setData({hiddenLogin:true,userInfo: res2.data.data});        },        fail(res2){        }      })    }else{      wx.getUserProfile({        lang: 'zh_CN',        desc:'用于完善會員資料',        success:function(res){          if (res.errMsg == "getUserProfile:ok"){            that.setData({              hiddenLogin:true            })            var UserInfo = JSON.parse(res.rawData);                        wx.request({              url: HTTP_REQUEST_URL '/api/user/update_profile',              data: {                invite_id: app.globalData.spid,                avatar: UserInfo.avatarUrl,                sex: UserInfo.gender,                nickname: UserInfo.nickName,                city: UserInfo.city,                province: UserInfo.province,                country: UserInfo.country,              },              dataType: 'json',              method: 'POST',              header: {                'Accept': 'application/json',                'Authori-zation' : 'Bearer '   token,              },              success: function (res2) {                wx.hideLoading();                wx.setStorageSync('TOKEN', token);                that.setData({hiddenLogin:true,userInfo: res2.data.data.user_info});              },              fail(res2){                //wx.hideLoading();              }            })          }else{          }        }      })    }  },
php
$updateData = array(    			"avatar"=>input("post.avatar"),    			"sex"=>input("post.sex"),    			"nickname"=>input("post.nickname"),    			"city"=>input("post.city"),    			"province"=>input("post.province"),    			"country"=>input("post.country"),    			"invite_id"=>$invite_id,    			"invite_center"=>$invite_center,    			"invite_bottom"=>$invite_bottom,    			"invite_str"=>$invite_str,    			"is_update_profile"=>1,	    	);Db::name("user")->where(["uid"=>$user_id])->update($updateData);
總結
登錄的流程一共分為兩步,第一步是獲取小程序用戶的唯一openid作為標識,第二步是將小程序用戶的基本信息更新到已創(chuàng)建的用戶那里,這樣整個登錄流程是做好了。
我是小程序軟件開發(fā),每天分享開發(fā)過程中遇到的知識點,如果對你有幫助的話,幫忙點個贊再走唄,非常感謝。
往期文章分享:
