CheckCodeHandler.php 3.0 KB

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