SmsService.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /**
  3. * @Name
  4. * @Description
  5. * @Author 刘学玺
  6. * @Date 2024/3/25 11:38
  7. */
  8. namespace App\Http\Services\Frontend\Client\Common;
  9. use App\Exceptions\ApiException;
  10. use App\Http\Services\Service;
  11. use App\Models\Member\User;
  12. class SmsService extends Service
  13. {
  14. /**
  15. * Notes :
  16. * Method : Interface send
  17. * @param $mobile
  18. * @param int $category 0-注册 1-登录 2-忽略类型
  19. * @throws ApiException
  20. */
  21. public function send($mobile, int $category = 0): void
  22. {
  23. $where = ['mobile' => $mobile];
  24. $exists = User::query()->where($where)->exists();
  25. $category === 1 && !$exists && self::error('用户不存在!',404);
  26. $category === 0 && $exists && self::error('用户已存在!', 409);
  27. // 检测短信发送间隔
  28. // 生成验证码
  29. $code = 123456;
  30. // 发送短信
  31. // 判断发送结果
  32. // 缓存验证码
  33. $this->save($mobile, $code);
  34. }
  35. /**
  36. * Notes :
  37. * Method : 验证手机验证码并清除缓存
  38. * @param $mobile
  39. * @param $code
  40. * @return bool
  41. */
  42. public function verifyCode($mobile, $code): bool
  43. {
  44. $correctCode = cache('mobile_verification_code_' . $mobile);
  45. $isValid = $correctCode === $code;
  46. $isValid && cache(['mobile_verification_code_' . $mobile => 0], 0);
  47. return $isValid;
  48. }
  49. /**
  50. * Notes :
  51. * Method : 使用缓存保存手机验证码
  52. * @param $mobile
  53. * @param $code
  54. */
  55. protected function save($mobile, $code): void
  56. {
  57. $sms_expires_time = env('SMS_EXPIRES_TIME', 10);
  58. $expiresAt = now()->addMinutes(floatval($sms_expires_time)); // 设置验证码有效期为10分钟
  59. cache(['mobile_verification_code_' . $mobile => $code], $expiresAt);
  60. }
  61. }