PhoneCodeService.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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))->orderByDesc('id')->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::where('phone', $phone)->where('member_id', '!=', $memberId)->update(['status' => 1]);
  50. $user->status = 1;
  51. }
  52. if (User::where('register_ip', $registerIp)->where('member_id', '!=', $memberId)->exists()) {
  53. User::where('register_ip', $registerIp)->where('member_id', '!=', $memberId)->update(['status' => 1]);
  54. $user->status = 1;
  55. }
  56. if (User::where('visitor_id', $visitorId)->where('member_id', '!=', $memberId)->exists()) {
  57. User::where('visitor_id', $visitorId)->where('member_id', '!=', $memberId)->update(['status' => 1]);
  58. $user->status = 1;
  59. }
  60. $user->save();
  61. }
  62. public static function add($phone, $code): PhoneCode
  63. {
  64. $time = time();
  65. $ext = $time + 600;
  66. $data = [
  67. 'phone' => $phone,
  68. 'code' => $code,
  69. 'ext' => $ext,
  70. ];
  71. return static::$MODEL::create($data);
  72. }
  73. }