微信小程序静默登录验证token

 1.小程序封装we.request()方法

// 定义连接通用地址 (域名)
const pubUrl = "http://www.day.com/index.php/api/"
// 定义请求
const http = (url,method,data,header) =>{
    return new Promise((resolve,reject) => {
        wx.request({
            url:pubUrl+url,
            method:method || 'get',
            data:data || {},
            header: header || {},
             success(request) {
                if (request.statusCode == 200) {
                resolve(request.data)
                } else {
                reject(request.data.msg)
                }
                }
        })
    }
    )}

    // 导出
    export default http

2.调用方法 

onLaunch() {
    // 判断缓存中是否有token
      var token = wx.getStorageSync('token')
      if (token) {
        // 判断是否有userid
        if(wx.getStorageSync('userid')==''){
          // 发送登录请求 
          wx.login({
           timeout:2000,
           success:({code})=>{
             //  发送请求 登录添加用户
             let header = {
               'Authorization':"Bearer"+" "+token}
           var promise = new Promise(function(resolve){
             resolve(http("wxlogin",'POST',{code},header));
           });
          // 取出请求里的值  将用户id缓存
           promise.then(function(value){
            wx.setStorageSync('userid', value.data)
           });
           }
         })
      } 
      }else{
        // 发送请求 获取token
        var promise = new Promise(function(resolve){
          let data = [{username:'user',password:'123456'}];
          resolve(http("auth/login",'POST',data));
        });
         promise.then(function(value){
            let token = value.data.token;
            wx.setStorageSync('token', token)
        });
      }
  },

 3.php后端验证token

 public function login(Request $request)
    {
//        验证找账号密码是否正确
        $bool=auth()->guard('apiweb')->attempt($postData);
        if($bool){
//            生成token
        $userModel = auth()->guard('apiweb')->user();
        $token = $userModel->createToken('api')->accessToken;

        $data=[
            'expire'=>7200,
            'token'=>$token
        ];
            return response(['code'=>200,'msg'=>"颁发token成功",'data'=>$data]);
        }else{
            return response(['code'=>200,'msg'=>"账号或密码错误",'data'=>"11"]);
        }
    }

4.实现用户添加

 public function wxlogin(Request $request)
    {
        $code=$request->post("code");
        $appId=config("wx.appId");
        $appSecret=config("wx.AppSecret");
        $url="https://api.weixin.qq.com/sns/jscode2session?appid={$appId}&secret={$appSecret}&js_code={$code}&grant_type=authorization_code";
        $headerArray =array("Content-type:application/json;","Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output,true);
//        判断openid是否在该表里存在
        $openId=$output['openid'];
        $res=Renting::selectData($openId);
        if(count($res)==0){
//            添加入库
            $data=['openid'=>$openId,'nickname'=>"微信用户".rand(1111,9999),'avatar'=>"http://img.yypzyq.com/2022-03-09/tx.jpg"];
            $addData=Renting::addData($data);
            if(!$addData){
                return response(['code'=>400,'msg'=>"登录失败",'data'=>""]);
            }
        }
        $findId=Renting::selectData($openId);
        $id=$findId[0]['id'];
        return response(['code'=>200,'msg'=>"登录成功",'data'=>$id]);
    }

你可能感兴趣的:(微信小程序,javascript,小程序登录)