PhoneCodeService.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 = [
  36. 'phone' => $phone,
  37. 'code' => $code,
  38. ];
  39. $phoneCode = static::$MODEL::where(static::getWhere($search))->first();
  40. if (!$phoneCode) throw new Exception("验证码错误", HttpStatus::CUSTOM_ERROR);
  41. $time = time();
  42. if ($phoneCode->ext < $time) throw new Exception("验证码过期", HttpStatus::CUSTOM_ERROR);
  43. $user = UserService::findOne(['member_id' => $memberId]);
  44. if (!$user) throw new Exception('用户不存在', HttpStatus::CUSTOM_ERROR);
  45. $registerIp = request()->ip();
  46. $user->register_ip = $registerIp;
  47. $user->phone = $phone;
  48. $user->visitor_id = $visitorId;
  49. if (User::where('phone', $phone)->where('member_id', '!=', $memberId)->exists()) {
  50. $user->status = 1;
  51. }
  52. if (User::where('register_ip', $registerIp)->where('member_id', '!=', $memberId)->exists()) {
  53. $user->status = 1;
  54. }
  55. if (User::where('visitor_id', $visitorId)->where('member_id', '!=', $memberId)->exists()) {
  56. $user->status = 1;
  57. }
  58. $user->save();
  59. }
  60. public static function add($phone, $code): PhoneCode
  61. {
  62. $time = time();
  63. $ext = $time + 600;
  64. $data = [
  65. 'phone' => $phone,
  66. 'code' => $code,
  67. 'ext' => $ext,
  68. ];
  69. return static::$MODEL::create($data);
  70. }
  71. }