getCacheKey($mobile, 'interval'); if (Cache::get($intervalKey)) { throw new Exception('发送太频繁,请稍后再试'); } try { // 这里调用具体的短信发送接口 $result = $this->sendSms($mobile, $code); if (!$result) { throw new Exception('短信发送失败'); } // 缓存验证码 $codeKey = $this->getCacheKey($mobile); Cache::set($codeKey, $code, self::CODE_EXPIRE); // 设置发送间隔 Cache::set($intervalKey, 1, self::SEND_INTERVAL); return [ 'mobile' => $mobile, 'expire' => self::CODE_EXPIRE ]; } catch (\Exception $e) { throw new Exception('短信发送失败:' . $e->getMessage()); } } /** * 验证码验证 * @param string $mobile * @param string $code * @return bool * @throws Exception */ public function check(string $mobile, string $code): bool { if (empty($mobile) || empty($code)) { throw new Exception('手机号和验证码不能为空'); } $codeKey = $this->getCacheKey($mobile); $cacheCode = Cache::get($codeKey); if (!$cacheCode) { throw new Exception('验证码已过期'); } if ($cacheCode !== $code) { throw new Exception('验证码错误'); } // 验证成功后删除缓存 Cache::rm($codeKey); return true; } /** * 发送短信 * @param string $mobile * @param string $code * @return bool */ protected function sendSms(string $mobile, string $code): bool { // 这里实现具体的短信发送逻辑 // 可以对接阿里云、腾讯云等短信服务 // 示例使用阿里云短信服务 try { $config = [ 'access_key_id' => config('site.sms.access_key_id'), 'access_key_secret' => config('site.sms.access_key_secret'), 'sign_name' => config('site.sms.sign_name'), 'template_code' => config('site.sms.template_code') ]; // 测试环境直接返回true return true; } catch (\Exception $e) { // 记录日志 \think\Log::error('短信发送失败:' . $e->getMessage()); return false; } } }