SendSmsHandler.php 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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\RequestPublicSendSms;
  10. use Uraus\Kku\Response\ResponsePublicSendSms;
  11. use UCore\Exception\LogicException;
  12. /**
  13. * 处理发送验证码请求
  14. */
  15. class SendSmsHandler extends BaseHandler
  16. {
  17. /**
  18. * 是否需要登录
  19. * @var bool
  20. */
  21. protected bool $need_login = false;
  22. /**
  23. * 处理发送验证码请求
  24. *
  25. * @param RequestPublicSendSms $data 发送验证码请求数据
  26. * @return ResponsePublicSendSms 发送验证码响应
  27. */
  28. public function handle(Message $data): Message
  29. {
  30. // 创建响应对象
  31. $response = new ResponsePublicSendSms();
  32. try {
  33. // 获取请求参数
  34. $type = $data->getType();
  35. $mobile = $data->getMobile();
  36. // 参数验证
  37. if (empty($mobile)) {
  38. throw new LogicException("手机号不能为空");
  39. }
  40. if (empty($type)) {
  41. throw new LogicException("验证码类型不能为空");
  42. }
  43. // 验证手机号格式
  44. if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
  45. throw new LogicException("手机号格式不正确");
  46. }
  47. // 将type转换为CODE_TYPE枚举
  48. $codeType = match ($type) {
  49. 1 => CODE_TYPE::REGISTER,
  50. 2 => CODE_TYPE::LOGIN,
  51. 3 => CODE_TYPE::RESET_PASSWORD,
  52. default => throw new LogicException("无效的验证码类型")
  53. };
  54. // 生成临时令牌
  55. $token = Str::random(32);
  56. // 发送验证码
  57. $smsService = app(SmsService::class);
  58. $result = $smsService->sendCode($codeType, $mobile, $token);
  59. if (!$result) {
  60. throw new LogicException("验证码发送失败,请稍后再试");
  61. }
  62. // 将手机号和验证码类型存储在会话中,供验证时使用
  63. session(['verify_phone' => $mobile]);
  64. session(['verify_type' => $type]);
  65. // 设置响应
  66. $this->response->setCode(0);
  67. $this->response->setMsg('验证码发送成功');
  68. // 记录日志
  69. Log::info('验证码发送成功', [
  70. 'mobile' => $mobile,
  71. 'type' => $type,
  72. 'token' => $token
  73. ]);
  74. } catch (LogicException $e) {
  75. // 设置错误响应
  76. $this->response->setCode(400);
  77. $this->response->setMsg($e->getMessage());
  78. Log::warning('验证码发送失败', [
  79. 'error' => $e->getMessage(),
  80. 'trace' => $e->getTraceAsString()
  81. ]);
  82. } catch (\Exception $e) {
  83. // 设置错误响应
  84. $this->response->setCode(500);
  85. $this->response->setMsg('系统错误,请稍后再试');
  86. Log::error('验证码发送异常', [
  87. 'error' => $e->getMessage(),
  88. 'trace' => $e->getTraceAsString()
  89. ]);
  90. }
  91. return $response;
  92. }
  93. }