TP6.0框架-----通过接口返回前端验证码

验证码功能组件下载:

composer require topthink/think-captcha

配置路由:(因为是后端返回前端验证码,会涉及到跨域问题,所以需要加上最后一个指向)

Route::get('getCaptcha','Login/getCaptcha')->allowCrossDomain();
//如果需要更改验证码相关配置,则需要加下面的路由
Route::get('captcha/:id', "\\think\\captcha\\CaptchaController@index");

(目前还不清楚为什么要加第二行的路由,如果有知道的小伙伴,希望能够留言评论,谢谢!)

如果需要更改验证码相关配置,修改文件:app/config/captcha.php

控制器:(域名自行更改)

public function getCaptcha()
    {
        //验证码标识
        $uniqid = uniqid((string)mt_rand(10000, 99999));
        //返回数据 验证码图片路径、验证码标识
        $data = [
            'src' => "http://adminapi.pyg.com" . captcha_src($uniqid),
            'uniqid' => $uniqid
        ];
        return success(200,'ok',$data);
    }

接口测试:Postman(接口自行修改)

http://adminapi.pyg.com/captcha

可修改组件源代码如下:
vendor/topthink/think-captcha/src/Captcha.php

/**
 * 创建验证码
 * @return array
 * @throws Exception
 */
protected function generate(): array
{
    $bag = '';

    if ($this->math) {
        $this->useZh  = false;
        $this->length = 5;

        $x   = random_int(10, 30);
        $y   = random_int(1, 9);
        $bag = "{$x} + {$y} = ";
        $key = $x + $y;
        $key .= '';
    } else {
        if ($this->useZh) {
            $characters = preg_split('/(?<!^)(?!$)/u', $this->zhSet);
        } else {
            $characters = str_split($this->codeSet);
        }

        for ($i = 0; $i < $this->length; $i++) {
            $bag .= $characters[rand(0, count($characters) - 1)];
        }

        $key = mb_strtolower($bag, 'UTF-8');
    }

    $hash = password_hash($key, PASSWORD_BCRYPT, ['cost' => 10]);

    $this->session->set('captcha', [
        'key' => $hash,
    ]);
    //因为是前后端分离,后端存储session,前端获取不到,所以需要缓存来存取验证码信息
    cache('captcha', [
        'key' => $hash,
    ]); //加上这行代码,便于后续校验验证码
    return [
        'value' => $bag,
        'key'   => $hash,
    ];
}

/**
 * 验证验证码是否正确
 * @access public
 * @param string $code 用户验证码
 * @return bool 用户验证码是否正确
 */
public function check(string $code): bool
{
    if (!cache('captcha')) {
        return false;
    }

    $key = cache('captcha')['key'];

    $code = mb_strtolower($code, 'UTF-8');

    $res = password_verify($code, $key);

    if ($res) {
        cache('captcha');
    }

    return $res;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值