thinkPHP6验证码接口

接口文档要求

 定义方法

    public function index(){
//        验证码标识
        $id=mt_rand(100000, 999999);
        $uniqid = uniqid("$id");
        //返回数据 验证码图片路径、验证码标识
        $data = [
            'src' =>"http://www.pyg.com" . captcha_src($uniqid),
            'uniqid' => $uniqid
        ];
        return json($data);
    }

多模块应用需要在路由里添加

Route::get('captcha/:id','\\think\\captcha\\CaptchaController@index')

 跨域请求需要在路由结尾加一个

->allowCrossDomain

 

考虑到前后端分离   验证码以cache缓存

需要在 pyg/vendor/topthink/think-captcha/src/Captcha.php中设置(找到创建验证码(generate)的方法    可以直接复制过去替换掉)

    /**
     * 创建验证码
     * @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]);

        cache('captcha', [
            'key' => $hash,
        ]);

        return [
            'value' => $bag,
            'key'   => $hash,
        ];
    }

然后找到  验证码是否正确(check)方法将里面session 改成cache (可以直接复制粘贴过去替换掉)

 /**
     * 验证验证码是否正确
     * @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;
    }

posted @ 2022-11-24 14:18  哎呀呀哈  阅读(28)  评论(0)    收藏  举报  来源