TelegramTrait.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App\Http\Traits;
  3. use Illuminate\Support\Facades\Http;
  4. use App\Models\User;
  5. //use App\Models\OrderPayment;
  6. use Telegram\Bot\Api;
  7. trait TelegramTrait
  8. {
  9. /**
  10. * 로그인 알림
  11. */
  12. protected function sendMessageToLogin(User $user)
  13. {
  14. $this->sendMessage(4,
  15. sprintf("[로그인]\n이메일 : %s\n이름 : %s", $user->email, $user->name)
  16. );
  17. }
  18. /**
  19. * 회원가입 알림
  20. */
  21. protected function sendMessageToRegister(User $user)
  22. {
  23. $this->sendMessage(4,
  24. sprintf("[회원가입]\n이메일 : %s\n이름 : %s\n생년월일 : %s", $user->email, $user->name, $user->birthday)
  25. );
  26. }
  27. /**
  28. * 주문 알림
  29. */
  30. // protected function sendMessageToOrder(OrderPayment $orderPayment)
  31. // {
  32. // $this->sendMessage(1,
  33. // sprintf("[상품 주문]\n주문 ID: %d\n주문자 : %s\n가격 : %s", $orderPayment->orderID, $orderPayment->buyer_name, number_format($orderPayment->order_price) . '원')
  34. // );
  35. // }
  36. /**
  37. * 텔레그램 알림 메시지
  38. */
  39. protected function sendMessage(int $room, string $msg): bool
  40. {
  41. $token = match ($room) {
  42. // G2A Order Bot Token
  43. 1 => config('g2a_order_bot_token'),
  44. // G2A Product Bot Token
  45. 2 => config('g2a_product_bot_token'),
  46. // G2A Error Bot Token
  47. 3 => config('g2a_error_bot_token'),
  48. // Main Bot Token
  49. 4 => config('main_bot_token')
  50. };
  51. if (!$token) {
  52. return false;
  53. }
  54. $api = new Api($token);
  55. if (!$api->getAccessToken()) {
  56. return false;
  57. }
  58. $chatID = null;
  59. $updates = $api->getUpdates();
  60. if($updates) {
  61. $chatID = last($updates)?->getChat()?->get('id');
  62. }
  63. if(!$chatID) {
  64. $chatID = 650107127;
  65. }
  66. $url = sprintf('https://api.telegram.org/bot%s/sendMessage?chat_id=%d&text=%s', $token, $chatID, $msg);
  67. $response = Http::timeout(60)->retry(3, 100)->get($url);
  68. unset($token, $api, $chatID, $url);
  69. return $response->ok();
  70. }
  71. }