1. 安装 gregwar/captcha
图片验证码接口的流程是:
生成图片验证码
生成随机的 key,将验证码文本存入缓存。
返回随机的 key,以及验证码图片
# 不限于 laravel 普通 php 项目也可以使用额
$ composer require gregwar/captcha
2. 开发接口
1). 新建路由
routes/web.php
oute::prefix('auth')->group(function (){Route::post('captchas', [CaptchasController::class, 'store']);
});
2). 新建控制器和表单验证类
创建 CaptchasController 以及 CaptchaRequest
$ php artisan make:controller CaptchasController
$ php artisan make:request Api/CaptchaRequest
修改文件如下
app/Http/Requests/Api/CaptchaRequest.php
<?phpnamespace App\Http\Requests\Api;use Illuminate\Foundation\Http\FormRequest;class CaptchaRequest extends FormRequest
{/*** Determine if the user is authorized to make this request.** @return bool*/public function authorize(){return true;}/*** Get the validation rules that apply to the request.** @return array*/public function rules(){return [// 'phone' => 'required|regex:/^1[34578]\d{9}$/|unique:users',];}
}
app/Http/Controllers/CaptchasController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Gregwar\Captcha\CaptchaBuilder;
use App\Http\Requests\Api\CaptchaRequest;
class CaptchasController extends Controller
{public function store(CaptchaRequest $request, CaptchaBuilder $captchaBuilder){ // $key = 'captcha-'.str_random(15);$key = 'captcha-'.time();$phone = $request->phone;$captcha = $captchaBuilder->build();$expiredAt = now()->addMinutes(2);\Cache::put($key, ['phone' => $phone, 'code' => $captcha->getPhrase()], $expiredAt);$result = ['captcha_key' => $key,'expired_at' => $expiredAt->toDateTimeString(),'captcha_image_content' => $captcha->inline()];return $result;return $this->response->$result->setStatusCode(201);}
}
代码分析
use Gregwar\Captcha\CaptchaBuilder;
创建验证码实例: $captcha = $captchaBuilder->build();
获取验证码值: $captcha->getPhrase(); // abcd…
获取验证码图片的 base64: $captcha->inline() // base64 xxxxx
3). 代码分解
分析一下代码:
增加了 CaptchaRequest 要求用户必须通过手机号调用图片验证码接口。
controller 中,注入CaptchaBuilder,通过它的 build 方法,创建出来验证码图片
使用 getPhrase 方法获取验证码文本,跟手机号一同存入缓存。
返回 captcha_key,过期时间以及 inline 方法获取的 base64 图片验证码
这里给图片验证码设置为 2 分钟过期,