thinkphp 微信小程序登陆

 //校验openid
    public function getOpenid(){
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $appid = config('wxpay.appid');
        $secret = config('wxpay.secret');
        $js_code = input('code','');
        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        $data = array('appid' => $appid,'secret' => $secret,'js_code' => $js_code,'grant_type' => 'authorization_code',);
        $res = httpRequest($url, 'POST', $data);
        $arr = json_decode($res, true);
        if (isset($arr['errcode']) && !empty($arr['errcode'])) {
            $this->error($arr['errmsg']);
        }
        $this->success('获取成功',$arr);
    }

    public function wxLogin(){
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $openid = input('openid','');
        $avatar = input('avatar','');
        $nickname = input('nickname','');
        if(empty($openid) || empty($avatar) || empty($nickname)){
            $this->error('openid或用户信息为空','');
        }
        $user = db('user')->where('openid', $openid)->find();
        if ($user) {
            unset($user['openid']);
            unset($user['password']);
            $this->success('登录成功',$user);
        } else {
            $data_user = ['openid'=>$openid,'avatar'=>$avatar,'nickname'=>$nickname,'status'=>'normal','jointime'=>time()];
            $id = db('user')->insertGetId($data_user);
            if($id){
                $user = db('user')->where('openid', $openid)->find();
                unset($user['openid']);
                unset($user['password']);
                $this->success('登录成功',$user);
            }else{
                $this->error('登录失败','');
            }
        }
    }
 <button open-type="getUserInfo" bindgetuserinfo="register" class='login-btn'>授权登录</button>

/**
 * 注册
 */
register: function (e) {
  console.log(e.detail.userInfo)
  var that = app

  wx.login({
    success: res => {
      var that = this
      if (res.code) {
        var url = 'api/User/getOpenid'
        var params = { 
          code: res.code,
        }
        util.wxRequest(url,params,"POST",data => {
          wx.setStorageSync('openid',data.data.openid) 
         }, data => { }, data => { })
      } else {
        that.globalData.login = false
        console.log('获取用户code失败')
      }
    }
  }) 
   
  if (e.detail.userInfo !== undefined){
      var param = {
        "openid":wx.getStorageSync('openid'),
        "avatar":e.detail.userInfo.avatarUrl,
        "nickname":e.detail.userInfo.nickName,
      }

      util.wxRequest('api/User/wxLogin',param,"POST",data => {
       console.log(data)
       }, data => { }, data => { })
    }
  },
上一篇:调用服务号消息推送


下一篇:Redis限制一键登录次数