CheckCodeHandler.php 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. namespace App\Module\AppGame\Handler\Public;
  3. use App\Module\AppGame\Handler\BaseHandler;
  4. use App\Module\Sms\Enums\CODE_TYPE;
  5. use App\Module\Sms\Services\SmsService;
  6. use Google\Protobuf\Internal\Message;
  7. use Illuminate\Support\Facades\Log;
  8. use Illuminate\Support\Str;
  9. use Uraus\Kku\Request\RequestPublicCheckCode;
  10. use Uraus\Kku\Response\ResponsePublicCheckCode;
  11. use UCore\Exception\LogicException;
  12. /**
  13. * 处理验证码校验请求
  14. */
  15. class CheckCodeHandler extends BaseHandler
  16. {
  17. /**
  18. * 是否需要登录
  19. * @var bool
  20. */
  21. protected bool $need_login = false;
  22. /**
  23. * 处理验证码校验请求
  24. *
  25. * @param RequestPublicCheckCode $data 验证码校验请求数据
  26. * @return ResponsePublicCheckCode 验证码校验响应
  27. */
  28. public function handle(Message $data): Message
  29. {
  30. // 创建响应对象
  31. $response = new ResponsePublicCheckCode();
  32. try {
  33. // 获取请求参数
  34. $code = $data->getCode();
  35. // 参数验证
  36. if (empty($code)) {
  37. throw new LogicException("验证码不能为空");
  38. }
  39. // 从会话中获取手机号和验证码类型
  40. $phone = session('verify_phone');
  41. $type = session('verify_type');
  42. if (empty($phone)) {
  43. throw new LogicException("请先发送验证码");
  44. }
  45. if (empty($type)) {
  46. throw new LogicException("验证码类型无效");
  47. }
  48. // 将type转换为CODE_TYPE枚举
  49. $codeType = match ((int)$type) {
  50. 1 => CODE_TYPE::REGISTER,
  51. 2 => CODE_TYPE::LOGIN,
  52. 3 => CODE_TYPE::RESET_PASSWORD,
  53. default => throw new LogicException("无效的验证码类型")
  54. };
  55. // 验证验证码
  56. $smsService = app(SmsService::class);
  57. $isValid = $smsService->verifyCode($codeType, $phone, $code);
  58. if (!$isValid) {
  59. throw new LogicException("验证码无效或已过期");
  60. }
  61. // 生成临时令牌
  62. $token = Str::random(32);
  63. // 将令牌与手机号关联并存储在会话中
  64. session(['verify_token' => $token]);
  65. session(['verified_phone' => $phone]);
  66. // 设置响应
  67. $response->setToken($token);
  68. $this->response->setCode(0);
  69. $this->response->setMsg('验证码验证成功');
  70. // 记录日志
  71. Log::info('验证码验证成功', [
  72. 'phone' => $phone,
  73. 'type' => $type,
  74. 'token' => $token
  75. ]);
  76. } catch (LogicException $e) {
  77. // 设置错误响应
  78. $this->response->setCode(400);
  79. $this->response->setMsg($e->getMessage());
  80. Log::warning('验证码验证失败', [
  81. 'error' => $e->getMessage(),
  82. 'trace' => $e->getTraceAsString()
  83. ]);
  84. } catch (\Exception $e) {
  85. // 设置错误响应
  86. $this->response->setCode(500);
  87. $this->response->setMsg('系统错误,请稍后再试');
  88. Log::error('验证码验证异常', [
  89. 'error' => $e->getMessage(),
  90. 'trace' => $e->getTraceAsString()
  91. ]);
  92. }
  93. return $response;
  94. }
  95. }