| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- <?php
- namespace App\Module\AppGame\Handler\Public;
- use App\Module\AppGame\Handler\BaseHandler;
- use App\Module\Sms\Enums\CODE_TYPE;
- use App\Module\Sms\Services\SmsService;
- use Google\Protobuf\Internal\Message;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Str;
- use Uraus\Kku\Request\RequestPublicSendSms;
- use Uraus\Kku\Response\ResponsePublicSendSms;
- use UCore\Exception\LogicException;
- /**
- * 处理发送验证码请求
- */
- class SendSmsHandler extends BaseHandler
- {
- /**
- * 是否需要登录
- * @var bool
- */
- protected bool $need_login = false;
- /**
- * 处理发送验证码请求
- *
- * @param RequestPublicSendSms $data 发送验证码请求数据
- * @return ResponsePublicSendSms 发送验证码响应
- */
- public function handle(Message $data): Message
- {
- // 创建响应对象
- $response = new ResponsePublicSendSms();
- try {
- // 获取请求参数
- $type = $data->getType();
- $mobile = $data->getMobile();
- // 参数验证
- if (empty($mobile)) {
- throw new LogicException("手机号不能为空");
- }
- if (empty($type)) {
- throw new LogicException("验证码类型不能为空");
- }
- // 验证手机号格式
- if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
- throw new LogicException("手机号格式不正确");
- }
- // 将type转换为CODE_TYPE枚举
- $codeType = match ($type) {
- 1 => CODE_TYPE::REGISTER,
- 2 => CODE_TYPE::LOGIN,
- 3 => CODE_TYPE::RESET_PASSWORD,
- default => throw new LogicException("无效的验证码类型")
- };
- // 生成临时令牌
- $token = Str::random(32);
- // 发送验证码
- $smsService = app(SmsService::class);
- $result = $smsService->sendCode($codeType, $mobile, $token);
- if (!$result) {
- throw new LogicException("验证码发送失败,请稍后再试");
- }
- // 将手机号和验证码类型存储在会话中,供验证时使用
- session(['verify_phone' => $mobile]);
- session(['verify_type' => $type]);
- // 设置响应
- $this->response->setCode(0);
- $this->response->setMsg('验证码发送成功');
- // 记录日志
- Log::info('验证码发送成功', [
- 'mobile' => $mobile,
- 'type' => $type,
- 'token' => $token
- ]);
- } catch (LogicException $e) {
- // 设置错误响应
- $this->response->setCode(400);
- $this->response->setMsg($e->getMessage());
- Log::warning('验证码发送失败', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- } catch (\Exception $e) {
- // 设置错误响应
- $this->response->setCode(500);
- $this->response->setMsg('系统错误,请稍后再试');
- Log::error('验证码发送异常', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- }
- return $response;
- }
- }
|