PublicService.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace App\Services;
  3. use App\Constants\HttpStatus;
  4. use App\Models\User;
  5. use Exception;
  6. use Illuminate\Support\Facades\App;
  7. class PublicService extends BaseService
  8. {
  9. public static function init($telegram, $data, $chatId, $firstName, $messageId): void
  10. {
  11. switch ($data) {
  12. case "message@@close"://关闭本条消息
  13. $telegram->deleteMessage(['chat_id' => $chatId, 'message_id' => $messageId]);
  14. break;
  15. }
  16. }
  17. /**
  18. * 获取Tg用户的 id 昵称 用户名
  19. * @param $message
  20. * @param $from
  21. * @return array
  22. */
  23. public static function getChatInfo($message, $from): array
  24. {
  25. $chatId = $message->chat->id;
  26. $firstName = $message->chat->firstName;
  27. $username = '';
  28. if (!$from->isBot) {
  29. $chatId = $from->id;
  30. $firstName = $from->firstName;
  31. $username = $from->username;
  32. }
  33. return [$chatId, $firstName, $username];
  34. }
  35. /**
  36. * 设置用户的访客ID
  37. * @param $memberId string 会员编号
  38. * @param $visitorId string 访客ID
  39. * @return void
  40. * @throws Exception
  41. */
  42. public static function setVisitorId(string $memberId, string $visitorId): void
  43. {
  44. try {
  45. $user = User::where('member_id', $memberId)->first();
  46. if (!$user) throw new Exception('验证失败', HttpStatus::CUSTOM_ERROR);
  47. if (empty($user->visitor_id)) {
  48. if (User::where('visitor_id', $visitorId)->exists()) {
  49. User::where('visitor_id', $visitorId)->update(['status' => 1]);
  50. $user->status = 1;
  51. }
  52. $user->visitor_id = $visitorId;
  53. }
  54. if (empty($user->register_ip)) {
  55. $registerIp = request()->ip();
  56. if (User::where('register_ip', $registerIp)->exists()) {
  57. User::where('register_ip', $registerIp)->update(['status' => 1]);
  58. $user->status = 1;
  59. }
  60. $user->register_ip = $registerIp;
  61. }
  62. $user->save();
  63. } catch (Exception $e) {
  64. throw new Exception('验证失败', HttpStatus::CUSTOM_ERROR);
  65. }
  66. }
  67. /**
  68. * 用户初始化 (用户注册)/ 更新用户昵称
  69. * @param $chatId
  70. * @param $username
  71. * @param $firstName
  72. * @return User
  73. */
  74. public static function index($chatId, $username, $firstName): User
  75. {
  76. //给每个用户生成一个专属的钱包
  77. WalletService::getUserWallet($chatId);
  78. $user = User::where('member_id', $chatId)->first();
  79. if (!$user) $user = new User();
  80. $user->member_id = $chatId;
  81. $user->first_name = $firstName;
  82. if ($username) $user->username = $username;
  83. $user->save();
  84. return $user;
  85. }
  86. public static function getWhere(array $search = []): array
  87. {
  88. // TODO: Implement getWhere() method.
  89. return [];
  90. }
  91. }