SendSmsHandler.php 3.0 KB

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