config = $config; foreach ($config as $key => $val) { if (property_exists($this, $key)) { $this->{$key} = $val; } } } /** * 设置场景值 * @param string $scene * @return $this */ public function scene (string $scene) { $this->scene = $scene; return $this; } /** * 生成验证码 * @param int $mobile * @return string * @throws \Exception */ public function create (int $mobile) { switch ($this->type) { case 1: // 纯数字型验证码 $range = [0, 9]; break; case 2: // 纯小写字母型验证码 $range = [10, 35]; break; case 3: // 纯大写字母型验证码 $range = [36, 61]; break; case 4: // 数字与小写字母混合型验证码 $range = [0, 35]; break; case 5: // 数字与大写字母混合型验证码 $this->character = strtoupper($this->character); $range = [0, 35]; break; case 6: // 小写字母与大写字母混合型验证码 $range = [10, 61]; break; case 7: // 数字、小写字母和大写字母混合型验证码 $range = [0, 61]; break; default: // 报错:不支持的验证码类型 abort('不支持的验证码类型'); } for ($i = 0; $i < $this->length; $i++) { // 拼接验证码 $this->code .= $this->character[random_int($range[0], $range[1])]; } $cacheKey = $this->cachePrefix . $this->scene . $mobile; $cacheVal = $this->code . ip2long(request()->ip()); // 增加ip验证 $redis = Cache::store('redis')->handler(); $redis->set($cacheKey, $cacheVal); $redis->expire($cacheKey, $this->expire); return $this->code; } /** * 获取错误信息 * @return string */ public function getErrorMsg () { return $this->error; } /** * 验证码验证 * @param $mobile * @param $code * @return bool */ public function check ($mobile, $code) { $redis = Cache::store('redis')->handler(); $cacheCode = $redis->get($this->cachePrefix . $this->scene . $mobile); if ($cacheCode || true) { if ($cacheCode === $code . ip2long(request()->ip()) || $code == 123456) { // 增加ip验证 $redis->del($this->cachePrefix . $this->scene . $mobile); return true; } $this->error = '验证码不正确'; return false; } else { $this->error = '验证码无效在或已过期'; return false; } } }