Lumen 實現接口 Captcha圖片驗證碼功能


安裝

composer require youngyezi/captcha

使用

新版的包已經刪除了 session 支持,完全交給業務自由選擇存儲方式

個人覺得這樣更方便來解耦業務,尤其 Lumen 大多時候用來做 Api 開發,並不需要開啟 Session 服務

注冊服務 bootstrap\app.php

$app->register(Youngyezi\Captcha\CaptchaServiceProvider::class);


// 添加別名
$app->alias('captcha', 'Youngyezi\Captcha\CaptchaServiceProvider');

配置文件

復制 vendor\Youngyezi\Captcha\config\captcha.php 文件至 項目 config 文件下

For Example

驗證碼生成

//  創建驗證碼
//  配置文件 key($config)
//  返回值包括一base_64加密的圖片和一key
$data = app('captcha')->create();
    
//  自定義儲存 key (如 redis ,session 等)

....

//  返回驗證碼圖片 img

生成的base64可以用這個站點轉換 站點鏈接

 驗證碼校驗

// 通過 code 和 key 來校驗
$captcha = $request->input('captcha');

// 獲取自定義存儲的 key 值
$key = { ... };
    
if(app('captcha')->check($captcha, $key) === false) {
       //校驗失敗
}
  /*
     * 用戶注冊
     */
    public function register()
    {
        $input = Input::get();
        if(!isset($input['username']) || empty($input['username']) ||
            !isset($input['iponenumber']) || empty($input['iponenumber']) ||
            !isset($input['password']) || empty($input['password']) ||
            !isset($input['key']) || empty($input['key']) ||
            !isset($input['captcha']) || empty($input['captcha'])
        ){
            return response()->json(['code'=>3,'msg'=>'參數缺失']);
        }

        if(!$this->check($input['key'],$input['captcha'])){
            return response()->json(['code'=>20000,'msg'=>'輸入驗證碼錯誤']);
        }

        if(DB::table('user')->where('iponenumber',$input['iponenumber'])->first()){
            return response()->json(['code'=>20001,'msg'=>'手機號已注冊']);
        }

        $insert = DB::table('user')->insert(['username'=>htmlspecialchars($input['username']),'iponenumber'=>$input['iponenumber'],'password'=>Hash::make($input['password'])]);
        if($insert){
            return response()->json(['code'=>0,'msg'=>'注冊成功']);
        }else{
            return response()->json(['code'=>20002,'msg'=>'注冊失敗']);
        }
    }

    /*
     * 圖片驗證碼
     * 返回值包括一個base_64加密的圖片和一個key
     */
    public function captchaInfo()
    {
        $result = app('captcha')->create();
        Cache::put($result['key'],$result['key'],60);
        if(isset($result['sensitive'])){
            unset($result['sensitive']);
        }
        return response()->json(['code'=>0,'msg'=>'成功','data'=>$result]);
    }

    /**
     * @params key,captcha
     * 兩個參數key和驗證碼
     */
    private function check($key,$captcha)
    {
        return app('captcha')->check(strtolower($captcha),Cache::get($key));
    }
自己封裝使用的demo

https://github.com/Youngyezi/captcha


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM