| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- <?php
- namespace App\Module\AppGame\Handler\Public;
- use App\Module\AppGame\Handler\BaseHandler;
- use App\Module\Sms\Enums\CODE_TYPE;
- use App\Module\Sms\Services\SmsService;
- use Google\Protobuf\Internal\Message;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Str;
- use Uraus\Kku\Request\RequestPublicCheckCode;
- use Uraus\Kku\Response\ResponsePublicCheckCode;
- use UCore\Exception\LogicException;
- /**
- * 处理验证码校验请求
- */
- class CheckCodeHandler extends BaseHandler
- {
- /**
- * 是否需要登录
- * @var bool
- */
- protected bool $need_login = false;
- /**
- * 处理验证码校验请求
- *
- * @param RequestPublicCheckCode $data 验证码校验请求数据
- * @return ResponsePublicCheckCode 验证码校验响应
- */
- public function handle(Message $data): Message
- {
- // 创建响应对象
- $response = new ResponsePublicCheckCode();
- try {
- // 获取请求参数
- $code = $data->getCode();
- // 参数验证
- if (empty($code)) {
- throw new LogicException("验证码不能为空");
- }
- // 从会话中获取手机号和验证码类型
- $phone = session('verify_phone');
- $type = session('verify_type');
- if (empty($phone)) {
- throw new LogicException("请先发送验证码");
- }
- if (empty($type)) {
- throw new LogicException("验证码类型无效");
- }
- // 将type转换为CODE_TYPE枚举
- $codeType = match ((int)$type) {
- 1 => CODE_TYPE::REGISTER,
- 2 => CODE_TYPE::LOGIN,
- 3 => CODE_TYPE::RESET_PASSWORD,
- default => throw new LogicException("无效的验证码类型")
- };
- // 验证验证码
- $smsService = app(SmsService::class);
- $isValid = $smsService->verifyCode($codeType, $phone, $code);
- if (!$isValid) {
- throw new LogicException("验证码无效或已过期");
- }
- // 生成临时令牌
- $token = Str::random(32);
- // 将令牌与手机号关联并存储在会话中
- session(['verify_token' => $token]);
- session(['verified_phone' => $phone]);
- // 设置响应
- $response->setToken($token);
- $this->response->setCode(0);
- $this->response->setMsg('验证码验证成功');
- // 记录日志
- Log::info('验证码验证成功', [
- 'phone' => $phone,
- 'type' => $type,
- 'token' => $token
- ]);
- } catch (LogicException $e) {
- // 设置错误响应
- $this->response->setCode(400);
- $this->response->setMsg($e->getMessage());
- Log::warning('验证码验证失败', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- } catch (\Exception $e) {
- // 设置错误响应
- $this->response->setCode(500);
- $this->response->setMsg('系统错误,请稍后再试');
- Log::error('验证码验证异常', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- }
- return $response;
- }
- }
|