1. 程式人生 > >微信小程式刷臉登入

微信小程式刷臉登入

微信小程式本身並不具有刷臉登入的功能,實現時需要藉助百度雲的人臉識別的sdk,當然現在百度雲是暫時免費的,我們可以登入自行下載使用。

下載地址:https://cloud.baidu.com

後臺程式碼我們使用thinkPHP框架實現,將下載好的sdk匯入thinkPHP框架中,就可以寫方法使用了

我們需要將圖片上傳到自己伺服器和百度雲人臉庫中

public function login(){
        $dir="./***";//自己定義的檔名
        if(!file_exists($dir)){
            mkdir($dir,0777,true);
        }
        $upload = new \Think\Upload();// 例項化上傳類
        $upload->maxSize = 3145728 ;// 設定附件上傳大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 設定附件上傳型別
        $upload->rootPath = $dir; // 設定附件上傳根目錄
        $upload->savepath='';
        // 上傳單個檔案
        $info = $upload->uploadOne($_FILES['file']);
        if(!$info) {// 上傳錯誤提示錯誤資訊
            return $this->ajaxReturn(array('error'=>true,'msg'=>$upload->getError()));
        }else{// 上傳成功 獲取上傳檔案資訊
            $file = $dir . $info['savepath'] . $info['savename'];
            $image = base64_encode(file_get_contents($file));
            $client = $this->init_face();
            $options['liveness_control']='NORMAL';
            $options['max_user_num']='1';
            $ret = $client->search($image,'BASE64',$this->face_group(),$options);

            if($ret['error_code']==0){
                $user = $ret['result']['user_list'][0];
                $no = $user['user_id'];
                $score = $user['score'];

                if(!empty($no)){
                    $data = M('student')->field('no,name,sex')->where("no='{$no}'")->find();

                    if($data){
                        //查到此學號
                        $data['score'] = $score;
                        echo json_encode($data,JSON_UNESCAPED_UNICODE);
                    }else{
                        //本地庫不存在此學號
                        echo "本地資料庫沒有該學生,百度雲庫資訊:個人資訊:{$no},分值:{$score}";
                    }

                }

            }else{
                echo "活體檢測失敗,".json_encode($ret,JSON_UNESCAPED_UNICODE);
            }
        }
    }

裡面的search方法是sdk的方法

 public function search($image, $imageType, $groupIdList, $options=array()){

        $data = array();
        
        $data['image'] = $image;
        $data['image_type'] = $imageType;
        $data['group_id_list'] = $groupIdList;

        $data = array_merge($data, $options);
        return $this->request($this->searchUrl, json_encode($data),  array(
            'Content-Type' => 'application/json',
        ));
    }

前三個引數是必填的,後面引數根據自己的實際情況選即可。

微信小程式中需要使用camera元件以及wx.createCameraContext()方法,之後在js呼叫後臺程式碼即可。

在dedeCms標籤裡面,arclist標籤不允許內部巢狀,所以一下程式碼在載入圖片時會出現:載入URL錯誤,經過查閱資料,我們可以把圖片當成一個arclist的一個欄位寫出來,就可以了。
可以將:{dede:global.cfg_templets_skin/}/default/images =>[field:global.cfg_templeturl/]/default/images,這樣圖片就可以正常顯示了。在dedeCms標籤裡面,arclist標籤不允許內部巢狀,所以一下程式碼在載入圖片時會出現:載入URL錯誤,經過查閱資料,我們可以把圖片當成一個arclist的一個欄位寫出來,就可以了。