71 lines
1.9 KiB
PHP
71 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace App\Endpoint\Api\Http\Controllers;
|
|
|
|
use App\Endpoint\Api\Http\Requests\StoreCaptchaRequest;
|
|
use App\Services\CaptchaService;
|
|
use Gregwar\Captcha\CaptchaBuilder;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Str;
|
|
|
|
class CaptchaController extends Controller
|
|
{
|
|
/**
|
|
* 创建图形验证码
|
|
*
|
|
* @param \App\Endpoint\Api\Http\Requests\StoreCaptchaRequest $request
|
|
* @param \App\Services\CaptchaService $captchaService
|
|
* @return \Illuminate\Http\Response
|
|
*/
|
|
public function store(StoreCaptchaRequest $request, CaptchaService $captchaService)
|
|
{
|
|
$builder = $this->builder();
|
|
$builder->build($request->input('w', 150), $request->input('h', 40));
|
|
|
|
$captchaService->put(
|
|
$key = $request->input('key', Str::random(16)),
|
|
$builder->getPhrase()
|
|
);
|
|
|
|
return response()->json([
|
|
'key' => $key,
|
|
'img' => $builder->inline(),
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 查看图形验证码
|
|
*
|
|
* @param string $key
|
|
* @param \Illuminate\Http\Request $request
|
|
* @param \App\Services\CaptchaService $captchaService
|
|
* @return \Illuminate\Http\Response
|
|
*/
|
|
public function show($key, Request $request, CaptchaService $captchaService)
|
|
{
|
|
$builder = $this->builder();
|
|
$builder->build(
|
|
(int) $request->query('w', 150),
|
|
(int) $request->query('h', 40),
|
|
);
|
|
|
|
if (strlen($key) <= 32) {
|
|
$captchaService->put($key, $builder->getPhrase());
|
|
}
|
|
|
|
return response($builder->get())
|
|
->header('Content-Type', 'image/jpeg')
|
|
->header('Cache-Control', 'no-cache');
|
|
}
|
|
|
|
/**
|
|
* 图形验证码生成器
|
|
*
|
|
* @return \Gregwar\Captcha\CaptchaBuilder
|
|
*/
|
|
protected function builder(): CaptchaBuilder
|
|
{
|
|
return new CaptchaBuilder(Str::random(5));
|
|
}
|
|
}
|