yuanlj-tea / click-captcha

点击验证码

1.0.4 2020-08-14 13:57 UTC

This package is auto-updated.

Last update: 2024-09-29 05:22:31 UTC


README

安装

使用Composer

composer require yuanlj-tea/click-captcha

用法

您可以使用输出函数创建验证码

$captcha = new \ClickCaptcha\Captcha();
$captcha->output();

或者直接在HTML页面中内联

$inline = $captcha->getInline();
echo "<img src='".$linlie."' />";

您将能够获取代码并与用户输入进行比较

$captcha->getCode();

用于Laravel

在config/app.php中注册ServiceProvider和Facade

'providers' => [
    // ...
    \ClickCaptcha\ClickCaptchaServiceProvider::class,
],
'aliases' => [
    // ...
    'ClickCaptcha' => \ClickCaptcha\ClickCaptchaFacade::class,
],

获取服务实例

方法参数注入

use ClickCaptcha\Captcha;

public function getImage(Request $request, Captcha $captcha)
{
  
}

通过外观类获得

use ClickCaptcha;

public function getImageV1()
{
     
}

通过服务名称

public function getImageV2()
{
     $captcha = app('click_captcha');
}

查看演示

/**
 * 获取验证码信息
 */
public function getCaptcha()
{
    $key = 'click:captcha:' . str_random(32);

    $captcha = new Captcha();
    $cacheMinutes = 30;

    $inline = $captcha->getInline();
    $data['captcha_key'] = $key;
    $data['expired_at'] = time() + $cacheMinutes * 60;

    $code = $captcha->getCode();

    $data['code'] = $code;
    Cache::put($key, $code, $cacheMinutes);
    $data['image'] = $inline;

    return AjaxResponse::success($data);
}

/**
 * 校验验证码
 * @param Request $request
 */
public function check(Request $request)
{
    $captcha_key = $request->input('captcha_key', '');
    $param = $request->input('data', []);

    if (!Cache::has($captcha_key)) {
        return AjaxResponse::fail('验证码已过期,请刷新后再试');
    }
    if (!is_array($param)) {
        return AjaxResponse::fail('验证失败,参数错误');
    }

    $code = Cache::get($captcha_key);
    $checkCode = array_column($code, 'scope');

    $errKey = $captcha_key . '_error';
    if (Cache::get($errKey) >= 3) {
        Cache::forget($captcha_key);
        Cache::forget($errKey);
        return AjaxResponse::fail('错误次数过多,请刷新验证码后再试');
    }
    foreach ($checkCode as $k => $v) {
        if (!isset($param[$k])) {
          	Cache::increment($errKey);
          	return AjaxResponse::fail('验证失败');
        }

        if (!isset($param[$k]['x']) || !isset($param[$k]['y'])) {
            Cache::increment($errKey);
            return AjaxResponse::fail('验证失败');
        }

        $x = $param[$k]['x'];
        $y = $param[$k]['y'];

        if (
          !(
            $x >= $v['x_limit_left'] && $x <= $v['x_limit_right'] &&
            $y >= $v['y_limit_up'] && $y <= $v['y_limit_down']
          )
        ) {
          Cache::increment($errKey);
          return AjaxResponse::fail('验证失败');
        }
    }
    Cache::forget($errKey);
    return AjaxResponse::success('验证成功');
}

许可证

MIT