PhoneCodeService.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace App\Services;
  3. use App\Constants\HttpStatus;
  4. use App\Models\PhoneCode;
  5. use App\Models\User;
  6. use Exception;
  7. class PhoneCodeService extends BaseService
  8. {
  9. public static string $MODEL = PhoneCode::class;
  10. public static function getWhere(array $search = []): array
  11. {
  12. $where = [];
  13. if (isset($search['phone']) && !empty($search['phone'])) {
  14. $where[] = ['phone', '=', $search['phone']];
  15. }
  16. if (isset($search['code']) && !empty($search['code'])) {
  17. $where[] = ['code', '=', $search['code']];
  18. }
  19. return $where;
  20. }
  21. public static function findOne(array $search = []): ?PhoneCode
  22. {
  23. return self::$MODEL::where(static::getWhere($search))->first();
  24. }
  25. /**
  26. * @param $phone
  27. * @param $code
  28. * @param $memberId
  29. * @param $visitorId
  30. * @return void
  31. * @throws Exception
  32. */
  33. public static function verify($phone, $code, $memberId, $visitorId): void
  34. {
  35. $search = ['phone' => $phone, 'code' => $code];
  36. $phoneCode = static::$MODEL::where(static::getWhere($search))->first();
  37. if (!$phoneCode) throw new Exception("验证码错误", HttpStatus::CUSTOM_ERROR);
  38. $time = time();
  39. if ($phoneCode->ext < $time) throw new Exception("验证码过期", HttpStatus::CUSTOM_ERROR);
  40. $phoneCode->status = 1;
  41. $phoneCode->save();
  42. $user = UserService::findOne(['member_id' => $memberId]);
  43. if (!$user) throw new Exception('用户不存在', HttpStatus::CUSTOM_ERROR);
  44. $registerIp = request()->ip();
  45. $user->register_ip = $registerIp;
  46. $user->phone = $phone;
  47. $user->visitor_id = $visitorId;
  48. if (User::where('phone', $phone)->where('member_id', '!=', $memberId)->exists()) {
  49. $user->status = 1;
  50. }
  51. if (User::where('register_ip', $registerIp)->where('member_id', '!=', $memberId)->exists()) {
  52. $user->status = 1;
  53. }
  54. if (User::where('visitor_id', $visitorId)->where('member_id', '!=', $memberId)->exists()) {
  55. $user->status = 1;
  56. }
  57. $user->save();
  58. }
  59. public static function add($phone, $code): PhoneCode
  60. {
  61. $time = time();
  62. $ext = $time + 600;
  63. $data = [
  64. 'phone' => $phone,
  65. 'code' => $code,
  66. 'ext' => $ext,
  67. ];
  68. return static::$MODEL::create($data);
  69. }
  70. }