PhoneCodeService.php 2.3 KB

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