美文网首页
laravel下captcha在接口中的使用笔记!

laravel下captcha在接口中的使用笔记!

作者: DragonersLi | 来源:发表于2020-10-26 18:33 被阅读0次
    composer require mews/captcha 
    
    找到config/app.php下的providers,添加如下代码 
    \Mews\Captcha\CaptchaServiceProvider::class,
    
    找到config/app.php下的aliases,添加如下代码 
    'Captcha' => Mews\Captcha\Facades\Captcha::class,
    
    引入配置文件,选择相应的包,生成config/captcha.php
    php artisan vendor:publish
    
    
    如果一直返回验证失败,则需要在app/Http/Kernel.php中的$middleware加入以下信息 
    `\Illuminate\Session\Middleware\StartSession::class`
    
    #原生图片
    captcha();
    Captcha::create();
    
    #URL
    captcha_src();
    Captcha::src();
    
    #HTML
    captcha_img();
    Captcha::img();
    
    使用配置文件captcha.php中不同的配置项
    captcha('flat');
    
    
    #route
    Route::get('/captcha', 'AllController@code');
    Route::post('/captcha', 'AllController@valid');
    
        //获取验证码
        public function captcha(Request $request)
        {  
            return [ 
                'code'=>app('captcha')->create('default', true) //使用config下的captcha.php数组中的default
                ];
            
        }
       
    //验证验证码
        public function captchaValidate(Request $request)
        {  
              
                $this->validate($request, [ 'captcha' => 'required|captcha',]);  //通过validate方式验证captcha,不用写逻辑
                
                //通过自调用方法验证captcha,要写逻辑
                $capthca = $request->input('captcha');//接收传来的验证码
                $key = $request->input('key');//验证码key
        
                if (!captcha_api_check($capthca, $key)){//验证失败
                   dd('valid error');
                }else{//验证码正确
                    dd('valid ok');
                }
        }
    
    请求接口获取验证码,验证的时候传递keyimg中的字符,调用验证方法验证。
    image.png image.png

    相关文章

      网友评论

          本文标题:laravel下captcha在接口中的使用笔记!

          本文链接:https://www.haomeiwen.com/subject/qbvarxtx.html