CheckCodeHandler.php 3.1 KB

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