您的位置 首页 java

微信小程序授权登录适配wx.getUserProfile最新代码

案例欣赏

代码展示

1、点击登录按钮的代码,这一步是通过 openid 创建一个账号,如果这个账号已经存在,则直接登录,如果不存在然后弹框,再进行下一步的用户信息更新

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 = '#39; . 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作为标识,第二步是将小程序用户的基本信息更新到已创建的用户那里,这样整个登录流程是做好了。

我是小程序 软件开发 ,每天分享开发过程中遇到的知识点,如果对你有帮助的话,帮忙点个赞再走呗,非常感谢。

往期文章分享:

文章来源:智云一二三科技

文章标题:微信小程序授权登录适配wx.getUserProfile最新代码

文章地址:https://www.zhihuclub.com/197150.shtml

关于作者: 智云科技

热门文章

网站地图