1.客戶端生成一個uuid請求服務端前端
2.服務端保存uuid到redis服務器,並設置過時時間,而後使用該uuid生成二維碼並返回ajax
3.客戶端展現二維碼,並設置ajax定時請求服務端判斷是否登陸redis
4.手機APP掃碼,獲取uuid,將uuid和自身用戶信息傳遞給服務端登陸接口json
5.服務端判斷uuid是否被使用以及過時,而後將uuid和用戶信息保存,將uuid做爲客戶端的token服務器
6.客戶端請求到成功登陸,並獲取到用戶信息app
/** * 生成登錄二維碼信息,存儲客戶端發過來的token * @url app/{controller}/qrCode * @method POST * @param string client_token * @return json */ public function qrCode($data = null){ if (is_string($data)) $data = json_decode($data, true); //參數驗證 $validate = Validate::make([ 'client_token' => 'require|min:1|max:100', ]); if (!$validate->check($data)) { $msg = $validate->getError(); return wx_errorReturn(null, -1, $msg); } //將客戶端發來的token存入redis $redis = Cache::store('redis')->handler(); $prefix = config('const.redis_prefix'); $key = $prefix['c_user_token'].$data['client_token']; $redis->Set($key,''); $redis->expire($key,120);//設置token,2分鐘過時 return wx_successReturn(['url'=>config('app.app_host').'/app/user/smlogin']);//二維碼也交給前端生成了 }
/** * 掃碼登錄,手機獲取到client_token,將client_token和用戶的token一塊兒傳過來 */ public function smLogin($data = null){ if (is_string($data)) $data = json_decode($data, true); //參數驗證 $validate = Validate::make([ 'client_token' => 'require|min:1|max:100', 'token' => 'require' ]); if (!$validate->check($data)) { $msg = $validate->getError(); return wx_errorReturn(null, -1, $msg); } //將客戶端token和用戶id信息存入redis $user = getAppUserInfo($data['token']); $redis = Cache::store('redis')->handler(); $prefix = config('const.redis_prefix'); $token_key = $prefix['c_user_token'].$data['client_token']; //同一個二維碼信息只能用一次 if($redis->get($token_key)) return wx_errorReturn(null,-1,'二維碼已失效'); $user_key = $prefix['c_user'].$user['id']; $redis->set($token_key,$user['id']); //token --> id $redis->hmset($user_key,$user); //id --> user $redis->expire($token_key,86400);//設置token,1天過時 $redis->expire($user_key,86400);//設置token,1天過時 return wx_successReturn(null,'登陸成功'); }
/** * 客戶端定時請求該接口判斷是否登陸 */ public function isLoginClient($data = null){ if (is_string($data)) $data = json_decode($data, true); //參數驗證 $validate = Validate::make([ 'client_token' => 'require|min:1|max:100', ]); if (!$validate->check($data)) { $msg = $validate->getError(); return wx_errorReturn(null, -1, $msg); } $redis = Cache::store('redis')->handler(); $prefix = config('const.redis_prefix'); $token_key = $prefix['c_user_token'].$data['client_token']; //判斷token_key是否過時 $exists = $redis->exists($token_key); if(!$exists) return wx_errorReturn(null,-1,'二維碼過時'); $user_id = $redis->get($token_key); $user_key = $prefix['c_user'].$user_id; $user = $redis->hGetAll($user_key); return wx_successReturn(['user_info' => $user],'登陸成功'); }