微信小程序获取用户信息并存入数据库

15 篇文章 0 订阅
9 篇文章 0 订阅

微信小程序获取用户信息,如果仅是需要用户头像和用户微信昵称,那就直接下面这两行代码无需授权直接获取

<!-- 如果只是展示用户头像昵称,可以使用 <open-data /> 组件 -->
<open-data type="userAvatarUrl"></open-data>
<open-data type="userNickName"></open-data>

好的,但是想要获取到更多,就需要调用wx.getUserInfo这个接口了,它会返回当前登陆的用户的详细信息,还是不错的
但是由于wx.getUserInfo接口的改版,不会再主动出现授权弹窗,需要用户去主动点击button来实现,所以我们就换个思路。
一般像这样的数据我们肯定需要用到多次,所以我们就把数据通过wx.setStorage放到本地的缓存中,然后当使用时候再wx.getStorage拿出来。
敲黑板!!!!!!!!!
我们在首页onShow方法里面先获取缓存wxuserinfo的信息,这个时候因为还没有存入,所以会获取失败,那么好,我们自己做一个引导页,同时在跳转到引导页的同时带上wx.login返回的code(解密时候会用到),引导用户进入授权页面,当用户点击确定授权时我们会获得如下这样的三个值,code是刚才通过wx.login传递过来的,然后将这三个值传递到后台进行解析,官方解析实例,解析成功之后,就会得到用户的信息,然后返回给小程序,这时候再用wx.setStorage将数据存储进去,OK,具体代码下面展示。
在这里插入图片描述

index.js
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.login({
      success: function (res) {
        var code=res.code;
        if (code) {
          wx.getStorage({
            key: 'wxUserInfo',
            success: function (res) {
                console.log(res);
            },
            fail: function (res) {
              wx.showModal({
                title: '微信小账本',
                content: '尚未进行授权,请点击确定跳转到授权页面进行授权。',
                showCancel: false,
                success: function (msg) {
                  if (msg.confirm) {
                    wx.redirectTo({
                      url: '../auth/auth?code=' + code,
                    })
                  }
                }
              })
            }
          });
        } else {
          console.log('登录失败!' + res.errMsg)
        }
      },
    });
  },
  引导页面
  <view class='container'>
  <view class='logo'>
   <image src='./logo.png'></image>
    <view id="font">将获取您的公开头像与昵称</view>
  </view>
  <button id="{{code}}" open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo" hover-class='none'>同意授权</button>
</view>
引导页面css
.logo{
  font-size: 24rpx;
  color: #333;
  text-align: center;
  margin-top: 120rpx;
  margin-bottom: 78rpx;
}
.logo image{
  width: 133rpx;
  height: 133rpx;
  margin-bottom: 6rpx;
}
button{
  height: 120rpx;
  background: #edc94f;
  font-size: 30rpx;
  color: #333;
  line-height: 120rpx;
  text-align: center;
  width: 96%;
}
引导页面JS
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this;
    that.setData({
      code: options.code
    });
  },
  bindGetUserInfo:function(event){
    var code = event.currentTarget.id;
    wx.request({
      url: 'https://***********/isregister',
      method :'post',
      data: {
        encryptedData: event.detail.encryptedData,
        iv: event.detail.iv,
        code: code,
      },
      success:function(data){
        console.log(data);
        wx.setStorage({
          key: 'wxUserInfo',
          data: data.data,
          success: function (re) {
            if (re.errMsg =='setStorage:ok'){
              wx.reLaunch({
                url: '../app/index',
              })
            }
          },
          fail: function () {
            console.log('保存wxUserInfo 失败')
          }
        })
      }
    })
  }
  OK小程序代码基本上好了,接下来看看服务端(PHP)代码
  public function isregister(Request $request){
        $msg='ok';
        $request=$request->all();
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$this->appid.'&secret='.$this->appsecret.'&js_code='.$request['code'].'&grant_type=authorization_code';
        $getOpenid = $this->my_curl_wx_api($url,'GET');
        //将数据解密
        $Crypt=new WXBizDataCrypt($this->appid,$getOpenid['session_key']);
        $errCode = $Crypt->decryptData($request['encryptedData'],$request['iv'],$data);
        if($errCode==0){
            $data = json_decode($data, true);
            $register=$this->user->where("username",$data['nickName'])->first();
            if(empty($register)){
                $userInfo=[
                    "openid"=>$data['openId'],
                    "username"=>$data['nickName'],
                    "image_url"=>$data['avatarUrl']
                ];
                $this->storeRecord($userInfo,$this->user);
            }else{
                $msg="用户已经存在";
            }
        }
        return ['info'=>$data,'msg'=>$msg];
    }
    上面就是获取用户信息的代码,如有不对,欢迎留言。
  • 7
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值